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

import IQKeyboardManagerSwift
import AttributedString
import SafariServices
import UIKit

class YHGCIncomeRecordViewController: YHBaseViewController {
    enum TableRow {
        case incomeSummary
        case incomeItem(_ company: String, _ money: String, _ timeStr: String, _ incomeId: Int, _ showBottomLine: Bool)
        case addItem
        case totalIncome(_ money: ASAttributedString)
        case consentForHKTravel(_ title: String, _ detail: ASAttributedString, _ question: String)
        case questionSelect(_ question: String)
        case employmentVerification // (_ employments: [YHWorkItemListModel], _ selectedId: Int?)
        case workingHoursStatement(_ placeholder: String, _ detail: ASAttributedString)
    }
    
    private lazy var datas: [[TableRow]] = []
    private lazy var viewModel = YHGCIncomeRecordViewModel()
    
    /// 校验是否提供赴港同意书
    private var hasCompanyConsentOK = true
    private var hasCompanyConsentIndexPath: IndexPath?
    /// 校验可提供的在职公司
    private var consentWorkIdOK = true
    private var consentWorkIdOKIndexPath: IndexPath?
    /// 校验人才中心是提供否赴港同意书
    private var hasCenterConsentOK = true
    private var hasCenterConsentIndexPath: IndexPath?
    /// 校验是否具有工作经历
    private var hasWorkListOK = true
    private var hasWorkListIndexPath: IndexPath?
    
    private lazy var saveButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
        button.setTitle("保存", for: .normal)
        button.setTitle("保存", for: .highlighted)
        button.setTitleColor(.mainTextColor, for: .normal)
        button.setTitleColor(.mainTextColor, for: .highlighted)
        button.addTarget(self, action: #selector(clickSaveButton), for: .touchUpInside)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.backgroundColor = .contentBkgColor
        return button
    }()

    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(YHIncomeRecordSummaryCell.self, forCellReuseIdentifier: YHIncomeRecordSummaryCell.cellReuseIdentifier)
        view.register(YHIncomeRecordItemCell.self, forCellReuseIdentifier: YHIncomeRecordItemCell.cellReuseIdentifier)
        view.register(YHInfoConsentForHKTravelCell.self, forCellReuseIdentifier: YHInfoConsentForHKTravelCell.cellReuseIdentifier)
        view.register(YHTotalIncomeCell.self, forCellReuseIdentifier: YHTotalIncomeCell.cellReuseIdentifier)
        
        view.register(YHAddIncomeRecordCell.self, forCellReuseIdentifier: YHAddIncomeRecordCell.cellReuseIdentifier)
        view.register(YHInfoQuestionSelectionCell.self, forCellReuseIdentifier: YHInfoQuestionSelectionCell.cellReuseIdentifier)
        view.register(YHEmploymentVerificationAvailableCell.self, forCellReuseIdentifier: YHEmploymentVerificationAvailableCell.cellReuseIdentifier)
        view.register(YHWorkingHoursStatementCell.self, forCellReuseIdentifier: YHWorkingHoursStatementCell.cellReuseIdentifier)

