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

import UIKit

class YHChildBasicInfoVC: YHBaseViewController, YHFamilyMemberProtol {

    var child: YHFamilyMember?
    weak var delegate: YHSpouseInfoVCProtocol?
    var isNeedShowError = false

    var items: [[YHFormItemProtocol]] = [[YHFormItemProtocol]]()
    
    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(YHFormItemDegreeInfoCell.self, forCellReuseIdentifier: YHFormItemDegreeInfoCell.cellReuseIdentifier)
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navigationBar.isHidden = true
        view.backgroundColor = UIColor(hexString: "#F8F8F8")
        createUI()
        loadInfo()
    }
    
    func createUI() {
        
        view.addSubview(tableView)
        let topHeight = k_Height_NavigationtBarAndStatuBar+YHStepView.height
        let bottomHeight = YHSaveAndSubmitView.height
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(KScreenHeight-topHeight-bottomHeight)
        }
    }
    
    func loadInfo() {
        
        guard let child = child else { return }
        items.removeAll()

        // 子女信息
        let title0 = YHFormTitleItem(type: .childInfo)
        let item00 = YHFormDetailItem(type: .childName)
        item00.value = child.subsetName
        item00.tips = "请输入子女姓名".local
        let item01 = YHFormDetailItem(type: .everName, isNeed: false)
        item01.value = child.usedName
        let item02 = YHFormDetailItem(type: .befourMarryFirstName, isNeed: false)
        item02.value = child.surname
        let item03 = YHFormDetailItem(type: .gender)
        item03.value = child.sexName()
        item03.tips = "请选择性别".local
        let item04 = YHFormDetailItem(type: .marriageState)
        item04.value = child.married
        item04.tips = "请选择婚姻状况".local
        let item06 = YHFormDetailItem(type: .birthNation)
        item06.value = String(child.isBirthOverSeas())
        item06.tips = "请选择出生国家/地区".local
        let item07 = YHFormDetailItem(type: .birthCity)
        
        if child.isBirthOverSeas() {
            item07.value = child.birthPlace.foreign
            item07.tips = "请输入出生城市".local

        } else {
            item07.value = child.birthPlace.details
            item07.tips = "请输入出生城市".local
            
//            item07.value = child.birthPlace.area.joined(separator: ",")
//            item07.tips = "请选择出生城市".local
        }
        
        let arr0: [YHFormItemProtocol] = [title0, item00, item01, item02, item03, item04, item06, item07]
        items.append(arr0)
        
        // 职业信息
//        let title1 = YHFormTitleItem(type: .occupationInfo)
//        let item10 = YHFormDetailItem(type: .occupation)
//        item10.value = child.occupation
//        item10.tips = "请选择职业".local
//        var arr1:[YHFormItemProtocol] = [title1, item10]
//        
//        if child.isNowHaveJob()  {
//            let item11 = YHFormDetailItem(type: .occupationName)
//            item11.value = child.occupationName
//            item11.tips = "请输入职业名称".local
//            arr1.append(item11)
//        }
//        items.append(arr1)
        
        if child.isFollow() {
            
            // 是否前次婚姻子女
            let title2 = YHFormTitleItem(type: .isPreviousMarriageChild)
            let item20 = YHFormDetailItem(type: .isPreviousMarriageChild)
            item20.value = String(child.isPreviousMarriageChild())
            item20.tips = "请选择是否前次婚姻子女".local
            let arr2: [YHFormItemProtocol] = [title2, item20]
            items.append(arr2)
            
            // 在港信息
//            let title3 = YHFormTitleItem(type: .inHongKongInfo)
//            let item30 = YHFormDetailItem(type: .isNowInHK)
//            item30.value = String(child.isNowInHK())
//            item30.tips = "请选择目前是否在港".local
//            
//            var arr3:[YHFormItemProtocol] = [title3, item30]
//            
//            
//            if child.isNowInHK() { // 目前在港才显示 逗留期限和在港身份
//                let item31 = YHFormDetailItem(type: .stayHKDate)
//                item31.tips = "请选择获准逗留期限".local
//                item31.value = child.childInHk.info
//                
//                let item32 = YHFormDetailItem(type: .roleInHK)
//                item32.tips = "请选择在港身份".local
//                item32.value = child.hkIdentity
//                
//                arr3.append(contentsOf: [item31, item32])
//            }
//            items.append(arr3)

        }

        // 香港身份证
        let title4 = YHFormTitleItem(type: .hkIdentityCardInfo)
        let item40 = YHFormDetailItem(type: .isHaveHkIdentityCard)
        item40.value = String(child.isHaveHKIdentityCard())
        item40.tips = "请选择是否办理过香港身份证".local
        var arr4: [YHFormItemProtocol] = [title4, item40]

        if child.isHaveHKIdentityCard() { // 办理过香港身份证才显示证号
            let item41 = YHFormDetailItem(type: .hkIdentityCardNumber)
            item41.value = child.hkIdentityCard
            let tips = isEmptyString(child.hkIdentityCard) ? "请输入香港身份证号码" : "请输入正确的香港身份证号码"
            item41.tips = tips
            arr4.append(item41)
        }
        items.append(arr4)
        tableView.reloadData()
    }
    
    func getCellType(_ item: Any) -> HKFormItemCellType {
        if item is YHFormTitleItem {
            return .title
        }
        
        if item is YHFormDetailItem {
            guard let detailItem = item as? YHFormDetailItem else { return .defaultType }
            
            if detailItem.type == .birthCity {
                return .inputText
                
//                var isBirthOverSeas = false
//                if let child = child {
//                    isBirthOverSeas = child.isBirthOverSeas()
//                }
//                if isBirthOverSeas {
//                    return .inputText
//                } else {
//                    return .selectSheet
//                }
            }
            
            if detailItem.type == .childName
                || detailItem.type == .everName
                || detailItem.type == .befourMarryFirstName
                || detailItem.type == .occupationName
                || detailItem.type == .hkIdentityCardNumber {
                return .inputText
            }
            if detailItem.type == .occupation
                || detailItem.type == .stayHKDate
                || detailItem.type == .roleInHK
                || detailItem.type == .ownDegree
                || detailItem.type == .gender
                || detailItem.type == .marriageState {
                return .selectSheet
            }
            if detailItem.type == .birthNation
                || detailItem.type == .isNowInHK
                || detailItem.type == .isHaveHkIdentityCard
                || detailItem.type == .isPreviousMarriageChild {
                return .twoChoice
            }
            
            if detailItem.type == .degreeDetailInfo {
                return .degreeDetailInfo
            }
        }
        return .defaultType
    }
    
}

