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

import UIKit

enum HKFormItemCellType: Int {
    
    case defaultType = 0
    case title = 1
    case enterDetail = 2
    case inputText = 3
    case selectSheet = 4
    case twoChoice = 5
    case addItem = 6
    case degreeDetailInfo = 7
    case onlyTwoChoice = 8
    
}

class YHSpouseBasicInfoVC: YHBaseViewController {
    
    var spouse:YHFamilyMember?
    weak var delegate:YHSpouseInfoVCProtocol?

    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 = .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()
        gk_navTitle = "配偶基本信息填写".local
        createUI()
        loadBasicInfo()
    }
    
    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().offset(topHeight)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.bottom.equalToSuperview().offset(-bottomHeight)
        }
    }
    
    func loadBasicInfo() {
        
        guard let spouse = spouse else { return }
        
        items.removeAll()
        
        // 配偶信息
        let title0 = YHFormTitleItem(type: .spouseInfo)
        let item00 = YHFormDetailItem(type: .spouseName)
        item00.placeHolder = "请输入".local
        item00.value = spouse.subsetName
        
        let item01 = YHFormDetailItem(type: .everName, isNeed: false)
        item01.placeHolder = "选填".local
        item01.value = spouse.usedName
        
        let item02 = YHFormDetailItem(type: .befourMarryFirstName, isNeed: false)
        item02.placeHolder = "如有则填写，仅支持输入字".local
        item02.value = spouse.surname
        
        let item03 = YHFormDetailItem(type: .birthday)
        item03.placeHolder = "请选择".local
        item03.value = spouse.birthday
        
        let item04 = YHFormDetailItem(type: .birthNation)
        item04.value = String(spouse.isBirthOverSeas())
        
        let item05 = YHFormDetailItem(type: .birthCity)
        if spouse.isBirthOverSeas() {
            item05.value = spouse.birthPlace?.foreign
            item05.placeHolder = "请输入".local
        } else {
            item05.value = spouse.birthPlace?.area?.joined(separator: ",")
            item05.placeHolder = "请选择".local
        }
        let arr0:[YHFormItemProtocol] = [title0, item00, item01, item02, item03, item04, item05]
            
        // 职业信息
        let title1 = YHFormTitleItem(type: .occupationInfo)
        let item10 = YHFormDetailItem(type: .occupation)
        item10.value = spouse.occupation
        item10.placeHolder = "请输入".local
        var arr1:[YHFormItemProtocol] = [title1, item10]
        
        if spouse.isNowHaveJob()  {
            let item11 = YHFormDetailItem(type: .occupationName)
            item11.value = spouse.occupationName
            item11.placeHolder = "请输入".local
            arr1.append(item11)
        }
        
        // 学位信息
        let title2 = YHFormTitleItem(type: .degreeInfo)
        let item20 = YHFormDetailItem(type: .ownDegree)
        item20.placeHolder = "请选择".local
        item20.value = spouse.haveDegreeName()
        var arr2:[YHFormItemProtocol] = [title2, item20]
        
        if spouse.isHaveDegree() { // 选择了有学位
            if let degreeArr = spouse.hasDegreeJson, !degreeArr.isEmpty {
                for degreeInfo in degreeArr {
                    let item = YHFormDetailItem(type: .degreeDetailInfo)
                    arr2.append(item)
                }
            } else { // 学位数组为空则添加一个
                let item = YHFormDetailItem(type: .degreeDetailInfo)
                let newDegree = YHHasDegreeJson()
                spouse.hasDegreeJson = [newDegree]
                arr2.append(item)
            }
            // 添加一行增加学历学位信息
            let item = YHFormAddItem(type: .addDegree)
            arr2.append(item)
        }
        
        
        
        // 在港信息
        let title3 = YHFormTitleItem(type: .inHongKongInfo)
        let item30 = YHFormDetailItem(type: .isNowInHK)
        item30.value = String(spouse.isNowInHK())
        var arr3:[YHFormItemProtocol] = [title3, item30]
        
        
        if spouse.isNowInHK() { // 目前在港才显示 逗留期限和在港身份
            let item31 = YHFormDetailItem(type: .stayHKDate)
            item31.placeHolder = "请选择".local
            item31.value = spouse.childInHk?.info
            
            let item32 = YHFormDetailItem(type: .roleInHK)
            item32.placeHolder = "请选择".local
            item32.value = spouse.hkIdentity
            
            arr3.append(contentsOf: [item31, item32])
        }

        // 香港身份证
        let title4 = YHFormTitleItem(type: .hkIdentityCardInfo)
        let item40 = YHFormDetailItem(type: .isHaveHkIdentityCard)
        item40.value = String(spouse.isHaveHKIdentityCard())
        var arr4:[YHFormItemProtocol] = [title4, item40]

        if spouse.isHaveHKIdentityCard() { // 办理过香港身份证才显示证号
            let item41 = YHFormDetailItem(type: .hkIdentityCardNumber)
            item41.value = spouse.hkIdentityCard
            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 YHFormAddItem {
            return .addItem
        }
        if item is YHFormDetailItem {
            let detailItem = item as! YHFormDetailItem
            
            if detailItem.type == .birthCity {
                var isBirthOverSeas = false
                if let spouse = spouse {
                    isBirthOverSeas = spouse.isBirthOverSeas()
                }
                if isBirthOverSeas {
                    return .inputText
                } else {
                    return .selectSheet
                }
            }
            
            if detailItem.type == .spouseName
               || 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
            {
                return .selectSheet
            }
            if detailItem.type == .birthNation
                || detailItem.type == .isNowInHK
                || detailItem.type == .isHaveHkIdentityCard
            {
                return .twoChoice
            }
            
            if detailItem.type == .degreeDetailInfo
            {
                return .degreeDetailInfo
            }
        }
        return .defaultType
    }
    
}