        view.keyboardDismissMode = .onDrag
        return view
    }()
    
    private let orderId: Int
    init(orderId: Int) {
        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()
        requestData(isNeedLoading: true)
    }
    
    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 YHGCIncomeRecordViewController {
    @objc private func clickSaveButton() {
        updateIncome(.save)
    }

    @objc private func clickSubmitButton() {
        guard checkInput() else {
            return
        }
        updateIncome(.submit)
    }

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

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

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

        saveButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(10)
            make.height.equalTo(44)
            make.width.equalTo(86)
        }

        submitButton.snp.makeConstraints { make in
            make.left.equalTo(saveButton.snp.right).offset(10)
            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 getCurrentRate() -> Double {
        let configRate = Double(YHConfigManager.shared.reqVM.configModel?.rate ?? "") ?? 0
        let rate = configRate > 0 ? configRate : 0.92
        return rate
    }
    
    private func setupData() {
        let hkdFormatter = currencyFormat("")
        var money: Double = 0
        var firstSection: [TableRow] = [.incomeSummary]
        let rate = getCurrentRate()
        let listCount = viewModel.listModel.count
        
        viewModel.listModel.enumerated().forEach { index, companyModel in
            let income = Double(companyModel.income ?? "") ?? 0
            money += income
            let moneyStr = income == 0 ? "" : "约" + (hkdFormatter.string(from: NSNumber(value: income / rate)) ?? "0") + "港币"
//            let vacantNum = companyModel.vacant_num ?? 0
//            let timeStr: String = vacantNum == 0 ? "已填写" : "有\(vacantNum)项未填写"
            let timeStr: String = (companyModel.entry_time ?? "") + "-" + (companyModel.departure_time ?? "")
            let incomeItem: TableRow = .incomeItem(companyModel.company_name ?? "", moneyStr, timeStr, companyModel.id ?? 0, index != listCount - 1)
            firstSection.append(incomeItem)
        }
        if listCount > 0 {
            let totalNum = hkdFormatter.string(from: NSNumber(value: money / rate)) ?? "0"
            let totalMoney: ASAttributedString = .init(string: "约 ", .font(.PFSC_R(ofSize: 14))) + .init(string: totalNum, .font(UIFont(name: "DINAlternate-Bold", size: 20) ?? UIFont.systemFont(ofSize: 20))) + .init(string: " 港币", .font(.PFSC_R(ofSize: 14)))
            firstSection.append(.totalIncome(totalMoney))
        }
        firstSection.append(.addItem)
        var secondSection: [TableRow] = []
        if viewModel.mainModel.has_work_time_overlap == 1 {
            let tipsIcon = ASAttributedString.init(.image(UIImage(named: "red_dot_6") ?? UIImage(), .custom(.offset(CGPoint(x: 0, y: 1)), size: .init(width: 6, height: 6))))
            let tips: ASAttributedString = tipsIcon + .init(string: "  检测到您的", .font(.PFSC_R(ofSize: 13)), .foreground(UIColor(hexString: "#8993A2") ?? .gray)) + .init(string: "工作时间有重叠", .font(.PFSC_R(ofSize: 13)), .foreground(UIColor.failColor)) + .init(string: "。请确认是否正确填报，若填报无误请在此处说明工作时间重叠的原因~", .font(.PFSC_R(ofSize: 13)), .foreground(UIColor(hexString: "#8993A2") ?? .gray))
            secondSection.append(.workingHoursStatement("如：工作时间灵活，可自由安排", tips))
        }
        
        var thirdSection: [TableRow] = []
        if viewModel.mainModel.is_consent_required == 1 {
            let detail: ASAttributedString = .init(string: "备注：赴港同意书为目前在职公司盖章提供，若目前未就职于任何公司，则由档案所在地人才中心盖章提供，", .font(UIFont.PFSC_R(ofSize: 13)), .foreground(UIColor(hexString: "#8993A2") ?? .gray))
            let actionStr = ASAttributedString.init(string: "查看示例模板", .font(UIFont.PFSC_R(ofSize: 13)), .foreground(UIColor.brandMainColor), .underline(.init(rawValue: 1)), .action { [weak self] in
                guard let self = self else {
                    return
                }
                let url = self.viewModel.mainModel.consent_template_url
                guard url.count > 0 else {
                    return
                }
                self.gotoPreview(url)
            })
            thirdSection.append(.consentForHKTravel("赴港同意书提供", detail + actionStr, "在职公司是否可以提供赴港同意书"))
            if viewModel.mainModel.has_company_consent == 1 {
                let employments = viewModel.listModel.filter {
                    $0.departure_time == "至今"
                }
                if viewModel.mainModel.consent_work_id == 0, employments.count == 1 {
                    viewModel.mainModel.consent_work_id = employments.first?.id ?? 0
                    consentWorkIdOK = true
                }
                thirdSection.append(.employmentVerification)
            } else if viewModel.mainModel.has_company_consent == 2 { // 选择否时才显示
                thirdSection.append(.questionSelect("人才中心是否可以提供赴港同意书"))
            }
        }
        datas = [firstSection]
        if secondSection.count > 0 {
            datas.append(secondSection)
        }
        if thirdSection.count > 0 {
            datas.append(thirdSection)
        }
        tableView.reloadData()
    }
    
    private func currencyFormat(_ currencySymbol: String) -> NumberFormatter {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.currencySymbol = currencySymbol
        formatter.maximumFractionDigits = 0
        return formatter
    }
    
    private func gotoPreview(_ urlString: String) {
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.getRealUsefulUrl(urlString) { [weak self] resultUrl in
            YHHUD.hide()
            guard let self = self, let url = URL(string: resultUrl) else { return }
            let safariViewController = SFSafariViewController(url: url)
            safariViewController.dismissButtonStyle = .close
            safariViewController.modalPresentationStyle = .fullScreen
            self.present(safariViewController, animated: true, completion: nil)
        }
    }
}

