//
//  YHChildInfoContainerVC.swift
//  galaxy
//
//  Created by edy on 2024/2/5.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

//@objc protocol YHchildInfoVCProtocol {
//    
//    @objc optional func updateStepView()
//    @objc optional func saveInfo()
//}

class YHChildInfoContainerVC: YHBaseViewController, YHSpouseInfoVCProtocol {

    let familyRequest:YHFamilyRequestViewModel = YHFamilyRequestViewModel()

    var orderId:Int = 0

    var child:YHFamilyMember? {
        didSet {
            primaryInfoVC.child = child
            uploadVC.familyMember = child
            certificateVC.familyMember = child
            basicInfoVC.child = child
        }
    }
    var stepVCs:[YHFaimilyStepItem] = []
    
    var _currentStep = 0
    var currentStep:Int {
        
        get {
            return _currentStep
        }
        
        set {
            
            if let child = child, !child.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 step = YHStepView()
        return step
    }()
    
    var bottomView: YHSaveAndSubmitView = {
        let view = YHSaveAndSubmitView.createView()
        view.changeRightBtnTitle("下一步")
        return view

    }()
        
    let primaryInfoVC =  YHChildPrimaryInfoVC()
    let uploadVC = YHCertificateUploadVC()
    let certificateVC = YHCertificateInfoController()
    let basicInfoVC = YHChildBasicInfoVC()

    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "子女信息填写".local
        createUI()
    }
    
    func createUI() {
        
        guard let child = child else { return }
        
        primaryInfoVC.delegate = self
        certificateVC.delegate = self
        basicInfoVC.delegate = self
        
        updateStepView()
        print("step:\(child.step)")
        currentStep = child.step
        stepView.maxIndex = getArrayIndexOfCurrentStep() ?? stepVCs.count-1

        
        view.addSubview(stepView)
        view.addSubview(bottomView)
        
        bottomView.submitBlock = {
            [weak self] in
            guard let self = self else { return }
            submit()
        }
        
        bottomView.saveBlock = {
            [weak self] in
            guard let self = self else { return }
            self.saveInfo(isSubmit: false, isShowLoading: 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().offset(-k_Height_safeAreaInsetsBottom())
            make.height.equalTo(YHSaveAndSubmitView.height)
        }
    }
    
    func updateStepView() {
        
        guard let child = child else { return }
        
        for vc in self.children {
            vc.willMove(toParent: nil)
            vc.removeFromParent()
            vc.view.removeFromSuperview()
        }
        
        print(self.children)
        
        if child.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 = k_Height_safeAreaInsetsBottom() + YHSaveAndSubmitView.height
            vcItem.vc.view.frame = CGRectMake(0, topHeight, KScreenWidth, KScreenHeight-topHeight-bottomHeight)
            self.addChild(vcItem.vc)
            self.view.addSubview(vcItem.vc.view)
            titles.append(vcItem.title)
        }
        stepView.dataSource = titles
        let step = currentStep
        currentStep = step

        stepView.block = {
            [weak self] index in
            guard let self = self else { return }
            if let targetStep = getStepForArrayIndex(index) {
                currentStep = targetStep
            }
            print("index:\(index)")
        }
        
        self.view.bringSubviewToFront(stepView)
        self.view.bringSubviewToFront(bottomView)

    }
    
    func submit() {
        if let targetVC = getCurrentStepViewController() {
            if targetVC.nextStep() {
                saveInfo(isSubmit: true, isShowLoading: true) {
                    [weak self] success, error in
                    guard let self = self else { return }
                    if success {
                        // 当前步骤已是最后一步
                        if let vc = stepVCs.last, vc.step == currentStep {
                            self.navigationController?.popViewController()
                            return
                        }
                        
                        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)")
                    }
                }
            }
        }
    }
    
    // 【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
    }
}

extension YHChildInfoContainerVC {
    
    // @param isSubmit:是否为提交 false为保存 true为提交
    // @param isShowLoading: 是否展示loading和toast
    func saveInfo(isSubmit:Bool, isShowLoading:Bool, callBack:((Bool, String?)->Void)?) {
        
        guard  let child = child else { return }
        guard let info = child.toDictionary() else { return }
        
        let dict:[String: Any] = ["order_id":child.orderId,
                                  "relation":child.relation,
                                  "step":isSubmit ? currentStep : 0,
                                  "next":isSubmit,
                                  "info":info]
        
        self.familyRequest.addOrSaveFamilyMember(params:dict, isShowLoading: isShowLoading) {
            [weak self] success, error in
            guard let self = self else { return }
            if isShowLoading {
                YHHUD.flash(message: success ? "保存成功" : "保存失败")
            }
            if let callBack = callBack {
                callBack(success, error?.errorMsg)
            }
        }
    }
    
    func saveInfoSilent() {
        saveInfo(isSubmit:false, isShowLoading:false, callBack:nil)
    }
}
