//
//  YHGCIncomeRecordWorkExperienceViewController.swift
//  galaxy
//
//  Created by alexzzw on 2024/11/15.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import AttributedString
import IQKeyboardManagerSwift
import UIKit

class YHGCIncomeRecordWorkExperienceViewController: YHBaseViewController {
    enum TableRow {
        case header(_ title: String)
        case incomeFrom(_ title: String, _ placeholder: String)
        case incomeTypeSelect(_ title: String, _ detail: String, _ isSelectedOne: Bool)
        case incomeTypes(_ types: [YHGCIncomeType])
        case inputMoney(_ title: String, _ detail: String?, _ inputStr: String?, _ showBottomLine: Bool, _ showStar: Bool, _ isIncomeMoney: Bool)
        case inputRemark(_ detail: String)
        case infoSelect(_ title: String, _ placeholder: String)
        case infoTillNowSelect(_ title: String, _ placeholder: String)
        case infoEdit(_ title: String, _ placeholder: String)
        case infoCheckbox(_ title: String)
    }

    private lazy var datas: [[TableRow]] = []

    private var selectedTypes: [YHGCIncomeType] = []

    private let currencyRate = 0.92
    private var isSaving = false
    var submitSuccess: (() -> Void)?

    // 校验字段
    /// 是否选定公司
    private var isCompanyOK = true
    private var companyIndexPath: IndexPath?
    /// 是否选定收入类型
    private var isIncomeTypeOK = true
    private var incomeTypeIndexPath: IndexPath?
    /// 是否收入金额已填写
    private var isIncomeMoneyOK = true
    private var incomMoneyIndexPath: IndexPath?
    
    /// 是否选定派薪国家
    private var isCountryOK = true
    private var countryIndexPath: IndexPath?
    /// 是否选定派薪城市
    private var isCityOK = true
    private var cityIndexPath: IndexPath?
    
    /// 是否选定职位
    private var isPositionOK = true
    private var positionIndexPath: IndexPath?
    /// 是否选定入职年月
    private var isEntryTimeOK = true
    private var entryTimeIndexPath: IndexPath?
    /// 是否选定离职年月
    private var isEndTimeOK = true
    private var endTimeIndexPath: IndexPath?
    
    /// 是否选定工作证明
    private var isWorkCertificateOK = true
    private var workCertificateIndexPath: IndexPath?
    /// 是否选定职业界别
    private var isWorkTypeOK = true
    private var workTypeIndexPath: IndexPath?
    
    /// 是否选定具体职业界别
    private var isFinalWorkTypeOK = true
    private var finalWorkTypeIndexPath: IndexPath?
    
    private lazy var viewModel = YHGCIncomeRecordWorkExperienceViewModel()

    private lazy var submitButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
        button.setTitle("提交", for: .normal)
        button.setTitle("提交", for: .highlighted)
        button.setTitleColor(UIColor(hex: 0xFFFFFF), for: .normal)
        button.setTitleColor(UIColor(hex: 0xFFFFFF), for: .highlighted)
        button.addTarget(self, action: #selector(clickSubmitButton), for: .touchUpInside)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.backgroundColor = .brandMainColor
        return button
    }()

    private lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()

    private lazy var tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .grouped)
        view.estimatedSectionHeaderHeight = 16.0
        view.estimatedSectionFooterHeight = 0.01
        view.sectionHeaderHeight = 16.0
        view.sectionFooterHeight = 0.01
        view.contentInsetAdjustmentBehavior = .never
        view.showsVerticalScrollIndicator = false
        view.separatorStyle = .none
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .clear
        view.tableFooterView = UITableViewHeaderFooterView()
        view.rowHeight = UITableView.automaticDimension

        view.register(YHWorkingHourHeaderCell.self, forCellReuseIdentifier: YHWorkingHourHeaderCell.cellReuseIdentifier)
        view.register(YHIncomeRecordFromCell.self, forCellReuseIdentifier: YHIncomeRecordFromCell.cellReuseIdentifier)
        view.register(YHIncomeTypeSelectCell.self, forCellReuseIdentifier: YHIncomeTypeSelectCell.cellReuseIdentifier)
        view.register(YHIncomeTypesCell.self, forCellReuseIdentifier: YHIncomeTypesCell.cellReuseIdentifier)
        view.register(YHIncomeInputMoneyCell.self, forCellReuseIdentifier: YHIncomeInputMoneyCell.cellReuseIdentifier)
        view.register(YHIncomeRemarkCell.self, forCellReuseIdentifier: YHIncomeRemarkCell.cellReuseIdentifier)
        view.register(YHIncomeDocumentationConfirmationCell.self, forCellReuseIdentifier: YHIncomeDocumentationConfirmationCell.cellReuseIdentifier)

        view.register(YHIncomeDateTillNowCell.self, forCellReuseIdentifier: YHIncomeDateTillNowCell.cellReuseIdentifier)
        view.register(YHIncomeInfoSelectCell.self, forCellReuseIdentifier: YHIncomeInfoSelectCell.cellReuseIdentifier)
        view.register(YHIncomeInfoEditCell.self, forCellReuseIdentifier: YHIncomeInfoEditCell.cellReuseIdentifier)
        view.register(YHInfoQuestionSelectionCell.self, forCellReuseIdentifier: YHInfoQuestionSelectionCell.cellReuseIdentifier)

        view.keyboardDismissMode = .onDrag
        return view
    }()

    private let incomeId: Int
    private let orderId: Int
    init(incomeId: Int, orderId: Int) {
        self.incomeId = incomeId
        self.orderId = orderId
        super.init(nibName: nil, bundle: nil)
    }

    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        if incomeId != 0 {
            requestData(isNeedLoading: true)
        } else {
            viewModel.position.order_id = orderId
            setupData()
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.isEnabled = true
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.isEnabled = false
    }
}

