//
//  YHResignInfoConfirmIViewModel.swift
//  galaxy
//
//  Created by edy on 2024/10/14.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHResignInfoConfirmViewModel {
    
    var listModel = YHResignInfoConfirmInfoListModel()
    var pinyinInfo: YHFamilyNamePinYin = YHFamilyNamePinYin()

    func getList(id: Int, callBack: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let params = ["id": id]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.ResignInfoConfirm.getList
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHResignInfoConfirmInfoListModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callBack(false, err)
                    return
                }
                self.listModel = resultModel
                callBack(true, nil)
                
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                self.listModel = YHResignInfoConfirmInfoListModel()
                callBack(false, err)
            }
        } failBlock: { err in
            self.listModel = YHResignInfoConfirmInfoListModel()
            callBack(false, err)
        }
    }
    
    func getList() -> [YHResignInfoConfirmFamilyInfoModel] {
        
        var results = [YHResignInfoConfirmFamilyInfoModel]()
        if let main = self.listModel.main {
            main.info.relation = YHFamilyMemberRelationType.mainApplicant.rawValue
            results.append(main)
        }
        
        if let spouse = listModel.spouse {
            spouse.info.relation = YHFamilyMemberRelationType.spouse.rawValue
            results.append(spouse)
        }
        
        for child in listModel.children {
            child.info.relation = YHFamilyMemberRelationType.child.rawValue
            results.append(child)
        }
        return results
    }
    
    // 提交信息确认修改
    func submitFamilyUpdate(param: [String: Any], callback: ((_ success: Bool, _ error: YHErrorModel?) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.ResignInfoConfirm.update
        
        _ = YHNetRequest.postRequest(url: strUrl, params: param) { json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                callback?(true, nil)
                
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    func submitAllConfirmInfo(orderId: Int, stepId: Int, callback: ((_ success: Bool, _ error: YHErrorModel?) -> Void)?) {
        
        let params: [String: Any] = ["id": stepId,
                                      "order_id": orderId]
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.ResignInfoConfirm.confirmInfo
        
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                callback?(true, nil)
                
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    func getPinYinFromName(_ name: String, callback: @escaping ((String, String) -> Void)) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.FamilyInfoConfirm.pinyinInfo
        _ = YHNetRequest.getRequest(url: strUrl, params: ["name": name]) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHFamilyNamePinYin.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback("", "")
                    return
                }
                self.pinyinInfo = resultModel
                callback(resultModel.family_name, resultModel.given_name)
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback("", "")
            }
            
        } failBlock: { _ in
            callback("", "")
        }
    }
}

extension YHResignInfoConfirmViewModel {
    
