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

import UIKit

class YHBrotherInfoVC: YHBaseViewController {
    
    var orderId: Int = 0
    var brotherInfo: YHFamilyMember?
    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()
        gk_navTitle = "兄弟姐妹信息填写".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().offset(-k_Height_safeAreaInsetsBottom())
            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 brotherInfo = brotherInfo else { return }

        items.removeAll()
        

        // 兄弟姐妹信息
        let title1 = YHFormTitleItem(type: .brotherInfo)
        let item10 = YHFormDetailItem(type: .brotherName, value:brotherInfo.subsetName, tips:"请输入姓名".local)
        let item11 = YHFormDetailItem(type: .birthday, value:brotherInfo.birthday, tips:"请选择出生日期".local )
        let item12 = YHFormDetailItem(type: .birthNation, value:String(brotherInfo.isBirthOverSeas()))

        var birthCity = ""
        if brotherInfo.isBirthOverSeas() {
            birthCity = brotherInfo.birthPlace.foreign
        } else {
            birthCity = brotherInfo.birthPlace.area.joined(separator: ",")
        }
        let item13 = YHFormDetailItem(type: .birthCity, value: birthCity, tips:"请选择出生城市".local)
        let item14 = YHFormDetailItem(type: .gender, value:brotherInfo.sexName(), tips:"请选择性别".local)
        let item15 = YHFormDetailItem(type: .marriageState, value:brotherInfo.married, tips:"请选择婚姻状况".local)
        let arr1:[YHFormItemProtocol] = [title1, item10, item11, item12, item13, item14, item15]

        
        // 职业信息
        let title2 = YHFormTitleItem(type: .occupationInfo)
        let item20 = YHFormDetailItem(type: .occupation, value:brotherInfo.occupation, tips:"请选择职业".local)
        var arr2:[YHFormItemProtocol] = [title2, item20]
    
        
        // 居住信息
        let title3 = YHFormTitleItem(type: .liveInfo)
        let item30 = YHFormDetailItem(type: .liveNationOrArea, value:brotherInfo.liveCountry, tips:"请选择国家/地区".local)
        let arr3:[YHFormItemProtocol] = [title3, item30]
        
        // 香港身份证
        let title4 = YHFormTitleItem(type: .hkIdentityCardInfo)
        let item40 = YHFormDetailItem(type: .isHaveHkIdentityCard, value:String(brotherInfo.isHaveHKIdentityCard()))
        var arr4:[YHFormItemProtocol] = [title4, item40]

        if brotherInfo.isHaveHKIdentityCard() { // 办理过香港身份证才显示证号
            let item41 = YHFormDetailItem(type: .hkIdentityCardNumber, value:brotherInfo.hkIdentityCard, tips: "请输入正确的香港身份证号码")
            arr4.append(item41)
        }
        items.append(contentsOf: [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 brotherInfo = brotherInfo {
                    isBirthOverSeas = brotherInfo.isBirthOverSeas()
                }
                if isBirthOverSeas {
                    return .inputText
                } else {
                    return .selectSheet
                }
            }
            
            if detailItem.type == .brotherName
                || detailItem.type == .occupationName
                || detailItem.type == .hkIdentityCardNumber
            {
                return .inputText
            }
            
            if detailItem.type == .birthday
                || detailItem.type == .marriageState
                || detailItem.type == .occupation
                || detailItem.type == .liveNationOrArea
                || detailItem.type == .gender
            {
                return .selectSheet
            }
            if detailItem.type == .birthNation || detailItem.type == .isHaveHkIdentityCard
            {
                return .twoChoice
            }
        }
        return .defaultType
    }
    
}