extension YHGCIncomeRecordViewController: 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 .incomeSummary:
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeRecordSummaryCell.cellReuseIdentifier) as? YHIncomeRecordSummaryCell {
                cell.setupCellInfo(viewModel.formState == .editing, true, showRightButton: true)
                cell.rightButtonClickEvent = { [weak self] in
                    guard let self = self else {
                        return
                    }
                    self.viewModel.toggleEditingState()
                    self.tableView.reloadSections(IndexSet(arrayLiteral: indexPath.section), with: .automatic)
                }
                return cell
            }
        case let .incomeItem(company, money, timeStr, id, showBottomLine):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeRecordItemCell.cellReuseIdentifier) as? YHIncomeRecordItemCell {
                cell.setupCellInfo(title: company, detail: money, rightText: timeStr, isEditing: viewModel.formState == .editing, showBottomLine: showBottomLine)
                cell.deleteButtonClickEvent = { [weak self] in
                    guard let self = self else {
                        return
                    }
                    self.showAlertWhenDeleteItem(id: id, name: company)
                }
                return cell
            }
        case let .totalIncome(money):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHTotalIncomeCell.cellReuseIdentifier) as? YHTotalIncomeCell {
                cell.setupCellInfo(detail: money, cellType: .mid)
                cell.didClickInfoButton = { [weak self, weak cell] in
                    guard let self = self else {
                        return
                    }
                    guard let cell = cell else {
                        return
                    }
                    let rate = self.getCurrentRate()
                    YHWholeScreenTipsView.show(type: .hkdToRmbRateTips("注：按1港币≈\(rate)人民币计算，实际金额按递交时入境处给出的汇率为准"), targetView: cell.infoButton)
                }
                return cell
            }
        case let .consentForHKTravel(title, detail, question):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHInfoConsentForHKTravelCell.cellReuseIdentifier) as? YHInfoConsentForHKTravelCell {
                hasCompanyConsentIndexPath = indexPath
                cell.setupCellInfo(title: title, detail: detail, question: question, needShowFailButton: !hasCompanyConsentOK)
                cell.didSelectSureButton = { [weak self] selected in
                    guard let self = self else {
                        return
                    }
                    switch selected {
                    case .true:
                        self.viewModel.mainModel.has_company_consent = YHCheckboxSelectType.true.rawValue
                        self.hasCompanyConsentOK = true
                        case .false:
                        self.viewModel.mainModel.has_company_consent = YHCheckboxSelectType.false.rawValue
                        self.hasCompanyConsentOK = true
                        case .unknown:
                        self.viewModel.mainModel.has_company_consent = YHCheckboxSelectType.unknown.rawValue
                        self.hasCompanyConsentOK = false
                    }
                    self.setupData()
                }
                let selectType = YHCheckboxSelectType(rawValue: viewModel.mainModel.has_company_consent) ?? .unknown
                switch selectType {
                case .true:
                    cell.selectedSureButton = .true
                case .false:
                    cell.selectedSureButton = .false
                case .unknown:
                    cell.selectedSureButton = .unknown
                }
                return cell
            }
        case .addItem:
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHAddIncomeRecordCell.cellReuseIdentifier) as? YHAddIncomeRecordCell {
                hasWorkListIndexPath = indexPath
                cell.setupCellInfo("新增收入/工作信息", needShowFailButton: !hasWorkListOK)
                cell.addButtonClickEvent = { [weak self] in
                    guard let self = self else {
                        return
                    }
                    let ctl = YHGCIncomeRecordWorkExperienceViewController(incomeId: 0, orderId: self.orderId)
                    ctl.submitSuccess = { [weak self] in
                        guard let self = self else {
                            return
                        }
                        self.hasWorkListOK = true
                        self.requestData(isNeedLoading: true)
                    }
                    self.navigationController?.pushViewController(ctl, animated: true)
                }
                return cell
            }
        case let .questionSelect(question):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHInfoQuestionSelectionCell.cellReuseIdentifier) as? YHInfoQuestionSelectionCell {
                hasCenterConsentIndexPath = indexPath
                
                cell.setupCellInfo(question: question, needShowFailButton: !hasCenterConsentOK)
                cell.didSelectSureButton = { [weak self] selected in
                    guard let self = self else {
                        return
                    }
                    switch selected {
                    case .true:
                        self.viewModel.mainModel.has_center_consent = YHCheckboxSelectType.true.rawValue
                        self.hasCenterConsentOK = true
                    case .false:
                        self.viewModel.mainModel.has_center_consent = YHCheckboxSelectType.false.rawValue
                        self.hasCenterConsentOK = true
                    case .unknown:
                        self.viewModel.mainModel.has_center_consent = YHCheckboxSelectType.unknown.rawValue
                        self.hasCenterConsentOK = false
                    }
                    self.setupData()
                }
                let selectType = YHCheckboxSelectType(rawValue: viewModel.mainModel.has_center_consent) ?? .unknown
                switch selectType {
                case .true:
                    cell.selectedSureButton = .true
                case .false:
                    cell.selectedSureButton = .false
                case .unknown:
                    cell.selectedSureButton = .unknown
                }
                
                return cell
            }
            
        case .employmentVerification:// (employments, selectedId):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHEmploymentVerificationAvailableCell.cellReuseIdentifier) as? YHEmploymentVerificationAvailableCell {
                consentWorkIdOKIndexPath = indexPath
                let employments = viewModel.listModel
                let selectedId = viewModel.mainModel.consent_work_id > 0 ? viewModel.mainModel.consent_work_id : nil
                let selectedEmployment = employments.first { model in
                    model.id == selectedId
                }
                
