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

import UIKit
import Alamofire

class YHFamilyMemberViewModel : YHBaseViewModel{

    var familyMemberModel: YHFamilyMember = YHFamilyMember()
    var mainApplicantInfo: YHMyMainApplicantInfoModel?

    var saveInfoSilentBlock:(()->())?
    
    func getIDCardDataSource(_ isShowPrompt: Bool) -> [YHSectionItemModel] {
        let item = YHItemModel(id: .id5, isNeed: true, title: "身份证", isUserKeyBoard: false, prompts: "请输入", message: nil, isShowPrompts: isShowPrompt)
        let section = YHSectionItemModel(title: "中国身份证(选填)", models: [item])
        let item1 = YHItemModel(id: .id6, isNeed: true, title: "港澳通行证(选填)", isUserKeyBoard: false, prompts: "请输入", message: nil, isShowPrompts: isShowPrompt)
        let section1 = YHSectionItemModel(title: "中国身份证(选填)", models: [item1])
        let item2 = YHItemModel(id: .id7, isNeed: true, title: "护照(选填)", isUserKeyBoard: false, prompts: "请输入", message: nil, isShowPrompts: isShowPrompt)
        let section2 = YHSectionItemModel(title: "护照(选填)", models: [item2])
        
        // 国籍
        let nationality = familyMemberModel.nationality
        // 居住国家
        var addressCountry = familyMemberModel.address.country
        // 居住海外是否满一年
        var is_live_oversea_year = familyMemberModel.isOverSeasOver1Year()
        if familyMemberModel.isLiveTother(), let mainApplicant = mainApplicantInfo { // 与主申请人同住用主申请人的居住信息判断
            addressCountry = mainApplicant.applicant_address.country
            is_live_oversea_year = mainApplicant.isOverSeasOver1Year()
        }
        
        if (nationality.contains("中国") && addressCountry.contains("中国")) || (nationality.contains("中国") && !is_live_oversea_year) {
            if familyMemberModel.isHandled == 1 {
                return [section, section1]
            } else {
                return [section]
            }
        } else if nationality.contains("中国") && is_live_oversea_year {
            return [section, section2]
            
        } else {
            return [section2]
        }
    }
    
    func updateModel(_ item: YHItemModel) {
        guard let type = item.id else { return }
        
        if item.id == .id8 {
            familyMemberModel.certificates.cnIdentityCard.number = item.message ?? ""
            
        } else if item.id == .id9 {
            familyMemberModel.certificates.cnIdentityCard.issueAt = item.message ?? ""
            
        } else if item.id == .id10 {
            familyMemberModel.certificates.cnIdentityCard.issueDateStartAt = item.message ?? ""
        } else if item.id == .id11 {
            familyMemberModel.certificates.cnIdentityCard.issueDateEndAt = item.message ?? ""
            
        } else if item.id == .id12 {
            familyMemberModel.certificates.hkMacaoPass.number = item.message ?? ""
        } else if item.id == .id13 {
            familyMemberModel.certificates.hkMacaoPass.issueAt = item.message ?? ""
        } else if item.id == .id14 {
            familyMemberModel.certificates.hkMacaoPass.issueDateStartAt = item.message ?? ""
        } else if item.id == .id15 {
            familyMemberModel.certificates.hkMacaoPass.issueDateEndAt = item.message ?? ""
        } else if item.id == .id16 {
//            familyMemberModel.certificates.passport.passportType = item.value?.first ?? ""
        } else if item.id == .id17 {
            familyMemberModel.certificates.passport.number = item.message ?? ""
        } else if item.id == .id18 {
            familyMemberModel.certificates.passport.issueAt = item.message ?? ""
        } else if item.id == .id19 {
            familyMemberModel.certificates.passport.issueDateStartAt = item.message ?? ""
        } else if item.id == .id20 {
            familyMemberModel.certificates.passport.issueDateEndAt = item.message ?? ""
        }
        if let saveInfoSilentBlock = saveInfoSilentBlock {
            saveInfoSilentBlock()
        }
    }
    