extension YHBrotherInfoVC : 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
                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 == .brotherName {
                        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 == .brotherName {
                        self.brotherInfo?.subsetName = text ?? ""
    
                    } else if detailItem.type == .birthCity {
                        self.brotherInfo?.birthPlace.foreign = text ?? ""
                        
                    } else if detailItem.type == .occupationName {
                        self.brotherInfo?.occupationName = text ?? ""
                        
                    } else if detailItem.type == .hkIdentityCardNumber {
                        self.brotherInfo?.hkIdentityCard = text ?? ""
                    }
                    
                    if isEditEnd {
                        self.loadInfo()
                        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.brotherInfo?.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 {
                            self.brotherInfo?.setHaveHKIdentityCard(selectItem.title == "是".local)
                        }
                        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 brotherInfo = brotherInfo, brotherInfo.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.brotherInfo?.setIsDead(selectItem.title == "已故".local)
                    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) { [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.brotherInfo?.birthday = dateStr
                    }
                    self.loadInfo()
                    saveInfoSilent()
                }
                
            } else if detailItem.type == .birthCity { // 出生城市
                
                var isBirthOverSeas = false
                if let brotherInfo = brotherInfo {
                    isBirthOverSeas = brotherInfo.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.brotherInfo?.birthPlace.area = citys
                     self.loadInfo()
                     saveInfoSilent()
                 }
                self.present(vc, animated: true)
 
            } else if detailItem.type == .occupation { // 职业
            
                let occupation = self.brotherInfo?.occupation ?? ""
                YHSheetPickerView.show(type: .profession, selectTitle:occupation) {
                    [weak self] selectItem in
                    guard let self = self else { return }
                    self.brotherInfo?.occupation = selectItem.title
                    self.loadInfo()
                    saveInfoSilent()
                }
                
            } else if detailItem.type == .marriageState { // 婚姻
                let marriage = self.brotherInfo?.married
                YHSheetPickerView.show(type: .marriage, selectTitle:marriage) {
                    [weak self] selectItem in
                    guard let self = self else { return }
                    self.brotherInfo?.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.brotherInfo?.liveCountry = string
                     self.loadInfo()
                     saveInfoSilent()
                 }
                self.navigationController?.pushViewController(vc)
                
            } else if detailItem.type == .gender { // 性别
                guard let brotherInfo = brotherInfo else { return }
        
                YHSheetPickerView.show(type: .gender, selectTitle:brotherInfo.sexName()) {
                    [weak self] selectItem in
                    guard let self = self else { return }
                    self.brotherInfo?.setSexName(selectItem.title)
                    self.loadInfo()
                    saveInfoSilent()
                }
            }
        }
    }
        
    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 YHBrotherInfoVC {
    
    // 检查填写信息完整性
    func checkIntegrity() -> Bool {
        
        guard let brotherInfo = brotherInfo else { return false }

        if isEmptyString(brotherInfo.subsetName) || isEmptyString(brotherInfo.birthday) || isEmptyString(brotherInfo.married) || isEmptyString(brotherInfo.occupation) {
            
            return false
        }
        
    
        if brotherInfo.isBirthOverSeas() {
            if isEmptyString(brotherInfo.birthPlace.foreign) {
                return false
            }
        } else {
            if isEmptyArray(brotherInfo.birthPlace.area) {
                return false
            }
        }
        
        if brotherInfo.sex == 0 {
            return false
        }
        
        if brotherInfo.isNowHaveJob()  {
            if isEmptyString(brotherInfo.occupationName) {
                return false
            }
        }
        
        if brotherInfo.isHaveHKIdentityCard() { // 办理过香港身份证才显示证号
            
            if isEmptyString(brotherInfo.hkIdentityCard) {
                return false
            }
            
            if let hkIdCard = brotherInfo.hkIdentityCard, !hkIdCard.isHKIdentityCardNumber() {
                return false
            }
        }
        
        return true
    }
    
    // isSubmit 是否是提交 isSilent:是否显示toast
    func saveInfo(isSubmit:Bool, isLoading:Bool, callBack:((Bool)->Void)?) {
        
        if isSubmit {
            let isChecked = checkIntegrity()
            isNeedShowError = !isChecked
            
            self.tableView .reloadData()
            
            if !isChecked {
                YHHUD.flash(message: "资料还未填完")
                return
            }
        }
        
        guard let brotherInfo = brotherInfo else { return }
        guard let info = brotherInfo.toDictionary() else { return }
        
        let dict:[String: Any] = ["order_id":orderId,
                                  "relation":brotherInfo.relation,
                                  "step":brotherInfo.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 brotherInfo = brotherInfo else { return }
        if brotherInfo.detailId == 0 { return }
        saveInfo(isSubmit: false, isLoading: false, callBack: nil)
    }
}