//                if selectedEmployment == nil, employments.count == 1 {
//                    selectedEmployment = employments.first
//                    viewModel.mainModel.consent_work_id = selectedEmployment?.id ?? 0
//                }
                cell.setupCellInfo(detail: selectedEmployment?.company_name, needShowFailButton: !consentWorkIdOK)
                return cell
            }
        case let .workingHoursStatement(placeholder, tips):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHWorkingHoursStatementCell.cellReuseIdentifier) as? YHWorkingHoursStatementCell {
                let content = viewModel.mainModel.why_work_time_overlap
                cell.setupCellInfo(placeholder: placeholder, remark: content, detail: tips, isShowBottomLine: false)
                cell.textDidExceedsMaxLimit = { maxCount in
                    YHHUD.flash(message: "不可超过\(maxCount)字")
                }
                
                cell.textViewDidChanged = { [weak self] textView in
                    guard let self = self else {
                        return
                    }
                    self.viewModel.mainModel.why_work_time_overlap = textView.text
                }
                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 let .incomeItem(_, _, _, incomeId, _) = tableRow {
            let ctl = YHGCIncomeRecordWorkExperienceViewController(incomeId: incomeId, orderId: orderId)
            ctl.submitSuccess = { [weak self] in
                guard let self = self else {
                    return
                }
                self.requestData(isNeedLoading: true)
            }
            navigationController?.pushViewController(ctl, animated: true)
        } else if case .employmentVerification = tableRow {
            let employments = viewModel.listModel.filter {
                $0.departure_time == "至今"
            }
            if employments.count == 0 {
                YHHUD.flash(message: "请确认工作经验中您是否已填写在职公司")
                return
            }
            let selectedId = viewModel.mainModel.consent_work_id > 0 ? viewModel.mainModel.consent_work_id : nil
            let companies = employments.compactMap {
                $0.company_name
            }
            let firstIndex = employments.firstIndex { model in
                model.id == selectedId
            }
            YHDynamicSheetPickerView.show(dataSource: companies, title: "选择可提供的在职公司", selectIndex: firstIndex ?? 0) { [weak self] index in
                guard let self = self else {
                    return
                }
                self.viewModel.mainModel.consent_work_id = employments[index].id ?? 0
                self.tableView.reloadRows(at: [indexPath], with: .automatic)
                self.consentWorkIdOK = true
            }
        }
    }
}

extension YHGCIncomeRecordViewController {
    private func showAlertWhenDeleteItem(id: Int, name: String) {
        let message0: ASAttributedString = .init(string: "您确认要删除收入信息", .font(UIFont.PFSC_R(ofSize: 16)), .foreground(UIColor.mainTextColor))
        let message1: ASAttributedString = .init(string: "【\(name)】", .font(UIFont.PFSC_M(ofSize: 16)), .foreground(UIColor.brandMainColor))
        let message2: ASAttributedString = .init(string: "吗？", .font(UIFont.PFSC_R(ofSize: 16)), .foreground(UIColor.mainTextColor))
        YHCommonAlertView.show(title: nil, attributedMessage: message0 + message1 + message2, "取消", "确认", fullGuestureEnable: false) {
        } callBack: { [weak self] in
            guard let self = self else {
                return
            }
            self.deleteWorkItem(id: id)
        }
    }
    
