//
//  YHSpouseInfoVC.swift
//  galaxy
//
//  Created by edy on 2024/1/31.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

@objc protocol YHSpouseInfoVCProtocol: NSObjectProtocol {
    
    @objc func updateStepView()
    // 静默保存数据(不显示toast)
    @objc func saveInfoSilent()
}

@objc protocol YHFamilyMemberProtol: NSObjectProtocol {
    @objc func nextStep() -> Bool
    @objc func loadInfo()
}

class YHFaimilyStepItem {
    
    typealias YHFamilyStepVC = UIViewController & YHFamilyMemberProtol
    var title: String = ""
    var vc: YHFamilyStepVC
    var step: Int = -1
    init(title: String, vc: YHFamilyStepVC, step: Int) {
        self.title = title
        self.vc = vc
        self.step = step
    }
}

class YHSpouseInfoContainerVC: YHBaseViewController, YHSpouseInfoVCProtocol {

    let familyRequest: YHFamilyRequestViewModel = YHFamilyRequestViewModel()
    var stepVCs: [YHFaimilyStepItem] = []
    var orderId: Int = 0

    var spouse: YHFamilyMember? {
        didSet {
            if let spouse = spouse {
                primaryInfoVC.spouse = spouse
                uploadVC.familyMember = spouse
                certificateVC.familyMember = spouse
                basicInfoVC.spouse = spouse
            }
        }
    }
    
    var mainApplicantInfo: YHMyMainApplicantInfoModel? {
        didSet {
            if let mainApplicantInfo = mainApplicantInfo {
                primaryInfoVC.mainApplicantInfo = mainApplicantInfo
                uploadVC.mainApplicantInfo = mainApplicantInfo
                certificateVC.mainApplicantInfo = mainApplicantInfo
            }
        }
    }
    
    var _currentStep = 0
    var currentStep: Int {
        
        get {
            return _currentStep
        }
        
        set {
            
            if let spouse = spouse, !spouse.isFollow(), newValue > 0 {
                _currentStep = 3
            } else {
                _currentStep = newValue
            }
            
            let index = getArrayIndexOfCurrentStep()
            if let index = index {
                stepView.currentIndex = index
                bottomView.changeRightBtnTitle(index == stepVCs.count-1 ? "提交".local : "下一步".local)
            }
            for vcItem in stepVCs {
                vcItem.vc.view.isHidden = (vcItem.step != currentStep)
                if vcItem.step == currentStep {
                    // 刷新
                    if vcItem.vc.responds(to: #selector(YHFamilyMemberProtol.loadInfo)) {
                        vcItem.vc.loadInfo()
                    }
                }
            }
        }
    }
    
    var stepView: YHStepView = {
        let stepV = YHStepView()
        return stepV
    }()
    
    var bottomView: YHSaveAndSubmitView = {
        let view = YHSaveAndSubmitView.createView()
        view.changeRightBtnTitle("下一步")
        return view
    }()
        
    let primaryInfoVC =  YHSpousePrimaryInfoVC()
    let uploadVC = YHCertificateUploadVC()
    let certificateVC = YHCertificateInfoController()
    let basicInfoVC = YHSpouseBasicInfoVC()

    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "配偶信息填写".local
        gk_navigationBar.backgroundColor = .white
        view.backgroundColor = UIColor(hexString: "#F8F8F8")
        createUI()
    }
    
    func createUI() {
        
        guard let spouse = spouse else { return }
    
        primaryInfoVC.delegate = self
        uploadVC.delegate = self
        certificateVC.delegate = self
        basicInfoVC.delegate = self
        
        view.addSubview(stepView)
        view.addSubview(bottomView)
        
        updateStepView()
        print("step:\(spouse.step)")
        currentStep = spouse.step
        stepView.maxIndex = getArrayIndexOfCurrentStep() ?? stepVCs.count-1
        
        bottomView.submitBlock = {
            [weak self] in
            guard let self = self else { return }
            submit()
        }
        
        bottomView.saveBlock = {
            [weak self] in
            guard let self = self else { return }
            saveInfo(isSubmit: false, isShowSubmitMsg: false, isLoading: true, callBack: nil)
        }
        
        stepView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.equalTo(view)
            make.height.equalTo(YHStepView.height)
        }
        
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(YHSaveAndSubmitView.height)
        }
    }
    
    func updateStepView() {
        
        guard let spouse = spouse else { return }
        
        for vc in self.children {
            vc.willMove(toParent: nil)
            vc.removeFromParent()
            vc.view.removeFromSuperview()
        }
        
        print(self.children)
        
        if spouse.isFollow() {
            
            stepVCs = [ YHFaimilyStepItem(title: "初始信息".local, vc: primaryInfoVC, step: 0),
                        YHFaimilyStepItem(title: "证件上传".local, vc: uploadVC, step: 1),
                        YHFaimilyStepItem(title: "证件信息".local, vc: certificateVC, step: 2),
                        YHFaimilyStepItem(title: "基本信息".local, vc: basicInfoVC, step: 3)]
            
        } else {
            
            stepVCs = [ YHFaimilyStepItem(title: "初始信息".local, vc: primaryInfoVC, step: 0),
                        YHFaimilyStepItem(title: "基本信息".local, vc: basicInfoVC, step: 3)]
        }
        
        var titles: [String] = []
        for vcItem in stepVCs {
            let topHeight = k_Height_NavigationtBarAndStatuBar+YHStepView.height
            let bottomHeight = YHSaveAndSubmitView.height
            vcItem.vc.view.frame = CGRect(x: 0, y: topHeight, width: KScreenWidth, height: KScreenHeight-topHeight-bottomHeight)
            self.addChild(vcItem.vc)
            self.view.addSubview(vcItem.vc.view)
            titles.append(vcItem.title)
        }
        
        stepView.dataSource = titles
        // 数据源可能会变，所以需要重新设置step
        let step = currentStep
        currentStep = step
        
        stepView.block = {
            [weak self] index in
            guard let self = self else { return }
            if let targetStep = getStepForArrayIndex(index) {
                currentStep = targetStep
            }
            requestDetail()
            print("index:\(index)")
        }
        
        self.view.bringSubviewToFront(stepView)
        self.view.bringSubviewToFront(bottomView)

    }
}

