//
//  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 {
    
    @objc optional func updateStepView()
    @objc optional func saveInfo()
}

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

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
                certificateVC.familyMember = spouse
                basicInfoVC.spouse = spouse
            }
        }
    }
    
    var currentStep = 0 {
        didSet {
            
            let index = getArrayIndexOfCurrentStep()
            if let index = index {
                stepView.currentIndex = index
            }
            for vcItem in stepVCs {
                vcItem.vc.view.isHidden = (vcItem.step != currentStep)
            }
        }
    }
    
    var stepView:YHStepView = {
        let stepV = YHStepView()
        return stepV
    }()
    
    var bottomView: YHSaveAndSubmitView = {
        return YHSaveAndSubmitView.createView()
    }()
        
    let primaryInfoVC =  YHSpousePrimaryInfoVC()
    let uploadVC = YHCertificateUploadVC()
    let certificateVC = YHCertificateInfoController()
    let basicInfoVC = YHSpouseBasicInfoVC()

    override func viewDidLoad() {
        super.viewDidLoad()
        createUI()
    }
    
    func createUI() {
        
        guard let spouse = spouse else { return }
        
        primaryInfoVC.delegate = self
        certificateVC.delegate = self
        basicInfoVC.delegate = self
        
        view.addSubview(stepView)
        view.addSubview(bottomView)
        
        updateStepView()
        print("step:\(spouse.step)")
        currentStep = spouse.step
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(tap))
        tap.cancelsTouchesInView = false
        self.view.addGestureRecognizer(tap)
        
        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()
        }
        
        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 spouse = spouse else { return }
        
        for vc in self.children {
            vc.willMove(toParent: nil)
            vc.removeFromParent()
        }
        
        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 {
            self.addChild(vcItem.vc)
            self.view.addSubview(vcItem.vc.view)
            titles.append(vcItem.title)
        }
        
        stepView.dataSource = titles
        
        stepView.block = {
            [weak self] index in
            guard let self = self else { return }
            if let targetStep = getStepForArrayIndex(index) {
                currentStep = targetStep
            }
            print("index:\(index)")
        }
        let step = currentStep
        currentStep = step
        self.view.bringSubviewToFront(stepView)
        self.view.bringSubviewToFront(bottomView)

    }
}

extension YHSpouseInfoContainerVC {
    func saveInfo() {
        
        guard  let spouse = spouse else { return }
        guard let info = spouse.toDictionary() else { return }
        
        let dict:[String: Any] = ["orderId":spouse.orderId,
                                  "relation":spouse.relationType.rawValue,
                                  "step":spouse.step,
                                  "next":false,
                                  "info":info]
        
        self.familyRequest.addOrSaveFamilyMember(params:dict) { [weak self] success, error in
            guard let self = self else { return }
            if success {
                
            }
        }
    }
    
    func submit() {
        if let targetVC = getCurrentStepViewController() {
            if targetVC.nextStep() {
               
                // 当前步骤已是最后一步
                if let vc = stepVCs.last, vc.step == currentStep {
                    YHHUD.flash(message: "已经是最后一步！")
                    return
                }
                if let cur = getArrayIndexOfCurrentStep(), let item = stepVCs[safe:cur+1] {
                    currentStep = item.step
                }
                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 YHSpouseInfoContainerVC: UIGestureRecognizerDelegate {
    
    @objc func tap() {
        print("点击了parentViewController: YHSpouseInfoContainerVC")
    }
}
