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

import IQKeyboardManagerSwift
import UIKit

class YHIncomeRecordWorkExperienceViewController: YHBaseViewController {
    enum TableRow {
        case header(_ title: String)
        case incomeFrom(_ title: String, _ detail: String)
        case incomeTypeSelect(_ title: String, _ detail: String, _ isSelectedOne: Bool)
        case incomeTypes(_ types: [YHIncomeType])
        case inputMoney(_ title: String, _ detail: String?, _ inputStr: String?, _ showBottomLine: Bool, _ showStar: Bool, _ isIncomeMoney: Bool)
        case inputRemark(_ detail: String)
        case documentComfirm(_ title: String, _ question: String, _ docs: [String])
    }

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

    private var selectedTypes: [YHIncomeType] = []

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

    // 校验字段控制
    /// 是否选定收入类型
    private var isIncomeTypeOK = true
    private var incomeTypeIndexPath: IndexPath?

    /// 是否选定文件
    private var isHasAllFileOK = true
    private var hasAllFileIndexPath: IndexPath?

    /// 是否收入金额已填写
    private var isIncomeMoneyOK = true
    private var incomMoneyIndexPath: IndexPath?

    private lazy var viewModel = YHIncomeRecordViewModel()
    private var companyModel = YHIncomeCompanyDetailModel()

    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.keyboardDismissMode = .onDrag
        return view
    }()

    private let incomeId: Int
    init(incomeId: Int) {
        self.incomeId = incomeId
        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
    }

    override func backItemClick(_ sender: Any) {
        guard !isSaving else {
            return
        }
        isSaving = true
        submitIncome(.save) { [weak self] _ in
            self?.isSaving = false
        }
    }

    /// 是否可以返回，包括点击返回和手势返回，默认YES
    override func navigationShouldPop() -> Bool {
        guard !isSaving else {
            return false
        }
        isSaving = true
        submitIncome(.save) { [weak self] _ in
            self?.isSaving = false
        }
        return false
    }
}

extension YHIncomeRecordWorkExperienceViewController {
    @objc private func clickSubmitButton() {
        submitIncome(.submit, 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 = companyModel.income_type.compactMap {
            YHIncomeType(rawValue: $0)
        }
        var firstSection: [TableRow] = [.header("收入信息"), .incomeFrom("收入来源公司", companyModel.company_name), .incomeTypeSelect("收入类型(多选)", "请选择", selectedTypes.count > 0)]
        if selectedTypes.count > 0 {
            firstSection.append(.incomeTypes(selectedTypes))
        }
        let hkdFmt = currencyFormat("")
        let rmbFmt = currencyFormat("¥")
        let rate = companyModel.rate > 0 ? companyModel.rate : 0.92
        if selectedTypes.contains(.incomeOfMainland) || selectedTypes.contains(.incomeOfHKCompanies) || selectedTypes.contains(.incomeOfMacauCompanies) || selectedTypes.contains(.incomeOfOtherOverseasCompanies) {
            firstSection.append(.inputMoney("公司营业额(近一年)", "约\(hkdFmt.string(from: NSNumber(value: companyModel.corporate_turnover / rate)) ?? "0")港币", rmbFmt.string(from: NSNumber(value: companyModel.corporate_turnover)) ?? "0", true, false, false))
        }
        firstSection.append(.inputMoney("收入金额", "约\(hkdFmt.string(from: NSNumber(value: companyModel.income_money / rate)) ?? "0")港币", rmbFmt.string(from: NSNumber(value: companyModel.income_money)) ?? "0", false, true, true))
        firstSection.append(.inputRemark("注：按1港币≈\(rate)人民币计算，实际金额按递交时入境处给出的汇率为准"))
        let set = Set(selectedTypes.map { $0.docsArray() }.flatMap { $0 })
        var arr = Array(set)
        if set.count == 0 {
            arr = YHIncomeType.defaultDocs()
        }
        let secondSection: [TableRow] = [.documentComfirm("证件提供确认", "您是否可以提供以下所有证明文件", arr)]
        datas = [firstSection, secondSection]
        tableView.reloadData()
    }

    private func showSelectIncomeTypePopVC(selectedTypes: [YHIncomeType]) {
        let ctl = YHIncomeTypeSelectViewController(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() {
        companyModel.income_type = selectedTypes.map { $0.rawValue }
        if companyModel.income_type.count > 0 {
            isIncomeTypeOK = true
        }
        var incomeTypesIndexPath: IndexPath?
        var incomeTypeSelectIndexPath: IndexPath?
        var docIndexPath: 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 .documentComfirm(title, question, _):
                    docIndexPath = IndexPath(row: row, section: section)
                    let set = Set(selectedTypes.map { $0.docsArray() }.flatMap { $0 })
                    if set.count > 0 {
                        return .documentComfirm(title, question, Array(set))
                    } else {
                        return .documentComfirm(title, question, YHIncomeType.defaultDocs())
                    }
                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 = companyModel.rate > 0 ? companyModel.rate : 0.92
                    sectionArr.insert(.inputMoney("公司营业额(近一年)", "约\(hkdFmt.string(from: NSNumber(value: companyModel.corporate_turnover / rate)) ?? "0")港币", rmbFmt.string(from: NSNumber(value: companyModel.corporate_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
                }
            }
        }

        if let secondSection = docIndexPath?.section {
            tableView.performBatchUpdates { [weak tableView] in
                tableView?.reloadSections(IndexSet(arrayLiteral: incomeTypeSelectIndexPath.section, secondSection), with: .automatic)
            }
        } else {
            tableView.performBatchUpdates { [weak tableView] in
                tableView?.reloadSections(IndexSet(integer: incomeTypeSelectIndexPath.section), with: .automatic)
            }
        }
    }

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

extension YHIncomeRecordWorkExperienceViewController: 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, detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeRecordFromCell.cellReuseIdentifier) as? YHIncomeRecordFromCell {
                cell.setupCellInfo(title: title, detail: detail, showBottomLine: true)
                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.companyModel.income_money = 0
                                    } else {
                                        self.companyModel.corporate_turnover = 0
                                    }
                                }
                            }
                        }
                        return
                    }
                    // 转换为数字
                    let number = Double(text) ?? 0
                    // 格式化为带货币符号和千分位
                    let detail = number / self.currencyRate
                    if isIncomeMoney {
                        self.isIncomeMoneyOK = true
                        self.companyModel.income_money = number
                    } else {
                        self.companyModel.corporate_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 .documentComfirm(title, question, docs):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeDocumentationConfirmationCell.cellReuseIdentifier) as? YHIncomeDocumentationConfirmationCell {
                hasAllFileIndexPath = indexPath
                cell.selectedSureButton = YHIncomeRecordHasAllFile(rawValue: companyModel.has_all_file) ?? .unknown
                cell.setupCellInfo(title: title, question: question, documents: docs, needShowFailButton: !isHasAllFileOK)
                cell.didSelectSureButton = { [weak self] flag in
                    guard let self = self else {
                        return
                    }
                    self.companyModel.has_all_file = flag.rawValue
                    self.isHasAllFileOK = flag != .unknown
                    self.tableView.reloadRows(at: [indexPath], with: .automatic)
                }
                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)
        }
    }
}