extension YHSpouseInfoContainerVC {
    
    // isSubmit:是否为提交 false为保存 true为提交
    func saveInfo(isSubmit: Bool, isShowSubmitMsg: Bool, isLoading: Bool, callBack: ((Bool) -> Void)?) {
        
        guard  let spouse = spouse else { return }
        
        guard let info = spouse.toDictionary() else { return }
        
        let dict: [String: Any] = ["order_id": orderId,
                                  "relation": spouse.relation,
                                  "step": currentStep,
                                  "next": isSubmit,
                                  "info": info]
        
        self.familyRequest.addOrSaveFamilyMember(params: dict, isShowLoading: isLoading) {
            success, error in
            if isLoading {
                if success {
                    YHHUD.flash(message: isSubmit && isShowSubmitMsg ? "提交成功" : "保存成功")
                } else {
                    var msg = isSubmit && isShowSubmitMsg ? "提交失败" : "保存失败"
                    if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                        msg = errorMsg
                    }
                    YHHUD.flash(message: msg)
                }
            }
            if let callBack = callBack {
                callBack(success)
            }
        }
    }
    
    func saveInfoSilent() {
        saveInfo(isSubmit: false, isShowSubmitMsg: false, isLoading: false) {
           [weak self] _ in
           
        }
    }
    
    func submit() {
        if let targetVC = getCurrentStepViewController() {
            if targetVC.nextStep() {
                
                var isShowSubmitMsg = false
                let index = getArrayIndexOfCurrentStep()
                if let index = index, index == stepVCs.count-1 {
                    // 最后一步
                    isShowSubmitMsg = true
                }
                
                saveInfo(isSubmit: true, isShowSubmitMsg: isShowSubmitMsg, isLoading: true) {
                    [weak self] success in
                    guard let self = self else { return }
                    if success {
                        // 当前步骤已是最后一步
                        if let vc = stepVCs.last, vc.step == currentStep {
                            self.navigationController?.popViewController()
                            return
                        }
                        requestDetail()
                        if let cur = getArrayIndexOfCurrentStep(), let item = stepVCs[safe: cur+1] {
                            currentStep = item.step
                            if cur+1 > stepView.maxIndex {
                                stepView.maxIndex = cur+1
                            }
                        }
                        print("currentIndex:\(currentStep)")
                    }
                }
            }
        }
    }
    
    func requestDetail() {
        if orderId <= 0 {
            print("订单号不存在")
            return
        }
        self.familyRequest.requestFamilyMemberDetailInfo(memberType: .spouse, orderId: orderId) { 
            [weak self] detail in
            guard let self = self else { return }
            if let detail = detail {
                self.spouse = detail
                for vcItem in stepVCs {
                    vcItem.vc.loadInfo()
                }
            }
        }
    }
    
    // 【WARNING!】步骤step和在数组中的下标有时候并不是一一对应
    func getArrayIndexOfCurrentStep() -> Int? {
        for (i, item) in stepVCs.enumerated() {
            if item.step == currentStep {
                return i
            }
        }
        return nil
    }
    
    // 【WARNING!】步骤step和在数组中的下标有时候并不是一一对应
    func getStepForArrayIndex(_ index: Int) -> Int? {
        if let targetVCItem = stepVCs[safe: index] {
            return targetVCItem.step
        }
        return nil
    }
    
    func getCurrentStepViewController() -> (UIViewController & YHFamilyMemberProtol)? {
        
        for vcItem in stepVCs {
            if vcItem.step == currentStep {
                return vcItem.vc
            }
        }
        return nil
    }
}