extension YHSpouseBasicInfoVC : 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()
            cell.clickBlock = {
                [weak self] in
                guard let self = self else { return }
                let newDegree = YHHasDegreeJson()
                self.spouse?.hasDegreeJson?.append(newDegree)
                self.loadBasicInfo()
            }
            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.isShowBottomLine = indexPath.row != arr.count-1

                cell.textChange = {
                    [weak self] (text, isEditEnd) in
                    guard let self = self else { return }
                    if detailItem.type == .spouseName {
                        self.spouse?.subsetName = text
                    } else if detailItem.type == .everName {
                        self.spouse?.usedName = text
                    } else if detailItem.type == .befourMarryFirstName {
                        self.spouse?.surname = text
                    } else if detailItem.type == .birthCity {
                        self.spouse?.birthPlace?.foreign = text
                    } else if detailItem.type == .occupationName {
                        self.spouse?.occupationName = text
                    } else if detailItem.type == .hkIdentityCardNumber {
                        self.spouse?.hkIdentityCard = text
                    }
                    
                    if isEditEnd {
                        self.loadBasicInfo()
                        if let delegate = delegate {
                            delegate.saveInfo?()
                        }
                    }
                }
                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.isShowBottomLine = indexPath.row != arr.count-1

                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.isShowBottomLine = indexPath.row != arr.count-1

                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.spouse?.setBirthOverSeas(selectItem.title == "国外".local)
                        self.loadBasicInfo()
                    }
                } else if detailItem.type == .isHaveHkIdentityCard || detailItem.type == .isNowInHK { // 是否办理过香港身份证 是否在岗
                    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 == .isNowInHK {
                            self.spouse?.setNowIsInHK(selectItem.title == "是".local)
                        } else if detailItem.type == .isHaveHkIdentityCard {
                            self.spouse?.setHaveHKIdentityCard(selectItem.title == "是".local)
                        }
                        self.loadBasicInfo()
                    }
                }
                
                return cell
            }
            
            if cellType == .degreeDetailInfo { // 学位cell
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemDegreeInfoCell.cellReuseIdentifier, for: indexPath) as! YHFormItemDegreeInfoCell
                
                
                if let degreeArr = self.spouse?.hasDegreeJson {
                    if indexPath.row-2 < degreeArr.count {
                        let degreeInfo = degreeArr[indexPath.row-2]
                        cell.title = String(format: "%@%d", "学位信息".local, indexPath.row-1)
                        cell.degreePlace = degreeInfo.address
                       
                        // 前两行是 学历学位信息标题 和 是否拥有学位
                        cell.showDeleteBtn(indexPath.row > 2)
                        
                        if let degree = degreeInfo.degree {
                            if let degreeIndex = Int(degree), let subType = YHPickerViewDegreeType(rawValue: degreeIndex) {
                                cell.degree = YHFormPickerViewSubType.degree(subType).title
                            } else {
                                cell.degree = ""
                            }
                        } else {
                            cell.degree = ""
                        }
                        if let address = degreeInfo.address {
                            if let addressIndex = Int(address), let subType = YHPickerViewDegreeLocationType(rawValue: addressIndex) {
                                cell.degreePlace = YHFormPickerViewSubType.degreeLocation(subType).title
                            } else {
                                cell.degreePlace = ""
                            }
                        } else {
                            cell.degreePlace = ""
                        }
                        cell.degreeClickBlock = {
                            YHFormPickerView.show(type: .degree) { [weak self] selectType in
                                guard let self = self else { return }
                                degreeInfo.degree = String(selectType.index)
                                self.loadBasicInfo()
                            }
                        }
                        cell.areaClickBlock = {
                            YHFormPickerView.show(type: .degreeLocation) { [weak self] selectType in
                                guard let self = self else { return }
                                degreeInfo.address = String(selectType.index)
                                self.loadBasicInfo()
                            }
                        }
                        cell.deleteBlock = {
                            [weak self] in
                            guard let self = self else { return }
                            self.spouse?.hasDegreeJson?.remove(at: indexPath.row-2)
                            self.loadBasicInfo()
                        }
                    }
                    
                }
                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 {
        
        if indexPath.section >= items.count { return 0.0 }
        let arr:[YHFormItemProtocol] = items[indexPath.section]
        if indexPath.row >= arr.count {  return 0.0 }
        
        let item = arr[indexPath.row]
        
        if item is YHFormTitleItem { // 标题
            return 52.0
        }
        
        if item is YHFormAddItem {
            return 70.0
        }
        
        if item is YHFormDetailItem {
            return UITableView.automaticDimension
        }
        return 52.0
    }
    
    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.spouse?.birthday = date
                    } else if detailItem.type == .stayHKDate {
                        self.spouse?.childInHk?.info =  date
                    }
                    self.loadBasicInfo()
                }
                
            } else if detailItem.type == .birthCity { // 出生城市
                
                var isBirthOverSeas = false
                if let spouse = spouse {
                    isBirthOverSeas = spouse.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)")
                     self.spouse?.birthPlace?.area = [string2, string3, string4]
                     self.loadBasicInfo()
                 }
                self.present(vc, animated: true)
 
            } else if detailItem.type == .roleInHK { // 在港身份
                
                let identity = self.spouse?.hkIdentity ?? ""
                YHFormPickerView.show(type: .identity, selectTitle:identity ) {
                    [weak self] selectType in
                    guard let self = self else { return }
                    self.spouse?.hkIdentity = selectType.title
                    self.loadBasicInfo()
                }
            } else if detailItem.type == .occupation {
                let occupation = self.spouse?.occupation ?? ""
                YHFormPickerView.show(type: .occupation, selectTitle:occupation ) {
                    [weak self] selectType in
                    guard let self = self else { return }
                    self.spouse?.occupation = selectType.title
                    self.loadBasicInfo()
                }
            } else if detailItem.type == .ownDegree {
                let hasDegree = self.spouse?.haveDegreeName() ?? "无学位"
                YHFormPickerView.show(type: .ownDegree, selectTitle:hasDegree ) {
                    [weak self] selectType in
                    guard let self = self else { return }
                    let ownDegree = (selectType.index == YHFormPickerViewSubType.ownDegree(.hasDegree).index)
                    self.spouse?.setHaveDegree(ownDegree)
                    self.loadBasicInfo()
                }
                
            }
        }
    }
        
    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
        }
    }
}