extension YHIncomeRecordWorkExperienceViewController {
    private func checkInput() -> Bool {
        var retValue = true
        var updateRows: [IndexPath] = []
        if companyModel.has_all_file == YHIncomeRecordHasAllFile.unknown.rawValue {
            isHasAllFileOK = false
            if let hasAllFileIndexPath = hasAllFileIndexPath, tableView.numberOfSections > hasAllFileIndexPath.section, tableView.numberOfRows(inSection: hasAllFileIndexPath.section) > hasAllFileIndexPath.row {
                updateRows.append(hasAllFileIndexPath)
            }
            retValue = false
        }
        if companyModel.income_type.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 companyModel.income_money == 0 {
            isIncomeMoneyOK = false
            if let incomMoneyIndexPath = incomMoneyIndexPath, tableView.numberOfSections > incomMoneyIndexPath.section, tableView.numberOfRows(inSection: incomMoneyIndexPath.section) > incomMoneyIndexPath.row {
                updateRows.append(incomMoneyIndexPath)
            }
            retValue = false
        }
        if updateRows.count > 0 {
            tableView.reloadRows(at: updateRows, with: .none)
            isHasAllFileOK = true
            isIncomeTypeOK = true
            isIncomeMoneyOK = true
        }
        return retValue
    }

    private func requestData(isNeedLoading: Bool = false) {
        if isNeedLoading {
            YHHUD.show(.progress(message: "加载中..."))
        }
        viewModel.getIncomeDetail(incomeId: incomeId) { [weak self] companyModel, error in
            guard let self = self else {
                return
            }

            if isNeedLoading {
                YHHUD.hide()
            }
            guard let companyModel = companyModel else {
                printLog("YHIncomeRecordWorkExperienceViewController:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                self.datas = []
                self.tableView.reloadData()
                return
            }
            self.companyModel = companyModel
            self.setupData()
        }
    }

    private func submitIncome(_ type: YHIncomeRecordUpdateType, complete: @escaping (Bool) -> Void) {
        view.endEditing(true)
        let msg = type == .save ? "保存中..." : "提交中..."
        if type == .submit {
            if checkInput() == false {
                return
            }
        }
        YHHUD.show(.progress(message: msg))
        viewModel.updateDetail(incomeId: incomeId, incomeMoney: companyModel.income_money, corporateTurnover: companyModel.corporate_turnover, incomeType: companyModel.income_type, hasAllFile: companyModel.has_all_file) { [weak self] success, error in
            guard let self = self else {
                complete(false)
                return
            }
            YHHUD.hide()
            complete(success)
            if success {
                let msg = type == .save ? "保存成功" : "提交成功"
                YHHUD.flash(message: msg)
                self.submitSuccess?()
                self.navigationController?.popViewController(animated: true)
            } else {
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                if type == .save {
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }
    }
}