    // 更新身份证
    func updateModel(_ model: YHCNIDCardModel) {
        if model.name.count != 0 {
            familyMemberModel.subsetName = model.name
        }
        if model.birth.count != 0 {
            if familyMemberModel.relationType != .child {
                // 孩子生日设置大于18岁后必须设置为不能随行 导致证件上传和证件信息页面隐藏 会产生异常
                familyMemberModel.birthday = model.birth
            }
        }
        if model.gender.count != 0 {
            if model.gender == "女" {
                familyMemberModel.setMale(false)
            } else {
                familyMemberModel.setMale(true)
            }
        }
        if model.term_begins.count != 0 {
            familyMemberModel.certificates.cnIdentityCard.issueDateStartAt = model.term_begins
        }
        if model.end_of_term.count != 0 {
            familyMemberModel.certificates.cnIdentityCard.issueDateEndAt = model.end_of_term
        }
        if model.issuing_authority.count != 0 {
            familyMemberModel.certificates.cnIdentityCard.issueAt = model.issuing_authority
        }
        if model.card_num.count != 0 {
            familyMemberModel.certificates.cnIdentityCard.number = model.card_num
        }
        if let saveInfoSilentBlock = saveInfoSilentBlock {
            saveInfoSilentBlock()
        }
    }
    
    // 更新港澳通行证
    func updateModel(_ model: YHHKIDCardModel) {
        if model.name.count != 0 {
            familyMemberModel.subsetName = model.name
        }
        if model.birth.count != 0 {
            if familyMemberModel.relationType != .child {
                // 孩子生日设置大于18岁后必须设置为不能随行 导致证件上传和证件信息页面隐藏 会产生异常
                familyMemberModel.birthday = model.birth
            }
        }
        if model.gender.count != 0 {
            if model.gender == "女" {
                familyMemberModel.setMale(false)
            } else {
                familyMemberModel.setMale(true)
            }
        }
        if model.term_begins.count != 0 {
            familyMemberModel.certificates.hkMacaoPass.issueDateStartAt = model.term_begins
        }
        if model.end_of_term.count != 0 {
            familyMemberModel.certificates.hkMacaoPass.issueDateEndAt = model.end_of_term
        }
        if model.IssueAddress.count != 0 {
            familyMemberModel.certificates.hkMacaoPass.issueAt = model.IssueAddress
        }
        if model.card_num.count != 0 {
            familyMemberModel.certificates.hkMacaoPass.number = model.card_num
        }
        if let saveInfoSilentBlock = saveInfoSilentBlock {
            saveInfoSilentBlock()
        }
    }
    
    func updateModel(_ type: YHCardType, isFront: Bool, url: String) {
        switch type {
        case .identity:
            if isFront {
                familyMemberModel.certificates.cnIdentityCard.imgFront = url
            } else {
                familyMemberModel.certificates.cnIdentityCard.imgBack = url
            }
        case .passport:
            if isFront {
                familyMemberModel.certificates.hkMacaoPass.imgFront = url
            } else {
                familyMemberModel.certificates.hkMacaoPass.imgBack = url
            }
        case .other:
            familyMemberModel.certificates.passport.imgFront = url
        }
        if let saveInfoSilentBlock = saveInfoSilentBlock {
            saveInfoSilentBlock()
        }
    }
    
    //orc识别 中国身份证
    func requestCnIDCardMessage(_ url: String, isBack: Int, callBackBlock:@escaping (_ success: Bool, _ error:YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curOssURL() + YHAllApiName.OCR.cn
        let params: [String : Any] = ["url": url,
                                      "is_back": isBack]
        let _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String : Any], let result = YHCNIDCardModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.updateModel(result)
                callBackBlock(true, nil)
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false,err)
        }
    }
    
    //orc识别 港澳通行证
    func requestHkIDCardMessage(_ url: String, isBack: Int, callBackBlock:@escaping (_ success: Bool, _ error:YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curOssURL() + YHAllApiName.OCR.hk
        let params: [String : Any] = ["url": url,
                                      "is_back": isBack]
        let _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String : Any], let result = YHHKIDCardModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.updateModel(result)
                callBackBlock(true, nil)
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false,err)
        }
    }
    
}