extension YHGCIncomeRecordWorkExperienceViewController {
    @objc private func clickSubmitButton() {
        submitIncome(complete: { _ in })
    }

    private func setupUI() {
        gk_navTitle = "收入记录/工作经验填写"
        gk_navBarAlpha = 1.0
        gk_navBackgroundColor = .white

        view.backgroundColor = UIColor.contentBkgColor
        view.addSubview(tableView)
        view.addSubview(bottomView)
        bottomView.addSubview(submitButton)

        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-64)
        }

        submitButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.top.equalToSuperview().offset(10)
            make.height.equalTo(44)
        }

        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(bottomView.snp.top)
        }

        tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 44))
    }

    private func setupData() {
        selectedTypes = viewModel.position.type_of_income.compactMap {
            YHGCIncomeType(rawValue: $0)
        }
        var firstSection: [TableRow] = [.header("收入信息"), .incomeFrom("收入来源公司", "请填写公司全称"), .incomeTypeSelect("收入类型(多选)", "请选择", selectedTypes.count > 0)]
        if selectedTypes.count > 0 {
            firstSection.append(.incomeTypes(selectedTypes))
        }
        let hkdFmt = currencyFormat("")
        let rmbFmt = currencyFormat("¥")
        let rate = getCurrentRate()
        if selectedTypes.contains(.incomeOfMainland) || selectedTypes.contains(.incomeOfHKCompanies) || selectedTypes.contains(.incomeOfMacauCompanies) || selectedTypes.contains(.incomeOfOtherOverseasCompanies) {
            let turnover = Double(viewModel.position.turnover) ?? 0
            firstSection.append(.inputMoney("公司营业额(近一年)", "约\(hkdFmt.string(from: NSNumber(value: turnover / rate)) ?? "0")港币", rmbFmt.string(from: NSNumber(value: turnover)) ?? "0", true, false, false))
        }
        let income = Double(viewModel.position.income) ?? 0
        firstSection.append(.inputMoney("收入金额", "约\(hkdFmt.string(from: NSNumber(value: income / rate)) ?? "0")港币", rmbFmt.string(from: NSNumber(value: income)) ?? "0", false, true, true))
        firstSection.append(.inputRemark("注：按1港币≈\(rate)人民币计算，实际金额按递交时入境处给出的汇率为准"))
        
        let secondSection = getEnterpriseInfo()
        datas = [firstSection, secondSection]
        tableView.reloadData()
    }
    
    @discardableResult
    private func getEnterpriseInfo(needUpdateDataSource: Bool = false) -> [TableRow] {
        var secondSection: [TableRow] = [.header("企业信息"), .infoSelect("派薪国家/地区", "请选择")]
        if viewModel.position.location.country.contains("中国") {
            secondSection.append(.infoSelect("派薪城市", "请选择"))
        } else {
            secondSection.append(.infoEdit("派薪城市", "请输入"))
        }
        secondSection.append(contentsOf: [.infoEdit("职位", "请输入"), .infoSelect("入职年月", "请选择"), .infoTillNowSelect("离职年月", "请选择"), .infoCheckbox("是否可以提供工作证明"), .infoSelect("职业界别", "请选择")])
        
        if viewModel.position.company_type.contains("其他") {
            secondSection.append(.infoEdit("具体职业界别", "请输入"))
        } else {
            viewModel.position.company_type_other = ""
        }
        
        if needUpdateDataSource {
            if let index = datas.firstIndex(where: { arr in
                if arr.contains(where: { row in
                    if case let .header(title) = row, title == "企业信息" {
                        return true
                    }
                    return false
                }) {
                    return true
                }
                return false
            }) {
                datas[index] = secondSection
                tableView.reloadSections(IndexSet(arrayLiteral: index), with: .automatic)
            }
        }
        return secondSection
    }

    private func showSelectIncomeTypePopVC(selectedTypes: [YHGCIncomeType]) {
        let ctl = YHGCIncomeTypeSelectViewController(selectedTypes: selectedTypes)
        let bpc = YHBottomPresentationController(presentedViewController: ctl, presenting: self)
        bpc.customRadius = 8.0
        ctl.transitioningDelegate = bpc
        ctl.sureButtonEvent = { [weak self] selectedTypes in
            guard let self = self else {
                return
            }
            self.selectedTypes = selectedTypes
            self.updateSelectTypes()
        }
        present(ctl, animated: true, completion: nil)
    }

    private func updateSelectTypes() {
        viewModel.position.type_of_income = selectedTypes.map { $0.rawValue }
        if viewModel.position.type_of_income.count > 0 {
            isIncomeTypeOK = true
        }
        var incomeTypesIndexPath: IndexPath?
        var incomeTypeSelectIndexPath: IndexPath?
        var incomeCompanyIndexPath: IndexPath?
        datas = datas.enumerated().map { section, sectionArr in
            sectionArr.enumerated().map { row, tableRow in
                switch tableRow {
                case .incomeTypes:
                    incomeTypesIndexPath = IndexPath(row: row, section: section)
                    return .incomeTypes(selectedTypes)
                case let .incomeTypeSelect(title, detail, _):
                    incomeTypeSelectIndexPath = IndexPath(row: row, section: section)
                    return .incomeTypeSelect(title, detail, selectedTypes.count > 0)
                case let .inputMoney(_, _, _, _, _, isIncomeMoney):
                    if !isIncomeMoney {
                        incomeCompanyIndexPath = IndexPath(row: row, section: section)
                    }
                    return tableRow
                default:
                    return tableRow
                }
            }
        }
        guard let incomeTypeSelectIndexPath = incomeTypeSelectIndexPath else {
            return
        }
        if selectedTypes.count > 0 {
            if incomeTypesIndexPath == nil {
                var sectionArr = datas[incomeTypeSelectIndexPath.section]
                sectionArr.insert(.incomeTypes(selectedTypes), at: incomeTypeSelectIndexPath.row + 1)
                datas[incomeTypeSelectIndexPath.section] = sectionArr
            }
        } else {
            guard let incomeTypesIndexPath = incomeTypesIndexPath else {
                return
            }
            var sectionArr = datas[incomeTypesIndexPath.section]
            sectionArr.remove(at: incomeTypesIndexPath.row)
            datas[incomeTypesIndexPath.section] = sectionArr
        }

        if selectedTypes.contains(.incomeOfMainland) || selectedTypes.contains(.incomeOfHKCompanies) || selectedTypes.contains(.incomeOfMacauCompanies) || selectedTypes.contains(.incomeOfOtherOverseasCompanies) {
            if incomeCompanyIndexPath == nil {
                var sectionArr = datas[incomeTypeSelectIndexPath.section]
                if let incomeIndex = sectionArr.firstIndex(where: { tableRow in
                    if case let .inputMoney(_, _, _, _, _, isIncomeMoney) = tableRow, isIncomeMoney == true {
                        return true
                    } else {
                        return false
                    }
                }) {
                    let newIndex = incomeIndex // > 1 ? incomeIndex - 1 : 0
                    let hkdFmt = currencyFormat("")
                    let rmbFmt = currencyFormat("¥")
                    let rate = getCurrentRate()
                    let turnover = Double(viewModel.position.turnover) ?? 0
                    sectionArr.insert(.inputMoney("公司营业额(近一年)", "约\(hkdFmt.string(from: NSNumber(value: turnover / rate)) ?? "0")港币", rmbFmt.string(from: NSNumber(value: turnover)) ?? "0", true, false, false), at: newIndex)
                    datas[incomeTypeSelectIndexPath.section] = sectionArr
                }
            }
        } else {
            if incomeCompanyIndexPath != nil {
                var sectionArr = datas[incomeTypeSelectIndexPath.section]
                if let companyIndex = sectionArr.firstIndex(where: { tableRow in
                    if case let .inputMoney(_, _, _, _, _, isIncomeMoney) = tableRow, isIncomeMoney == false {
                        return true
                    } else {
                        return false
                    }
                }) {
                    sectionArr.remove(at: companyIndex)
                    datas[incomeTypeSelectIndexPath.section] = sectionArr
                }
            }
        }
        tableView.performBatchUpdates { [weak tableView] in
            tableView?.reloadSections(IndexSet(integer: incomeTypeSelectIndexPath.section), with: .automatic)
        }
    }
    
    private func getCurrentRate() -> Double {
        let configRate = Double(YHConfigManager.shared.reqVM.configModel?.rate ?? "") ?? 0
        let rate = configRate > 0 ? configRate : 0.92
        return rate
    }

    private func currencyFormat(_ currencySymbol: String) -> NumberFormatter {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.currencySymbol = currencySymbol
        formatter.maximumFractionDigits = 0
        return formatter
    }
}

extension YHGCIncomeRecordWorkExperienceViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard datas.count > section else {
            return 0
        }
        let sectionArr = datas[section]
        return sectionArr.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard datas.count > indexPath.section else {
            return UITableViewCell()
        }
        let sectionArr = datas[indexPath.section]
        guard sectionArr.count > indexPath.row else {
            return UITableViewCell()
        }
        let tableRow = sectionArr[indexPath.row]
        switch tableRow {
        case let .header(title):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHWorkingHourHeaderCell.cellReuseIdentifier) as? YHWorkingHourHeaderCell {
                cell.setupCellInfo(title)
                return cell
            }
        case let .incomeFrom(title, placeholder):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeRecordFromCell.cellReuseIdentifier) as? YHIncomeRecordFromCell {
                companyIndexPath = indexPath
                cell.setupCellInfo(title: title, detail: viewModel.position.company_name, showBottomLine: true, showRightArrow: true, placeholder: placeholder, needShowFailButton: !isCompanyOK)
                return cell
            }
        case let .incomeTypeSelect(title, detail, isSelectedOne):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeTypeSelectCell.cellReuseIdentifier) as? YHIncomeTypeSelectCell {
                cell.setupCellInfo(title: title, detail: detail, isSelectedOne: isSelectedOne, showBottomLine: !isSelectedOne, needShowFailButton: !isIncomeTypeOK)
                incomeTypeIndexPath = indexPath
                return cell
            }
        case let .incomeTypes(types):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeTypesCell.cellReuseIdentifier) as? YHIncomeTypesCell {
                cell.setupCellInfo(types: types.map { $0.nameString() })
                cell.didClickTypeView = { [weak self] index in
                    guard let self = self else {
                        return
                    }
                    self.selectedTypes.remove(at: index)
                    self.updateSelectTypes()
                }
                return cell
            }
        case let .inputMoney(title, detail, inputStr, showBottomLine, showStar, isIncomeMoney):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeInputMoneyCell.cellReuseIdentifier) as? YHIncomeInputMoneyCell {
                var needShowFailButton = false
                if isIncomeMoney {
                    incomMoneyIndexPath = indexPath
                    needShowFailButton = !isIncomeMoneyOK
                }
                cell.setupCellInfo(title: title, detail: detail, inputValue: inputStr, showBottomLine: showBottomLine, showStarIcon: showStar, needShowFailButton: needShowFailButton)
                cell.didBeginEditing = { textField in
                    var text = textField.text ?? ""
                    text = text.replacingOccurrences(of: "¥", with: "")
                    text = text.replacingOccurrences(of: ",", with: "")
                    if text == "0" {
                        text = ""
                    }
                    textField.text = text
                }
                cell.didEndEditing = { [weak self] textField in
                    guard let self = self else {
                        return
                    }
                    guard let text = textField.text, text.count > 0 else {
                        if self.datas.count > indexPath.section {
                            let sectionArr = self.datas[indexPath.section]
                            if sectionArr.count > indexPath.row {
                                let currentRow = sectionArr[indexPath.row]
                                if case let .inputMoney(title, _, _, showBottomLine, showStar, isIncomeMoney) = currentRow {
                                    self.datas[indexPath.section][indexPath.row] = .inputMoney(title, nil, nil, showBottomLine, showStar, isIncomeMoney)
                                    self.tableView.reloadRows(at: [indexPath], with: .automatic)
                                    if isIncomeMoney {
                                        self.viewModel.position.income = "0"
                                    } else {
                                        self.viewModel.position.turnover = "0"
                                    }
                                }
                            }
                        }
                        return
                    }
                    // 转换为数字
                    let number = Int64(text) ?? 0
                    // 格式化为带货币符号和千分位
                    let detail = Double(number) / self.currencyRate
                    if isIncomeMoney {
                        self.isIncomeMoneyOK = true
                        self.viewModel.position.income = "\(number)"
                    } else {
                        self.viewModel.position.turnover = "\(number)"
                    }

                    let rmbFormatter = self.currencyFormat("¥")
                    let hkdFormatter = self.currencyFormat("")
                    if let formattedString = rmbFormatter.string(from: NSNumber(value: number)) {
                        textField.text = formattedString
                        let detailStr = "约" + (hkdFormatter.string(from: NSNumber(value: detail)) ?? "") + "港币"
                        if self.datas.count > indexPath.section {
                            let sectionArr = self.datas[indexPath.section]
                            if sectionArr.count > indexPath.row {
                                let currentRow = sectionArr[indexPath.row]
                                if case let .inputMoney(title, _, _, showBottomLine, showStar, isIncomeMoney) = currentRow {
                                    self.datas[indexPath.section][indexPath.row] = .inputMoney(title, detailStr, formattedString, showBottomLine, showStar, isIncomeMoney)
                                    self.tableView.reloadRows(at: [indexPath], with: .automatic)
                                }
                            }
                        }
                    }
                }
                return cell
            }
        case let .inputRemark(detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeRemarkCell.cellReuseIdentifier) as? YHIncomeRemarkCell {
                cell.setupCellInfo(detail)
                return cell
            }
        case let .infoSelect(title, placeholder):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeInfoSelectCell.cellReuseIdentifier) as? YHIncomeInfoSelectCell {
                var detail = ""
                var needShowFailButton = false
                var cellType: YHResignRoundCellType = .mid
                switch title {
                case "派薪国家/地区":
                    countryIndexPath = indexPath
                    needShowFailButton = !isCountryOK
                    detail = viewModel.position.location.country
                case "派薪城市":
                    cityIndexPath = indexPath
                    needShowFailButton = !isCityOK
                    let city = viewModel.position.location.area.reduce("") { partialResult, item in
                        partialResult.count > 0 ? partialResult + "/" + item : partialResult + item
                    }
                    detail = city
                case "入职年月":
                    entryTimeIndexPath = indexPath
                    needShowFailButton = !isEntryTimeOK
                    detail = viewModel.position.entry_time
                case "职业界别":
                    workTypeIndexPath = indexPath
                    needShowFailButton = !isWorkTypeOK
                    detail = viewModel.position.company_type
                    if !detail.contains("其他") {
                        cellType = .bottom
                    }
                default:
                    break
                }
                cell.setupCellInfo(title: title, detail: detail, placeholder: placeholder, needShowFailButton: needShowFailButton, cellType: cellType)
                return cell
            }
        case let .infoTillNowSelect(title, placeholder):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeDateTillNowCell.cellReuseIdentifier) as? YHIncomeDateTillNowCell {
                endTimeIndexPath = indexPath
                let needShowFailButton = !isEndTimeOK
                let detail = viewModel.position.departure_time
                cell.setupCellInfo(title: title, detail: detail, placeholder: placeholder, needShowFailButton: needShowFailButton)
                cell.tillNowButtonEvent = { [weak self] tillNow in
                    guard let self = self else {
                        return
                    }
                    if tillNow {
                        self.viewModel.position.departure_time = "至今"
                        self.isEndTimeOK = true
                        self.tableView.reloadRows(at: [indexPath], with: .automatic)
                    } else {
                        self.viewModel.position.departure_time = ""
                        self.isEndTimeOK = false
                        self.tableView.reloadRows(at: [indexPath], with: .automatic)
                    }
                }
                return cell
            }
        case let .infoEdit(title, placeholder):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeInfoEditCell.cellReuseIdentifier) as? YHIncomeInfoEditCell {
                var detail = ""
                var needShowFailButton = false
                var cellType: YHResignRoundCellType = .mid
                switch title {
                case "派薪城市":
                    cityIndexPath = indexPath
                    needShowFailButton = !isCityOK
                    detail = viewModel.position.location.foreign
                case "职位":
                    positionIndexPath = indexPath
                    needShowFailButton = !isPositionOK
                    detail = viewModel.position.position
                case "具体职业界别":
                    finalWorkTypeIndexPath = indexPath
                    needShowFailButton = !isFinalWorkTypeOK
                    detail = viewModel.position.company_type_other
                    cellType = .bottom
                default:
                    break
                }
                cell.setupCellInfo(title: title, detail: detail, placeholder: placeholder, needShowFailButton: needShowFailButton, cellType: cellType)
                cell.didEndEditing = { [weak self] textField in
                    guard let self = self else {
                        return
                    }
                    switch title {
                    case "派薪城市":
                        self.viewModel.position.location.area = []
                        self.viewModel.position.location.foreign = textField.text ?? ""
                        self.isCityOK = (textField.text?.count ?? 0) > 0
                    case "职位":
                        self.viewModel.position.position = textField.text ?? ""
                        self.isPositionOK = (textField.text?.count ?? 0) > 0
                    case "具体职业界别":
                        self.viewModel.position.company_type_other = textField.text ?? ""
                        self.isFinalWorkTypeOK = (textField.text?.count ?? 0) > 0
                    default:
                        break
                    }
                    self.tableView.reloadRows(at: [indexPath], with: .automatic)
                }
                return cell
            }
        case let .infoCheckbox(title):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHInfoQuestionSelectionCell.cellReuseIdentifier) as? YHInfoQuestionSelectionCell {
                workCertificateIndexPath = indexPath
                cell.setupCellInfo(question: title, showBottomLine: true, needShowFailButton: !isWorkCertificateOK)
                cell.didSelectSureButton = { [weak self] selected in
                    guard let self = self else {
                        return
                    }
                    switch selected {
                    case .true:
                        self.viewModel.position.has_work_certificate = YHCheckboxSelectType.true.rawValue
                        self.isWorkCertificateOK = true
                    case .false:
                        self.viewModel.position.has_work_certificate = YHCheckboxSelectType.false.rawValue
                        self.isWorkCertificateOK = true
                    case .unknown:
                        self.viewModel.position.has_work_certificate = YHCheckboxSelectType.unknown.rawValue
                        self.isWorkCertificateOK = false
                    }
                    self.tableView.reloadRows(at: [indexPath], with: .automatic)
                }
                let selectType = YHCheckboxSelectType(rawValue: viewModel.position.has_work_certificate) ?? .unknown
                switch selectType {
                case .true:
                    cell.selectedSureButton = .true
                case .false:
                    cell.selectedSureButton = .false
                case .unknown:
                    cell.selectedSureButton = .unknown
                }
                return cell
            }
        }

        return UITableViewCell()
    }

    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()
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        guard datas.count > indexPath.section else {
            return
        }
        let sectionArr = datas[indexPath.section]
        guard sectionArr.count > indexPath.row else {
            return
        }
        let tableRow = sectionArr[indexPath.row]
        if case .incomeTypeSelect = tableRow {
            showSelectIncomeTypePopVC(selectedTypes: selectedTypes)
        } else if case .incomeFrom = tableRow {
            let vc = YHCompanySelectViewController()
            vc.backLocationStringController = { [weak self] company in
                guard let self = self else {
                    return
                }
                self.viewModel.position.company_name = company.company_name ?? ""
                self.tableView.reloadRows(at: [indexPath], with: .automatic)
                self.isCompanyOK = (company.company_name?.count ?? 0) > 0
                self.tableView.reloadRows(at: [indexPath], with: .automatic)
            }
            navigationController?.pushViewController(vc)
        } else if case let .infoSelect(title, _) = tableRow {
            switch title {
            case "派薪国家/地区":
                let vc = YHSelectCountryViewController()
                vc.backLocationStringController = { [weak self] country in
                    guard let self = self else {
                        return
                    }
                    let oldContry = self.viewModel.position.location.country
                    self.viewModel.position.location.country = country
                    self.viewModel.position.location_aboard = country.contains("中国") ? 0 : 1
                    self.isCountryOK = country.count > 0
                    if country != oldContry {
                        self.viewModel.position.location.area = []
                        self.viewModel.position.location.foreign = ""
                        self.getEnterpriseInfo(needUpdateDataSource: true)
                    } else {
                        self.tableView.reloadRows(at: [indexPath], with: .automatic)
                    }
                }
                navigationController?.pushViewController(vc)
            case "派薪城市":
                let country = viewModel.position.location.country
                var provice = ""
                if country.contains("台湾") {
                    provice = "台湾省"
                }
                if country.contains("香港") {
                    provice = "香港特别行政区"
                }
                if country.contains("澳门") {
                    provice = "澳门特别行政区"
                }
                let addressPicker = YHAddressViewController(selectProvince: provice)
                addressPicker.backLocationStringController = { [weak self] (_, province, city, _) in
                    guard let self = self else {
                        return
                    }
                    self.viewModel.position.location.area = [province, city]
                    self.viewModel.position.location.foreign = ""
                    self.isCityOK = true
                    self.tableView.reloadRows(at: [indexPath], with: .automatic)
                }
                present(addressPicker, animated: true, completion: nil)
            case "入职年月":
                let title = "选择入职年月"
                let lastIsTaday = true
                YHDatePickView.show(type: .yyyymm, title: title, lastIsTaday: lastIsTaday, currentDay: viewModel.position.entry_time) { [weak self] date in
                    guard let self = self else {
                        return
                    }
                    let format = DateFormatter()
                    format.dateFormat = "yyyy-MM"
                    if let selectDate = format.date(from: date) {
                        let selectTimeInterval = selectDate.timeIntervalSince1970
                        let currentTimeInterval = Date().timeIntervalSince1970
                        if selectTimeInterval > currentTimeInterval {
                            YHHUD.flash(message: "入职年月不能晚于当前日期")
                        } else {
                            guard let endDate = format.date(from: self.viewModel.position.departure_time) else {
                                self.viewModel.position.entry_time = date
                                self.tableView.reloadRows(at: [indexPath], with: .automatic)
                                self.isEntryTimeOK = true
                                self.tableView.reloadRows(at: [indexPath], with: .automatic)
                                return
                            }
                            let endTimeInterval = endDate.timeIntervalSince1970
                            if selectTimeInterval > endTimeInterval {
                                YHHUD.flash(message: "入职年月不能晚于离职年月")
                            } else {
                                self.isEntryTimeOK = true
                                self.viewModel.position.entry_time = date
                                self.tableView.reloadRows(at: [indexPath], with: .automatic)
                            }
                        }
                    }
                }
            case "职业界别":
                YHOtherPickerView.show(type: .position, selectTitle: viewModel.position.company_type) {[weak self] data in
                    guard let self = self else { return }
                    let companyType = self.viewModel.position.company_type
                    self.viewModel.position.company_type = data.title
                    self.isWorkTypeOK = true
                    
                    if (data.title == "其他" || companyType == "其他") && companyType != data.title {
                        self.getEnterpriseInfo(needUpdateDataSource: true)
                    } else {
                        self.tableView.reloadRows(at: [indexPath], with: .automatic)
                    }
                }
            default:
                break
            }
            
        } else if case let .infoTillNowSelect(title, _) = tableRow {
            if title == "离职年月" {
                let title = "选择离职年月"
                let lastIsTaday = true
                YHDatePickView.show(type: .yyyymm, title: title, lastIsTaday: lastIsTaday, currentDay: viewModel.position.departure_time) { [weak self] date in
                    guard let self = self else { return }
                    let format = DateFormatter()
                    format.dateFormat = "yyyy-MM"
                    if let selectDate = format.date(from: date), let startDate = format.date(from: self.viewModel.position.entry_time) {
                        let selectTimeInterval = selectDate.timeIntervalSince1970
                        let startTimeInterval = startDate.timeIntervalSince1970
                        if selectTimeInterval < startTimeInterval {
                            YHHUD.flash(message: "离职年月不能早于入职年月")
                        } else {
                            self.isEndTimeOK = true
                            self.viewModel.position.departure_time = date
                            self.tableView.reloadRows(at: [indexPath], with: .automatic)
                        }
                    } else {
                        self.isEndTimeOK = true
                        self.viewModel.position.departure_time = date
                        self.tableView.reloadRows(at: [indexPath], with: .automatic)
                    }
                }
            }
        }
    }
}

