//
//  YHParentViewController.swift
//  galaxy
//
//  Created by edy on 2024/1/26.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHParentInfoVC: YHBaseViewController {
    
    var parentInfo: YHFamilyMember?
    var orderId: Int = 0
    var items:[[YHFormItemProtocol]] = [[YHFormItemProtocol]]()
    let familyRequest:YHFamilyRequestViewModel = YHFamilyRequestViewModel()
    // 是否显示未填写错误提示
    var isNeedShowError = false
    
    var bottomView: YHSaveAndSubmitView = {
        let view = YHSaveAndSubmitView.createView()
        view.isHiddenSave = true
        view.changeRightBtnTitle("保存")
        return view
    }()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame:.zero, style:.grouped)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.estimatedSectionHeaderHeight = 14.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = UIColor(hexString:"#F8F8F8")
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHFormItemDoubleChoiceCell.self, forCellReuseIdentifier: YHFormItemDoubleChoiceCell.cellReuseIdentifier)
        tableView.register(YHFormItemInputTextCell.self, forCellReuseIdentifier: YHFormItemInputTextCell.cellReuseIdentifier)
        tableView.register(YHFormItemEnterDetailCell.self, forCellReuseIdentifier: YHFormItemEnterDetailCell.cellReuseIdentifier)
        tableView.register(YHFormItemTitleCell.self, forCellReuseIdentifier: YHFormItemTitleCell.cellReuseIdentifier)
        tableView.register(YHFormItemAddCell.self, forCellReuseIdentifier: YHFormItemAddCell.cellReuseIdentifier)
        tableView.register(YHFormItemSelectSheetCell.self, forCellReuseIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier)
        tableView.register(YHFormItemOnlyDoubleChoiceCell.self, forCellReuseIdentifier: YHFormItemOnlyDoubleChoiceCell.cellReuseIdentifier)
        
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if let parentInfo = parentInfo {
            gk_navTitle = parentInfo.relationType == .father ?  "父亲信息填写".local :  "母亲信息填写".local
        }
        gk_navigationBar.backgroundColor = .white
        view.backgroundColor = UIColor(hexString:"#F8F8F8")
        createUI()
        loadInfo()
    }
    
    func createUI() {
        
        view.addSubview(tableView);
        view.addSubview(bottomView)
        
        bottomView.submitBlock = {
            [weak self] in
            guard let self = self else { return }
            self.saveInfo(isSubmit: true, isLoading: true) {
                [weak self] success in
                if success {
                    self?.navigationController?.popViewController(animated: true)
                }
            }
        }
        
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(YHSaveAndSubmitView.height)
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(bottomView.snp.top)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
        }
        loadInfo()

    }
    
    func loadInfo() {
        
        guard let parentInfo = parentInfo else { return }

        items.removeAll()
        
        // 基本信息
        let title0 = YHFormTitleItem(type: .basicInfo)
        let item00 = YHFormDetailItem(type: .onlyDoubleChoice)
        item00.value = String(parentInfo.isDead())
        let arr0:[YHFormItemProtocol] = [title0, item00]


        // 父母亲信息
        var arr1 = [YHFormItemProtocol]()
        if parentInfo.relationType == .father { // 父亲
            let title1 = YHFormTitleItem(type: .fatherInfo)
            let item10 = YHFormDetailItem(type: .fatherName, value:parentInfo.subsetName, tips:"请输入姓名".local)
            arr1.append(title1)
            arr1.append(item10)
        } else { // 母亲

            let title1 = YHFormTitleItem(type: .motherInfo)
            let item10 = YHFormDetailItem(type: .motherName, value:parentInfo.subsetName, tips:"请输入姓名".local)
            arr1.append(title1)
            arr1.append(item10)
        }
        
        let item11 = YHFormDetailItem(type: .birthday, value:parentInfo.birthday, tips:"请选择生日日期".local)
        let item12 = YHFormDetailItem(type: .birthNation, value:String(parentInfo.isBirthOverSeas()))
        
        var cityValue = parentInfo.birthPlace.area.joined(separator: ",")
        var cityPlaceHolder = "请选择".local
        var cityTips = "请选择城市".local
        if parentInfo.isBirthOverSeas() {
            cityValue = parentInfo.birthPlace.foreign
            cityPlaceHolder = "请输入".local
            cityTips = "请输入城市".local
        }
        let item13 = YHFormDetailItem(type: .birthCity, value:cityValue,placeHolder:cityPlaceHolder, tips:cityTips)
        
        
        let arr:[YHFormItemProtocol] = [item11, item12, item13]
        arr1.append(contentsOf: arr)
        
        if parentInfo.isDead() {
            items.append(contentsOf: [arr0, arr1])
        }
        
        if !parentInfo.isDead() { // 健在
            let item14 = YHFormDetailItem(type: .marriageState, value:parentInfo.married, tips:"请选择婚姻状况".local)
            arr1.append(item14)
            
            // 职业信息
            let title2 = YHFormTitleItem(type: .occupationInfo)
            let item20 = YHFormDetailItem(type: .occupation, value:parentInfo.occupation, tips:"请选择职业".local)
            var arr2:[YHFormItemProtocol] = [title2, item20]
            
            if parentInfo.isNowHaveJob()  {
                let item21 = YHFormDetailItem(type: .occupationName, value:parentInfo.occupationName, tips:"请输入职业名称".local)
                arr2.append(item21)
            }
            
            // 居住信息
            let title3 = YHFormTitleItem(type: .liveInfo)
            let item30 = YHFormDetailItem(type: .liveNationOrArea, value:parentInfo.liveCountry, tips:"请选择国家/地区".local)
            let arr3:[YHFormItemProtocol] = [title3, item30]
            
            // 香港身份证
            let title4 = YHFormTitleItem(type: .hkIdentityCardInfo)
            let item40 = YHFormDetailItem(type: .isHaveHkIdentityCard)
            item40.value = String(parentInfo.isHaveHKIdentityCard())
            var arr4:[YHFormItemProtocol] = [title4, item40]

            if parentInfo.isHaveHKIdentityCard() { // 办理过香港身份证才显示证号
                let tips = isEmptyString(parentInfo.hkIdentityCard) ? "请输入香港身份证号码".local : "请输入正确的香港身份证号码".local
                let item41 = YHFormDetailItem(type: .hkIdentityCardNumber, value:parentInfo.hkIdentityCard, tips: tips)
                arr4.append(item41)
            }
            items.append(contentsOf: [arr0, arr1, arr2, arr3, arr4])
        } else { // 父母已故
            if let hkIdentityCard = parentInfo.hkIdentityCard, !hkIdentityCard.isHKIdentityCardNumber() {
                parentInfo.hkIdentityCard = ""
            }
        }
        tableView.reloadData()
    }
    
    func getCellType(_ item: Any) ->HKFormItemCellType {
        if item is YHFormTitleItem {
            return .title
        }
        
        if item is YHFormDetailItem {
            let detailItem = item as! YHFormDetailItem
            
            if detailItem.type == .birthCity {
                var isBirthOverSeas = false
                if let parentInfo = parentInfo {
                    isBirthOverSeas = parentInfo.isBirthOverSeas()
                }
                if isBirthOverSeas {
                    return .inputText
                } else {
                    return .selectSheet
                }
            }
            
            if detailItem.type == .fatherName
                || detailItem.type == .motherName
                || detailItem.type == .occupationName
                || detailItem.type == .hkIdentityCardNumber
            {
                return .inputText
            }
            
            if detailItem.type == .birthday
                || detailItem.type == .marriageState
                || detailItem.type == .occupation
                || detailItem.type == .liveNationOrArea
            {
                return .selectSheet
            }
            if detailItem.type == .birthNation || detailItem.type == .isHaveHkIdentityCard
            {
                return .twoChoice
            }
            if detailItem.type == .onlyDoubleChoice
            {
                return .onlyTwoChoice
            }
        }
        return .defaultType
    }
    
}