extension YHChildBasicInfoVC: 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 { // 标题
            guard let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemTitleCell.cellReuseIdentifier, for: indexPath) as? YHFormItemTitleCell else { return UITableViewCell() }
            cell.setTitleAndSubTitle(title: item.getTitle())
            return cell
        }
        
        if item is YHFormDetailItem {
            guard let detailItem = item as? YHFormDetailItem else { return UITableViewCell() }
            
            if cellType == .inputText { // 输入文字cell
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemInputTextCell.cellReuseIdentifier, for: indexPath) as? YHFormItemInputTextCell else { return UITableViewCell() }
                cell.isMust = detailItem.isNeed
                cell.placeHolder = detailItem.placeHolder
                cell.title = detailItem.getTitle()
                cell.text = detailItem.value
                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)
                }
                
                if detailItem.type == .befourMarryFirstName {
                    cell.textField.keyboardType = .asciiCapable //  英文键盘
                } else {
                    cell.textField.keyboardType = .default
                }
                
                cell.textInputCondtion = {
                    textField in
                    
                    if detailItem.type == .befourMarryFirstName { // 仅支持输入最多30个大写字母
                        let regex = "[^A-Za-z]+"
                        textField.limitInputWithPattern(pattern: regex, 30)
                        return true
                    }
                    
                    var max = -1
                    if detailItem.type == .childName ||
                        detailItem.type == .everName {
                        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 == .childName {
                        self.child?.subsetName = text ?? ""
                        
                    } else if detailItem.type == .everName {
                        self.child?.usedName = text ??  ""
                        
                    } else if detailItem.type == .befourMarryFirstName {
                        let tt = text?.uppercased()
                        self.child?.surname = tt ??  ""
                        cell.textField.text = tt
                        
                    } else if detailItem.type == .birthCity {
                        if let child = child, child.isBirthOverSeas() { // 出生国外
                            self.child?.birthPlace.foreign = text ?? ""
                        } else {
                            self.child?.birthPlace.details = text ?? ""
                        }
                        
                    } else if detailItem.type == .occupationName {
                        self.child?.occupationName = text ??  ""
                        
                    } else if detailItem.type == .hkIdentityCardNumber {
                        self.child?.hkIdentityCard = text
                    }
                    if isEditEnd {
                        self.loadInfo()
                        if detailItem.type == .hkIdentityCardNumber {
                            if let text = text, !text.isEmpty, !text.isHKIdentityCardNumber() {
                                YHHUD.flash(message: "请输入正确的香港身份证号格式")
                                return
                            }
                        }
                        save()
                    }
                }
                return cell
            }
            
            if cellType == .selectSheet { // 点击选择列表cell
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier, for: indexPath) as? YHFormItemSelectSheetCell else { return UITableViewCell() }
                cell.isMust = detailItem.isNeed
                cell.placeHolder = detailItem.placeHolder
                cell.title = detailItem.getTitle()
                cell.detail = detailItem.value
                cell.setTips(detailItem.tips, isShow: isNeedShowError && detailItem.isShowTips)
                return cell
            }
            
            if cellType == .twoChoice { // 双项选择cell
                
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemDoubleChoiceCell.cellReuseIdentifier, for: indexPath) as? YHFormItemDoubleChoiceCell else { return UITableViewCell() }
                cell.isMust = detailItem.isNeed
                cell.title = item.getTitle()
                cell.answerArr = nil
                cell.setTips(detailItem.tips, isShow: detailItem.isShowTips)
                
                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.view.endEditing(true)
                        self.child?.setBirthOverSeas(selectItem.title == "国外".local)
                        self.loadInfo()
                        save()
                    }
                } else if detailItem.type == .isHaveHkIdentityCard || detailItem.type == .isNowInHK || detailItem.type == .isPreviousMarriageChild { // 是否办理过香港身份证 是否在岗 是否前次婚姻子女
                    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]
                        let option = selectItem.title == "是".local
                        if detailItem.type == .isNowInHK {
                            self.child?.setNowIsInHK(option)
                        } else if detailItem.type == .isHaveHkIdentityCard {
                            self.child?.setHaveHKIdentityCard(option)
                            if !option {
                                self.child?.hkIdentityCard = ""
                            }
                        } else if detailItem.type == .isPreviousMarriageChild {
                            self.child?.setPreviousMarriageChild(option)
                        }
                        self.loadInfo()
                        save()
                    }
                }
                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 {
            guard let detailItem = item as? YHFormDetailItem else { return }
            
            if detailItem.type == .stayHKDate { // 出生日期/获准滞留至
                var title = ""
                if detailItem.type == .stayHKDate {
                    title = "选择逗留日期"
                }
                YHDatePickView.show(type: .yyyymmdd, title: title, lastIsTaday: true, currentDay: self.child?.childInHk.info ?? "") { [weak self] dateStr in
                    guard let self = self else { return }
                    
                    if detailItem.type == .stayHKDate {
                        self.child?.childInHk.info =  dateStr
                    }
                    loadInfo()
                    save()
                }
                
            } else if detailItem.type == .birthCity { // 出生城市
                
                return
//                var isBirthOverSeas = false
//                if let child = child {
//                    isBirthOverSeas = child.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.child?.birthPlace.area = citys
//                     self.loadInfo()
//                     save()
//                 }
//                self.present(vc, animated: true)
 
            } else if detailItem.type == .roleInHK { // 在港身份
                
                let identity = self.child?.hkIdentity ?? ""
                
                YHSheetPickerView.show(type: .identity, selectTitle: identity) {
                    [weak self] selectItem in
                    guard let self = self else { return }
                    self.child?.hkIdentity = selectItem.title
                    self.loadInfo()
                    save()
                }
                
            } else if detailItem.type == .occupation { // 职业
                let occupation = self.child?.occupation ?? ""
                YHSheetPickerView.show(type: .occupation, selectTitle: occupation) {
                    [weak self] selectItem in
                    guard let self = self else { return }
                    self.child?.occupation = selectItem.title
                    self.loadInfo()
                    save()
                }
                
            } else if detailItem.type == .gender { // 性别
                YHSheetPickerView.show(type: .gender, selectTitle: child?.sexName()) {
                    [weak self] selectItem in
                    guard let self = self else { return }
                    self.child?.setSexName(selectItem.title)
                    self.loadInfo()
                    save()
                }
                
            } else if detailItem.type == .marriageState { // 婚姻
                YHSheetPickerView.show(type: .marriageText, selectTitle: self.child?.married) {
                    [weak self] selectItem in
                    guard let self = self else { return }
                    self.child?.married = selectItem.title
                    self.loadInfo()
                    save()
                }
            }
        }
    }
        
    func createCorner(cell: UITableViewCell, arr: [Any], indexPath: IndexPath) {
        // 复用时需清理
        cell.layer.mask = nil
        // 设置每块section圆角
        if indexPath.row == 0 {
            let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
            cell.createCorner(CGSize(width: 12.0, height: 12.0), corner)
            
        } else if indexPath.row == arr.count-1 {
            let corner = UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue)
            cell.createCorner(CGSize(width: 12.0, height: 12.0), corner)
            
        } else {
            cell.layer.mask = nil
        }
    }
}

