//
//  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:.plain)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.estimatedSectionHeaderHeight = 14.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        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()
        createUI()
        loadInfo()
    }
    
    func createUI() {
        
        view.addSubview(tableView);
        let topHeight = k_Height_NavigationtBarAndStatuBar+YHStepView.height
        let bottomHeight = k_Height_safeAreaInsetsBottom() + 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.placeHolder = "请输入子女姓名".local
        item00.tips = "请输入子女姓名".local
        let item01 = YHFormDetailItem(type: .everName, isNeed: false)
        item01.value = child.usedName
        item01.placeHolder = "请输入曾用名".local
        let item02 = YHFormDetailItem(type: .befourMarryFirstName, isNeed: false)
        item02.value = child.surname
        item02.placeHolder = "请输入婚前姓氏".local
        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 item05 = YHFormDetailItem(type: .birthday)
        item05.value = child.birthday
        item05.tips = "请选择出生日期".local
        item05.placeHolder = "请选择出生日期".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.placeHolder = "请输入".local
            item07.tips = "请输入出生城市".local

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

        // 香港身份证
        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
            item41.tips = "请输入香港身份证号".local
            arr4.append(item41)
        }

        items.append(contentsOf: [arr0, arr1, arr2, arr3, arr4])
        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 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 == .birthday
                || 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 { // 标题
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemTitleCell.cellReuseIdentifier, for: indexPath) as! YHFormItemTitleCell
            cell.setTitleAndSubTitle(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.placeHolder = detailItem.placeHolder
                cell.title = detailItem.getTitle()
                cell.text = detailItem.value
                cell.setTips(detailItem.tips, isShow: isNeedShowError && detailItem.isShowTips)
                cell.textInputCondtion = {
                    textField in
                    
                    if detailItem.type == .befourMarryFirstName { // 仅支持输入最多30个大写字母
                        let regex = "[^A-Z]+"
                        textField.limitInputWithPattern(pattern:regex, 30)
                        return true
                    }
                    
                    var max = -1
                    if detailItem.type == .childName ||
                        detailItem.type == .everName {
                        max = 30
                    } else if detailItem.type == .birthCity ||
                              detailItem.type == .occupationName
                    {
                        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 {
                        self.child?.surname = text ??  ""
                        
                    } else if detailItem.type == .birthCity {
                        self.child?.birthPlace.foreign = text ?? ""
                        
                    } else if detailItem.type == .occupationName {
                        self.child?.occupationName = text ??  ""
                        
                    } else if detailItem.type == .hkIdentityCardNumber {
                        self.child?.hkIdentityCard = text
                    }
                    
                    if isEditEnd {
                        self.loadInfo()
                        save()
                    }
                }
                return cell
            }
            
            if cellType == .selectSheet { // 点击选择列表cell
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier, for: indexPath) as! YHFormItemSelectSheetCell
                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
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemDoubleChoiceCell.cellReuseIdentifier, for: indexPath) as! YHFormItemDoubleChoiceCell
                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.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)
                        } 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, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 14.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 || detailItem.type == .stayHKDate { // 出生日期/获准滞留至
                YHDatePickView.show(type: .yyyymmdd) { [weak self] date in
                    guard let self = self else { return }
                    
                    if detailItem.type == .birthday {
                        self.child?.birthday = date
                    } else if detailItem.type == .stayHKDate {
                        self.child?.childInHk.info =  date
                    }
                    self.loadInfo()
                    save()
                }
                
            } else if detailItem.type == .birthCity { // 出生城市
                
                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: .marriage, 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: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 YHChildBasicInfoVC {
   
    // 检查填写信息完整性
    func checkIntegrity() -> Bool {
        
        guard let child = child else { return false}
        if isEmptyString(child.subsetName)
            || child.sex == 0
            || isEmptyString(child.married)
            || isEmptyString(child.birthday){
            return false
        }
        
        if child.isBirthOverSeas() {
            if isEmptyString(child.birthPlace.foreign) {
                return false
            }
            
        } else {
            if isEmptyArray(child.birthPlace.area) {
                return false
            }
        }
        
        if isEmptyString(child.occupation) {
            return false
        }
        if child.isNowHaveJob(), isEmptyString(child.occupationName)  {
            return false
        }
        
        if child.isNowInHK() {
            if isEmptyString(child.childInHk.info) ||  isEmptyString(child.hkIdentity) {
                return false
            }
        }
        
        if child.isHaveHKIdentityCard() {
            if isEmptyString(child.hkIdentityCard) {
                return false
            }
            if let hkIdentityCard = child.hkIdentityCard, !hkIdentityCard.isHKIdentityCardNumber() {
                return false
            }
        }
        return true
    }
    
    func nextStep()->Bool {
        let isChecked = checkIntegrity()
        isNeedShowError = !isChecked
        
        loadInfo()
        
        if !isChecked {
            YHHUD.flash(message: "资料还未填完")
            return false
        }
        return true
    }
    
    func save() {
        if let delegate = delegate, delegate.responds(to: #selector(YHSpouseInfoVCProtocol.saveInfoSilent)) {
            delegate.saveInfoSilent()
        }
    }
}