    private func checkInput() -> Bool {
        var retValue = true
        var updateRows: [IndexPath] = []
        if viewModel.listModel.count == 0 {
            hasWorkListOK = false
            if let hasWorkListIndexPath = hasWorkListIndexPath, tableView.numberOfSections > hasWorkListIndexPath.section, tableView.numberOfRows(inSection: hasWorkListIndexPath.section) > hasWorkListIndexPath.row {
                updateRows.append(hasWorkListIndexPath)
            }
            retValue = false
        }
        if viewModel.mainModel.has_company_consent == YHCheckboxSelectType.unknown.rawValue {
            hasCompanyConsentOK = false
            if let hasCompanyConsentIndexPath = hasCompanyConsentIndexPath, tableView.numberOfSections > hasCompanyConsentIndexPath.section, tableView.numberOfRows(inSection: hasCompanyConsentIndexPath.section) > hasCompanyConsentIndexPath.row {
                updateRows.append(hasCompanyConsentIndexPath)
            }
            retValue = false
        }
        if viewModel.mainModel.has_company_consent == YHCheckboxSelectType.true.rawValue, viewModel.mainModel.consent_work_id == 0 {
            consentWorkIdOK = false
            if let consentWorkIdOKIndexPath = consentWorkIdOKIndexPath, tableView.numberOfSections > consentWorkIdOKIndexPath.section, tableView.numberOfRows(inSection: consentWorkIdOKIndexPath.section) > consentWorkIdOKIndexPath.row {
                updateRows.append(consentWorkIdOKIndexPath)
            }
            retValue = false
        }
        if viewModel.mainModel.has_company_consent == YHCheckboxSelectType.false.rawValue, viewModel.mainModel.has_center_consent == YHCheckboxSelectType.unknown.rawValue {
            hasCenterConsentOK = false
            if let hasCenterConsentIndexPath = hasCenterConsentIndexPath, tableView.numberOfSections > hasCenterConsentIndexPath.section, tableView.numberOfRows(inSection: hasCenterConsentIndexPath.section) > hasCenterConsentIndexPath.row {
                updateRows.append(hasCenterConsentIndexPath)
            }
            retValue = false
        }
        if updateRows.count > 0 {
            tableView.reloadRows(at: updateRows, with: .none)
            hasWorkListOK = true
            hasCompanyConsentOK = true
            consentWorkIdOK = true
            hasCenterConsentOK = true
        }
        return retValue
    }
    
    private func requestData(isNeedLoading: Bool = false, lastSelectedIncomeOver100: Int? = nil) {
        if isNeedLoading {
            YHHUD.show(.progress(message: "加载中..."))
        }
        viewModel.requestWorkList(orderId) { [weak self] workModel, error in
            guard let self = self else {
                return
            }
            if isNeedLoading {
                YHHUD.hide()
            }
            guard workModel != nil else {
                printLog("YHGCIncomeRecordViewController:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                self.datas = []
                self.tableView.reloadData()
                self.navigationController?.popViewController(animated: true)
                return
            }
            self.setupData()
        }
        
    }
    
    private func updateIncome(_ type: YHIncomeRecordUpdateType) {
        let msg = type == .save ? "保存中..." : "提交中..."
        YHHUD.show(.progress(message: msg))
        let isSubmit: Bool = type == .save ? false : true
        viewModel.requestWorkTimeRemarkWorkExperience(orderId, isSubmit) { [weak self] success, error in
            guard let self = self else {
                return
            }
            YHHUD.hide()
            if success {
                let msg = type == .save ? "保存成功" : "提交成功"
                YHHUD.flash(message: msg)
                if type == .submit {
                    self.navigationController?.popViewController(animated: true)
                } else {
                    self.requestData(isNeedLoading: true)
                }
            } else if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                YHHUD.flash(message: errorMsg)
            }
        }
    }
    
    private func deleteWorkItem(id: Int) {
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.requestDeleteWorkExperience(id, orderId) { [weak self] success, error in
            guard let self = self else {
                return
            }
            YHHUD.hide()
            if success {
                self.requestData(isNeedLoading: true)
            } else {
                printLog("YHGCIncomeRecordViewController:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
            }
        }
    }
}