    func getInfoConfirm(_ model: YHResignInfoConfirmFamilyModel, isEditMode: Bool) -> [YHResignFamilyInfoItem] {
                
        var nameTitle = ""
        var previousNameTitle = ""
        var id = YHResignFamilyInfoType.none
        
        var resultArr = [YHResignFamilyInfoItem]()
        
        if model.relation == YHFamilyMemberRelationType.mainApplicant.rawValue {
            id = .mainApplicantName
            nameTitle = "主申人姓名"
            previousNameTitle = "原主申人姓名"
            
        } else if model.relation == YHFamilyMemberRelationType.spouse.rawValue {
            id = .spouseName
            nameTitle = "配偶姓名"
            previousNameTitle = "原配偶姓名"
            
        } else if model.relation == YHFamilyMemberRelationType.child.rawValue {
            id = .childName
            nameTitle = "子女姓名"
            previousNameTitle = "原子女姓名"
        }

        // 姓名
        let mainApplicantNameInfo = YHResignFamilyInfoItem(id: id,
                                                           action: .edit,
                                                           isMust: true,
                                                           title: nameTitle,
                                                           value: model.name,
                                                           previousTitle: previousNameTitle,
                                                           previousValue: model.nameHistory,
                                                           isEditMode: isEditMode,
                                                           isShowPreviousInfo: !isEditMode && !model.nameHistory.isEmpty)
        resultArr.append(mainApplicantNameInfo)
       
        // 姓(拼音)
        let firstNameInfo =  YHResignFamilyInfoItem(id: .firstName,
                                                    action: .edit,
                                                    isMust: true,
                                                    title: "姓(拼音)",
                                                    value: model.familyName,
                                                    previousTitle: "原姓(拼音)",
                                                    previousValue: model.familyNameHistory,
                                                    isEditMode: isEditMode,
                                                    isShowPreviousInfo: !isEditMode && !model.familyNameHistory.isEmpty)
        resultArr.append(firstNameInfo)
        
        // 名(拼音)
        let lastNameInfo =  YHResignFamilyInfoItem(id: .lastName,
                                                     action: .edit,
                                                     isMust: true,
                                                     title: "名(拼音)",
                                                     value: model.givenName,
                                                     previousTitle: "原名(拼音)",
                                                     previousValue: model.givenNameHistory,
                                                     isEditMode: isEditMode,
                                                     isShowPreviousInfo: !isEditMode && !model.givenNameHistory.isEmpty)
        resultArr.append(lastNameInfo)
        
        // 婚姻状况
        let marriageInfo = YHResignFamilyInfoItem(id: .marriage,
                                                    action: .select,
                                                    isMust: true,
                                                    title: "婚姻状况",
                                                    value: model.getMarriageState(),
                                                    previousTitle: "原婚姻状况",
                                                    previousValue: model.getHistoryMarriageState(),
                                                    isEditMode: isEditMode,
                                                    isShowPreviousInfo: !isEditMode && !model.getHistoryMarriageState().isEmpty)
        marriageInfo.valueIndex = Int(model.married) ?? -1
        resultArr.append(marriageInfo)
        
        // 申报国籍
        let declareNationInfo =  YHResignFamilyInfoItem(id: .declareNation,
                                                          action: .select,
                                                          isMust: true,
                                                          title: "申报国籍",
                                                          value: model.nationality,
                                                          previousTitle: "原申报国籍",
                                                          previousValue: model.nationalityHistory,
                                                          isEditMode: isEditMode,
                                                          isShowPreviousInfo: !isEditMode && !model.nationalityHistory.isEmpty)
        resultArr.append(declareNationInfo)
        
        // 职业
        let occupationInfo =  YHResignFamilyInfoItem(id: .occupation,
                                               action: .edit,
                                               isMust: true,
                                               title: "职业",
                                               value: model.occupationName,
                                               previousTitle: "原职业",
                                               previousValue: model.occupationNameHistory,
                                               isEditMode: isEditMode,
                                               isShowPreviousInfo: !isEditMode && !model.occupationNameHistory.isEmpty)
        resultArr.append(occupationInfo)
        
        // 香港身份证号
        let hongkongIdInfo =  YHResignFamilyInfoItem(id: .hongKongId,
                                               action: .edit,
                                               isMust: false,
                                               title: "香港身份证号",
                                               value: model.hkIdentityid,
                                               previousTitle: "原香港身份证号",
                                               previousValue: model.hkIdentityidHistory,
                                               isEditMode: isEditMode,
                                               isShowPreviousInfo: !isEditMode && !model.hkIdentityidHistory.isEmpty)
        resultArr.append(hongkongIdInfo)
        
        // 香港地址
        if model.relation != YHFamilyMemberRelationType.child.rawValue &&
            model.relation != YHFamilyMemberRelationType.spouse.rawValue { // 子女\配偶无香港住址一栏
            
            let hongkongAddressInfo =  YHResignFamilyInfoItem(id: .hongkongAddress,
                                                           action: .edit,
                                                           isMust: false,
                                                           title: "香港住址",
                                                           value: model.hkAddress,
                                                           previousTitle: "原香港住址",
                                                           previousValue: model.hkAddressHistory,
                                                           isEditMode: isEditMode,
                                                           isShowPreviousInfo: !isEditMode && !model.hkAddressHistory.isEmpty)
            
            resultArr.append(hongkongAddressInfo)

        }
        
        return resultArr
    }
    
    func getCertificateInfo(_ model: YHResignInfoConfirmFamilyModel) -> [YHResignFamilyInfoItem] {
        
        var resultArr = [YHResignFamilyInfoItem]()
        
        guard let identity = model.identity  else { return [] }
        
        // 申报旅行证件
        let travelCerInfo = YHResignFamilyInfoItem(id: .travelCertificateType,
                                               action: .select,
                                               isMust: false,
                                               title: "申报旅行证件",
                                               value: identity.name,
                                               previousTitle: "原申报旅行证件",
                                               previousValue: identity.name,
                                               isEditMode: false,
                                               isShowPreviousInfo: false)
        resultArr.append(travelCerInfo)
        
        // 证件号
        let cerIdInfo = YHResignFamilyInfoItem(id: .travelCertificateId,
                                             action: .edit,
                                             isMust: false,
                                             title: "证件号",
                                             value: identity.number,
                                             previousTitle: "原证件号",
                                             previousValue: identity.number,
                                             isEditMode: false,
                                             isShowPreviousInfo: false)
        resultArr.append(cerIdInfo)

        // 有效期
        var validTime = "-"
        if !identity.begin.isEmpty, !identity.end.isEmpty {
            validTime = "\(identity.begin) ~ \(identity.end)"
        }
        let validTimeInfo = YHResignFamilyInfoItem(id: .certificateValidTime,
                                                 action: .edit,
                                                 isMust: false,
                                                 title: "有效期",
                                                 value: validTime,
                                                 previousTitle: "原证件号",
                                                 previousValue: validTime,
                                                 isEditMode: false,
                                                 isShowPreviousInfo: false)
        resultArr.append(validTimeInfo)
        
        return resultArr
    }
}