extension YHChildBasicInfoVC {
   
    // 检查填写信息完整性
    func checkIntegrity() -> Bool {
        
        guard let child = child else { return false}
        if isEmptyString(child.subsetName)
            || child.sex == 0
            || isEmptyString(child.married) {
            return false
        }
        
        if child.isBirthOverSeas() {
            if isEmptyString(child.birthPlace.foreign) {
                return false
            }
            
        } else {
            if isEmptyString(child.birthPlace.details) {
                return false
            }
        }
        
//        if isEmptyString(child.occupation) {
//            return false
//        }
//        if child.isNowHaveJob(), isEmptyString(child.occupationName)  {
//            return false
//        }
        
//        if child.isFollow() {
//            if child.isNowInHK() {
//                if isEmptyString(child.childInHk.info) ||  isEmptyString(child.hkIdentity) {
//                    return false
//                }
//            }
//        }
        
        if child.isHaveHKIdentityCard() {
            if isEmptyString(child.hkIdentityCard) {
                return false
            }
        }
        return true
    }
    
    func nextStep() -> Bool {
        let isChecked = checkIntegrity()
        isNeedShowError = !isChecked
        
        loadInfo()
        
        if !isChecked {
            YHHUD.flash(message: "资料还未填完")
            return false
        }
        guard let child = child else { return false}

        if child.isHaveHKIdentityCard(), let hkIdentityCard = child.hkIdentityCard, !hkIdentityCard.isHKIdentityCardNumber() {
            isNeedShowError = true
            loadInfo()
            YHHUD.flash(message: "请输入正确的香港身份证号码")
            return false
        }
        return true
    }
    
    func save() {
        if let delegate = delegate, delegate.responds(to: #selector(YHSpouseInfoVCProtocol.saveInfoSilent)) {
            delegate.saveInfoSilent()
        }
    }
}
