//
//  YHFamilyInfoConfirmModel.swift
//  galaxy
//
//  Created by edy on 2024/8/20.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHFamilyInfoConfirmViewModel: NSObject {
    
    var familyInfo: YHFamilyGroupModel = YHFamilyGroupModel()
    var pinyinInfo: YHFamilyNamePinYin = YHFamilyNamePinYin()
    var isHaveShowRiskAlert: Bool = false
    
    func getFamilyInfo(param: [String: Any], callback: ((_ success: Bool, _ error: YHErrorModel?) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.FamilyInfoConfirm.familyInfo
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { [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 = YHFamilyGroupModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback?(false, err)
                    return
                }
                self.familyInfo = resultModel
                // 处理亲属关系
                self.familyInfo.main.info.relation = YHFamilyMemberRelationType.mainApplicant.rawValue
                self.familyInfo.spouse.info.relation = YHFamilyMemberRelationType.spouse.rawValue
                for child in self.familyInfo.children {
                    child.info.relation = YHFamilyMemberRelationType.child.rawValue
                }
                
                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: ((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?("", "")
        }
    }
    
    func submitFamilyUpdate(param: [String: Any], callback: ((_ success: Bool, _ error: YHErrorModel?) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.FamilyInfoConfirm.submitFamilyUpdate
        
        _ = YHNetRequest.postRequest(url: strUrl, params: param) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            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 submitFaimiyInfoWithOrderId(_ orderId: Int, callback: ((_ success: Bool, _ error: YHErrorModel?) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.FamilyInfoConfirm.familyNext
        
        _ = YHNetRequest.postRequest(url: strUrl, params: ["orderId": orderId]) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            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 requetRiskAlertShow(callback: ((_ isHaveShow: Bool) -> Void)?) {
        let param = ["identify": 3]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getOfficialCheckStatusApi
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                if let flag = json.data?.peel as? Bool {
                    self.isHaveShowRiskAlert = flag
                } else {
                    self.isHaveShowRiskAlert = false
                }
                callback?(self.isHaveShowRiskAlert)
                
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false)
            }
            
        } failBlock: { _ in
            callback?(false)
        }
    }
}

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

        // 姓名
        let mainApplicantNameInfo =  YHFamilyInfoItem(id: id,
                                                      action: .edit,
                                                      isMust: true,
                                                      title: nameTitle,
                                                      value: model.info.name,
                                                      previousTitle: previousNameTitle,
                                                      previousValue: model.info.nameHistory,
                                                      isEditMode: isEditMode,
                                                      isShowPreviousInfo: !isEditMode && !model.info.nameHistory.isEmpty)
        resultArr.append(mainApplicantNameInfo)
       
        // 姓(拼音)
        let firstNameInfo =  YHFamilyInfoItem(id: .firstName,
                                              action: .edit,
                                              isMust: true,
                                              title: "姓(拼音)",
                                              value: model.info.familyName,
                                              previousTitle: "原姓(拼音)",
                                              previousValue: model.info.familyNameHistory,
                                              isEditMode: isEditMode,
                                              isShowPreviousInfo: !isEditMode && !model.info.familyNameHistory.isEmpty)
        resultArr.append(firstNameInfo)
        
        // 名(拼音)
        let lastNameInfo =  YHFamilyInfoItem(id: .lastName,
                                             action: .edit,
                                             isMust: true,
                                             title: "名(拼音)",
                                             value: model.info.givenName,
                                             previousTitle: "原名(拼音)",
                                             previousValue: model.info.givenNameHistory,
                                             isEditMode: isEditMode,
                                             isShowPreviousInfo: !isEditMode && !model.info.givenNameHistory.isEmpty)
        resultArr.append(lastNameInfo)
        
        // 婚姻状况
        if model.info.relation != YHFamilyMemberRelationType.child.rawValue &&
            model.info.relation != YHFamilyMemberRelationType.spouse.rawValue { // 子女\配偶无婚姻状况一栏
            let marriageInfo = YHFamilyInfoItem(id: .marriage,
                                                action: .select,
                                                isMust: true,
                                                title: "婚姻状况",
                                                value: model.info.getMarriageState(),
                                                previousTitle: "原婚姻状况",
                                                previousValue: model.info.getHistoryMarriageState(),
                                                isEditMode: isEditMode,
                                                isShowPreviousInfo: !isEditMode && !model.info.getHistoryMarriageState().isEmpty)
            resultArr.append(marriageInfo)
        }
        
        // 出生国家/地区
        let birthNation = model.info.getBirthNation()
        let historyBirthNation = model.info.getHistoryBirthNation()
        let options = [YHFamilyInfoOption(index: 0, value: "国内", isSelect: model.info.birthPlaceAboard != "1"),
                       YHFamilyInfoOption(index: 1, value: "国外", isSelect: model.info.birthPlaceAboard == "1")]
        
        let birthNationInfo =   YHFamilyInfoItem(id: .birthNation,
                                                 action: .choice,
                                                 isMust: true,
                                                 title: "出生国家/地区",
                                                 value: birthNation,
                                                 previousTitle: "原出生国家/地区",
                                                 previousValue: historyBirthNation,
                                                 options: options,
                                                 isEditMode: isEditMode,
                                                 isShowPreviousInfo: !isEditMode && !historyBirthNation.isEmpty)
        resultArr.append(birthNationInfo)
        
        var birthPlaceId = YHFamilyInfoType.birthPlaceInChina
        var birthPlaceActionType = YHFamilyInfoActionType.select
        // 出生地
        var birthPlace = ""
        if model.info.birthPlaceAboard == "1" { // 当前出生国家是国外
            birthPlaceId = .birthPlaceAboard
            birthPlaceActionType = .edit
            birthPlace = model.info.birthPlace.foreign
        
        } else {
            birthPlaceId = .birthPlaceInChina
            birthPlaceActionType = .select
            birthPlace = model.info.birthPlace.area.joined(separator: "")
        }
        
        //
        var birthPlaceHistory = ""
        if model.info.birthPlaceAboardHistory == "1" { // 原出生国家是国外
            birthPlaceHistory = model.info.birthPlaceHistory.foreign

        } else {
            birthPlaceHistory = model.info.birthPlaceHistory.area.joined(separator: "")
        }
            
        let birthPlaceInfo =  YHFamilyInfoItem(id: birthPlaceId,
                                               action: birthPlaceActionType,
                                               isMust: true,
                                               title: "出生地",
                                               value: birthPlace,
                                               previousTitle: "原出生地",
                                               previousValue: birthPlaceHistory,
                                               isEditMode: isEditMode,
                                               isShowPreviousInfo: !isEditMode && !birthPlaceHistory.isEmpty)
        resultArr.append(birthPlaceInfo)
        
        // 申报国籍
        let declareNationInfo =  YHFamilyInfoItem(id: .declareNation,
                                                  action: .select,
                                                  isMust: true,
                                                  title: "申报国籍",
                                                  value: model.info.nationality,
                                                  previousTitle: "原申报国籍",
                                                  previousValue: model.info.nationalityHistory,
                                                  isEditMode: isEditMode,
                                                  isShowPreviousInfo: !isEditMode && !model.info.nationalityHistory.isEmpty)
        resultArr.append(declareNationInfo)
        
        // 职业
        let occupationInfo =  YHFamilyInfoItem(id: .occupation,
                                               action: .edit,
                                               isMust: true,
                                               title: "职业",
                                               value: model.info.occupationName,
                                               previousTitle: "原职业",
                                               previousValue: model.info.occupationNameHistory,
                                               isEditMode: isEditMode,
                                               isShowPreviousInfo: !isEditMode && !model.info.occupationNameHistory.isEmpty)
        resultArr.append(occupationInfo)
        
        // 香港身份证号
        let hongkongIdInfo =  YHFamilyInfoItem(id: .hongKongId,
                                               action: .edit,
                                               isMust: false,
                                               title: "香港身份证号",
                                               value: model.info.hkIdentityid,
                                               previousTitle: "原香港身份证号",
                                               previousValue: model.info.hkIdentityidHistory,
                                               isEditMode: isEditMode,
                                               isShowPreviousInfo: !isEditMode && !model.info.hkIdentityidHistory.isEmpty)
        resultArr.append(hongkongIdInfo)
        
        return resultArr
    }
    
    func getCertificateInfo(_ model: YHApplicantInfoModel) -> [YHFamilyInfoItem] {
        
        // 申报旅行证件
        var resultArr = [YHFamilyInfoItem]()
        let travelCerInfo = YHFamilyInfoItem(id: .travelCertificateType,
                                               action: .select,
                                               isMust: false,
                                               title: "申报旅行证件",
                                               value: model.info.identity?.name ?? "",
                                               previousTitle: "原申报旅行证件",
                                               previousValue: model.info.identity?.name ?? "",
                                               isEditMode: false,
                                               isShowPreviousInfo: false)
        resultArr.append(travelCerInfo)
        
        // 证件号
        let cerIdInfo = YHFamilyInfoItem(id: .travelCertificateId,
                                         action: .edit,
                                         isMust: false,
                                         title: "证件号",
                                         value: model.info.identity?.number ?? "",
                                         previousTitle: "原证件号",
                                         previousValue: model.info.identity?.number ?? "",
                                         isEditMode: false,
                                         isShowPreviousInfo: false)
        resultArr.append(cerIdInfo)
        return resultArr
    }
}