extension YHParentInfoVC : UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section >= items.count { return 0 }
        let arr = items[section]
        return arr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section >= items.count { return createDefaultCell(indexPath) }
        let arr:[YHFormItemProtocol] = items[indexPath.section]
        if indexPath.row >= arr.count {  return createDefaultCell(indexPath) }
        let item:YHFormItemProtocol = arr[indexPath.row]
        
        let cellType = getCellType(item)
        
        if cellType == .title { // 标题
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemTitleCell.cellReuseIdentifier, for: indexPath) as! YHFormItemTitleCell
            cell.setTitleAndSubTitle(title:item.getTitle())

            return cell
        }
        
        if cellType == .addItem { // 新增item cell
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemAddCell.cellReuseIdentifier, for: indexPath) as! YHFormItemAddCell
            cell.title = item.getTitle()
            return cell
        }
        
        if item is YHFormDetailItem {
            
            let detailItem = item as! YHFormDetailItem
            
            if cellType == .inputText { // 输入文字cell
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemInputTextCell.cellReuseIdentifier, for: indexPath) as! YHFormItemInputTextCell
                cell.isMust = detailItem.isNeed
                cell.title = detailItem.getTitle()
                cell.text = detailItem.value
                cell.placeHolder = detailItem.placeHolder
                if detailItem.type == .hkIdentityCardNumber { // 输入香港身份证号码
                    let isEmptyValue = isEmptyString(detailItem.value)
                    var isUnvalidFormat = true
                    if let value = detailItem.value, value.isHKIdentityCardNumber() {
                        isUnvalidFormat = false
                    }
                    let isNeedShowTips = isEmptyValue || isUnvalidFormat
                    cell.setTips(detailItem.tips, isShow: isNeedShowError && isNeedShowTips)
                } else {
                    cell.setTips(detailItem.tips, isShow: isNeedShowError && detailItem.isShowTips)
                }
                cell.textInputCondtion = {
                    textField in
                    
                    var max = -1
                    if detailItem.type == .fatherName ||
                        detailItem.type == .motherName {
                        max = 30
                        
                    } else if detailItem.type == .occupationName {
                        max = 50
                    } else if detailItem.type == .birthCity {
                        max = 100
                    }

                    if max > 0 {
                        if let textStr = textField.text {
                            textField.text = (textStr.count > max ? textStr[safe: ..<max] : textStr)
                        }
                    }
                    return true
                }
                cell.textChange = {
                    
                    [weak self] (text, isEditEnd) in
                    guard let self = self else { return }
                    if detailItem.type == .fatherName || detailItem.type == .motherName {
                        self.parentInfo?.subsetName = text ?? ""
    
                    } else if detailItem.type == .birthCity {
                        self.parentInfo?.birthPlace.foreign = text ?? ""
                        
                    } else if detailItem.type == .occupationName {
                        self.parentInfo?.occupationName = text ?? ""
                        
                    } else if detailItem.type == .hkIdentityCardNumber {
                        self.parentInfo?.hkIdentityCard = text
                    }
                    if isEditEnd {
                        self.loadInfo()
                        if detailItem.type == .hkIdentityCardNumber {
                            if let text = text, !text.isEmpty, !text.isHKIdentityCardNumber() {
                                YHHUD.flash(message: "请输入正确的香港身份证号格式")
                                return
                            }
                        }
                        saveInfoSilent()
                    }
                }
                return cell
            }
            
            if cellType == .selectSheet { // 点击选择列表cell
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier, for: indexPath) as! YHFormItemSelectSheetCell
                cell.isMust = detailItem.isNeed
                cell.title = detailItem.getTitle()
                cell.detail = detailItem.value
                cell.setTips(detailItem.tips, isShow: isNeedShowError && detailItem.isShowTips)
                return cell
            }
            
            if cellType == .twoChoice { // 问答双项选择cell
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemDoubleChoiceCell.cellReuseIdentifier, for: indexPath) as! YHFormItemDoubleChoiceCell
                cell.isMust = detailItem.isNeed
                cell.title = item.getTitle()
                cell.answerArr = nil
                
                if detailItem.type == .birthNation { // 出生国家
                    var select = false
                    if let value = detailItem.value {
                       select = Bool(value)!
                    }
                    let answers = [YHFormChoiceItem(title: "国内".local, isSelect: !select),
                                   YHFormChoiceItem(title: "国外".local, isSelect: select)]
                    cell.answerArr = answers
                    cell.answerBlock = {
                        [weak self] (answers, index) in
                        guard let self = self else { return }
                         let selectItem = answers[index]
                        self.parentInfo?.setBirthOverSeas(selectItem.title == "国外".local)
                        self.loadInfo()
                        saveInfoSilent()
                    }
                } else if detailItem.type == .isHaveHkIdentityCard { // 是否办理过香港身份证
                    var select = false
                    if let value = detailItem.value {
                       select = Bool(value)!
                    }
                    let answers = [YHFormChoiceItem(title: "是".local, isSelect: select),
                                   YHFormChoiceItem(title: "否".local, isSelect: !select)]
                    cell.answerArr = answers
                    cell.answerBlock = {
                        [weak self] (answers, index) in
                        guard let self = self else { return }
                         let selectItem = answers[index]
                         if detailItem.type == .isHaveHkIdentityCard {
                            let isHaveIdCard = selectItem.title == "是".local
                            self.parentInfo?.setHaveHKIdentityCard(isHaveIdCard)
                             if !isHaveIdCard {
                                 self.parentInfo?.hkIdentityCard = ""
                             }
                        }
                        self.loadInfo()
                        saveInfoSilent()
                    }
                }
                
                return cell
            }
            
            if cellType == .onlyTwoChoice { // 仅有双项选择cell
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemOnlyDoubleChoiceCell.cellReuseIdentifier, for: indexPath) as! YHFormItemOnlyDoubleChoiceCell

                var isDead = false
                if let parentInfo = parentInfo, parentInfo.isDead() { // 已故
                    isDead = true
                }
                let answers = [YHFormChoiceItem(title: "健在".local, isSelect: !isDead),
                               YHFormChoiceItem(title: "已故".local, isSelect: isDead)]
                cell.answerArr = answers
                cell.answerBlock = { 
                    [weak self] (arr, selectIndex) in
                    guard let self = self else { return }
                    let selectItem:YHFormChoiceItem = arr[selectIndex]
                    self.parentInfo?.setIsDead(selectItem.title == "已故")
                    self.loadInfo()
                    saveInfoSilent()
                }
                return cell
            }
        }
        return createDefaultCell(indexPath)
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if indexPath.section >= items.count { return  }
        let arr:[YHFormItemProtocol] = items[indexPath.section]
        if indexPath.row >= arr.count {  return }
        createCorner(cell: cell, arr: arr, indexPath: indexPath)
    }
    
    func createDefaultCell(_ indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 14.0
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        if section == items.count-1 {
            return 14.0
        }
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if !(0..<items.count).contains(indexPath.section) { return }
        let arr:[YHFormItemProtocol] = items[indexPath.section]
        if !(0..<arr.count).contains(indexPath.row) {  return  }
        let item = arr[indexPath.row]
        
        if item is YHFormDetailItem {
            let detailItem = item as! YHFormDetailItem
            
            if detailItem.type == .birthday { // 出生日期
                YHDatePickView.show(type: .yyyymmdd, title:"选择出生日期".local, lastIsTaday: true, currentDay: self.parentInfo?.birthday ?? "") { [weak self] dateStr in
                    guard let self = self else { return }
                    
                    if detailItem.type == .birthday {
                        let format = DateFormatter()
                        format.dateFormat = "yyyy-MM-dd"
                        if let selectDate = format.date(from:dateStr) {
                            let selectTimeInterval = selectDate.timeIntervalSince1970
                            let currentTimeInterval = Date().timeIntervalSince1970
                            // 出生日期须早于当前日期
                            if selectTimeInterval > currentTimeInterval {
                                YHHUD.flash(message: "出生日期不能晚于当前日期".local)
                                return
                            }
                        }
                        self.parentInfo?.birthday = dateStr
                    }
                    self.loadInfo()
                    saveInfoSilent()
                }
                
            } else if detailItem.type == .birthCity { // 出生城市
                
                var isBirthOverSeas = false
                if let parentInfo = parentInfo {
                    isBirthOverSeas = parentInfo.isBirthOverSeas()
                }
                // 出生国外时 出生城市是输入框
                if isBirthOverSeas { return }
                
                let vc = YHAddressViewController()
                vc.backLocationStringController = {
                     [weak self] (string1, string2, string3, string4) in
                     guard let self = self else { return }
                     print("\(string1)\n\(string2)\n\(string3)\n\(string4)")
                    var citys:[String] = []
                    if !isEmptyString(string2) {
                        citys.append(string2)
                    }
                    if !isEmptyString(string3) {
                        citys.append(string3)
                    }
                     self.parentInfo?.birthPlace.area = citys
                     self.loadInfo()
                     saveInfoSilent()
                 }
                self.present(vc, animated: true)
 
            } else if detailItem.type == .occupation { // 职业
                
                let occupation = self.parentInfo?.occupation ?? ""
                YHSheetPickerView.show(type: .occupation, selectTitle:occupation) {
                    [weak self] selectItem in
                    guard let self = self else { return }
                    self.parentInfo?.occupation = selectItem.title
                    self.loadInfo()
                    saveInfoSilent()
                }
                
            } else if detailItem.type == .marriageState { // 婚姻
                YHSheetPickerView.show(type: .marriage, selectTitle:self.parentInfo?.married) {
                    [weak self] selectItem in
                    guard let self = self else { return }
                    self.parentInfo?.married = selectItem.title
                    self.loadInfo()
                    saveInfoSilent()
                }
               
            } else if detailItem.type == .liveNationOrArea { // 现居住国家/地区
                let vc = YHSelectCountryViewController()
                vc.backLocationStringController = {
                     [weak self] string in
                     guard let self = self else { return }
                     self.parentInfo?.liveCountry = string
                     self.loadInfo()
                     saveInfoSilent()
                 }
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
        
    func createCorner(cell:UITableViewCell, arr:Array<Any>, indexPath:IndexPath) {
        // 复用时需清理
        cell.layer.mask = nil
        // 设置每块section圆角
        if (indexPath.row == 0) {
            let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
            cell.createCorner(CGSizeMake(12.0, 12.0), corner)
            
        } else if (indexPath.row == arr.count-1) {
            let corner = UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue)
            cell.createCorner(CGSizeMake(12.0, 12.0), corner)
            
        } else {
            cell.layer.mask = nil
        }
    }
}

extension YHParentInfoVC {
    
    // 检查填写信息完整性
    func checkIntegrity() -> Bool {
        
        guard let parentInfo = parentInfo else { return false }
        
        
        if isEmptyString(parentInfo.subsetName) || isEmptyString(parentInfo.birthday) {
            
            return false
        }
        
    
        if parentInfo.isBirthOverSeas() {
            if isEmptyString(parentInfo.birthPlace.foreign) {
                return false
            }
        } else {
            if isEmptyArray(parentInfo.birthPlace.area) {
                return false
            }
        }
    
        if parentInfo.isDead() {
            return true
        }
        
        // 以下是父母未死的情况
        
        if isEmptyString(parentInfo.married) || isEmptyString(parentInfo.occupation) || isEmptyString(parentInfo.liveCountry) {
            return false
        }
        
        if parentInfo.isNowHaveJob()  {
            if isEmptyString(parentInfo.occupationName) {
                return false
            }
        }
        
        if parentInfo.isHaveHKIdentityCard() { // 办理过香港身份证才显示证号
            
            if isEmptyString(parentInfo.hkIdentityCard) {
                return false
            }
        }
        
        return true
    }
    
    // isSubmit 是否是提交 isSilent:是否显示toast
    func saveInfo(isSubmit:Bool, isLoading:Bool, callBack:((Bool)->Void)?) {
        
        if isSubmit {
            let isChecked = checkIntegrity()
            isNeedShowError = !isChecked
            loadInfo()
            
            if !isChecked {
                YHHUD.flash(message: "资料还未填完")
                return
            }
            guard let parentInfo = parentInfo else { return  }

            if  parentInfo.isHaveHKIdentityCard(), !parentInfo.isDead(), let hkIdentityCard = parentInfo.hkIdentityCard, !hkIdentityCard.isHKIdentityCardNumber() {
                isNeedShowError = true
                loadInfo()
                YHHUD.flash(message: "请输入正确的香港身份证号码")
                return
            }
        }
        
        guard let parentInfo = parentInfo else { return }
        guard let info = parentInfo.toDictionary() else { return }
        
        let dict:[String: Any] = ["order_id":orderId,
                                  "relation":parentInfo.relation,
                                  "step":parentInfo.step,
                                  "next":isSubmit,
                                  "info":info]
        
        self.familyRequest.addOrSaveFamilyMember(params:dict, isShowLoading: isLoading) { success, error in
            if isLoading {
                if success {
                    YHHUD.flash(message:"保存成功")
                } else {
                    var msg = "保存失败"
                    if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                        msg = errorMsg
                    }
                    YHHUD.flash(message:msg)
                }
            }
            if let callBack = callBack {
                callBack(success)
            }
        }
    }
    
    // 静默保存 不显示toast和loading
    func saveInfoSilent() {
        guard let parentInfo = parentInfo else { return }
        if parentInfo.detailId == 0 { return }
        saveInfo(isSubmit: false, isLoading: false, callBack: nil)
    }
}