extension YHGCIncomeRecordWorkExperienceViewController {
    private func checkInput() -> Bool {
        var retValue = true
        var updateRows: [IndexPath] = []
        
        if viewModel.position.company_name.count == 0 {
            isCompanyOK = false
            if let companyIndexPath = companyIndexPath, tableView.numberOfSections > companyIndexPath.section, tableView.numberOfRows(inSection: companyIndexPath.section) > companyIndexPath.row {
                updateRows.append(companyIndexPath)
            }
            retValue = false
        }
        
        if viewModel.position.type_of_income.count == 0 {
            isIncomeTypeOK = false
            if let incomeTypeIndexPath = incomeTypeIndexPath, tableView.numberOfSections > incomeTypeIndexPath.section, tableView.numberOfRows(inSection: incomeTypeIndexPath.section) > incomeTypeIndexPath.row {
                updateRows.append(incomeTypeIndexPath)
            }
            retValue = false
        }
        if viewModel.position.income == "0" {
            isIncomeMoneyOK = false
            if let incomMoneyIndexPath = incomMoneyIndexPath, tableView.numberOfSections > incomMoneyIndexPath.section, tableView.numberOfRows(inSection: incomMoneyIndexPath.section) > incomMoneyIndexPath.row {
                updateRows.append(incomMoneyIndexPath)
            }
            retValue = false
        }
        
        if viewModel.position.location.country.count == 0 {
            isCountryOK = false
            if let countryIndexPath = countryIndexPath, tableView.numberOfSections > countryIndexPath.section, tableView.numberOfRows(inSection: countryIndexPath.section) > countryIndexPath.row {
                updateRows.append(countryIndexPath)
            }
            retValue = false
        }
        if viewModel.position.location.country.contains("中国") {
            if viewModel.position.location.area.count == 0 {
                isCityOK = false
                if let cityIndexPath = cityIndexPath, tableView.numberOfSections > cityIndexPath.section, tableView.numberOfRows(inSection: cityIndexPath.section) > cityIndexPath.row {
                    updateRows.append(cityIndexPath)
                }
                retValue = false
            }
        } else {
            if viewModel.position.location.foreign.count == 0 {
                isCityOK = false
                if let cityIndexPath = cityIndexPath, tableView.numberOfSections > cityIndexPath.section, tableView.numberOfRows(inSection: cityIndexPath.section) > cityIndexPath.row {
                    updateRows.append(cityIndexPath)
                }
                retValue = false
            }
        }
        
        if viewModel.position.position.count == 0 {
            isPositionOK = false
            if let positionIndexPath = positionIndexPath, tableView.numberOfSections > positionIndexPath.section, tableView.numberOfRows(inSection: positionIndexPath.section) > positionIndexPath.row {
                updateRows.append(positionIndexPath)
            }
            retValue = false
        }
        
        if viewModel.position.entry_time.count == 0 {
            isEntryTimeOK = false
            if let entryTimeIndexPath = entryTimeIndexPath, tableView.numberOfSections > entryTimeIndexPath.section, tableView.numberOfRows(inSection: entryTimeIndexPath.section) > entryTimeIndexPath.row {
                updateRows.append(entryTimeIndexPath)
            }
            retValue = false
        }
        
        if viewModel.position.departure_time.count == 0 {
            isEndTimeOK = false
            if let endTimeIndexPath = endTimeIndexPath, tableView.numberOfSections > endTimeIndexPath.section, tableView.numberOfRows(inSection: endTimeIndexPath.section) > endTimeIndexPath.row {
                updateRows.append(endTimeIndexPath)
            }
            retValue = false
        }
        
        if viewModel.position.has_work_certificate == YHCheckboxSelectType.unknown.rawValue {
            isWorkCertificateOK = false
            if let workCertificateIndexPath = workCertificateIndexPath, tableView.numberOfSections > workCertificateIndexPath.section, tableView.numberOfRows(inSection: workCertificateIndexPath.section) > workCertificateIndexPath.row {
                updateRows.append(workCertificateIndexPath)
            }
            retValue = false
        }
        
        if viewModel.position.company_type.count == 0 {
            isWorkTypeOK = false
            if let workTypeIndexPath = workTypeIndexPath, tableView.numberOfSections > workTypeIndexPath.section, tableView.numberOfRows(inSection: workTypeIndexPath.section) > workTypeIndexPath.row {
                updateRows.append(workTypeIndexPath)
            }
            retValue = false
        }
        
        if viewModel.position.company_type.contains("其他"), viewModel.position.company_type_other.count == 0 {
            isFinalWorkTypeOK = false
            if let finalWorkTypeIndexPath = finalWorkTypeIndexPath, tableView.numberOfSections > finalWorkTypeIndexPath.section, tableView.numberOfRows(inSection: finalWorkTypeIndexPath.section) > finalWorkTypeIndexPath.row {
                updateRows.append(finalWorkTypeIndexPath)
            }
            retValue = false
        }
        if updateRows.count > 0 {
            tableView.reloadRows(at: updateRows, with: .none)
//            isCompanyOK = true
//            isIncomeTypeOK = true
//            isIncomeMoneyOK = true
//            isCountryOK = true
//            isCityOK = true
//            isPositionOK = true
//            isEntryTimeOK = true
//            isEndTimeOK = true
//            isWorkCertificateOK = true
//            isWorkTypeOK = true
//            isFinalWorkTypeOK = true
        }
        return retValue
    }

    private func requestData(isNeedLoading: Bool = false) {
        if isNeedLoading {
            YHHUD.show(.progress(message: "加载中..."))
        }
        viewModel.requestWorkPositionDetail(incomeId, orderId) { [weak self] success, error in
            guard let self = self else {
                return
            }
            if isNeedLoading {
                YHHUD.hide()
            }
            guard success else {
                printLog("YHGCIncomeRecordWorkExperienceViewController:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                self.datas = []
                self.tableView.reloadData()
                return
            }
            self.setupData()
        }
    }

    private func submitIncome(complete: @escaping (Bool) -> Void) {
        view.endEditing(true)
        let msg = "提交中..."
        if checkInput() == false {
            return
        }
        YHHUD.show(.progress(message: msg))
        viewModel.saveWorkPosition { [weak self] success, error in
            guard let self = self else {
                complete(false)
                return
            }
            YHHUD.hide()
            complete(success)
            if success {
                let msg = "提交成功"
                YHHUD.flash(message: msg)
                self.submitSuccess?()
                self.navigationController?.popViewController(animated: true)
            } else {
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
            }
        }
    }
}
