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

import IQKeyboardManagerSwift
import AttributedString
import UIKit

class YHIncomeRecordViewController: YHBaseViewController {
    enum TableRow {
        case incomeSummary(_ isEditing: Bool = false, _ isEditEnable: Bool = false)
        case incomeItem(_ isEditState: Bool = false, _ company: String, _ money: String, _ timeStr: String, _ incomeId: Int, _ showBottomLine: Bool)
        case totalIncome(_ money: ASAttributedString)
        case consentForHKTravel(_ title: String, _ detail: ASAttributedString, _ question: String)
        case incomeCompanyTips(_ detail: String)
    }
    
    private lazy var datas: [[TableRow]] = []
    
    /// 是否超过
    private var isOver100OK = true
    private var over100IndexPath: IndexPath?
    
    private lazy var viewModel = YHIncomeRecordViewModel()
    private var incomeModel = YHIncomeRecordCompleteModel()
    
    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(YHIncomeRecordCompanyTipsCell.self, forCellReuseIdentifier: YHIncomeRecordCompanyTipsCell.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 YHIncomeRecordViewController {
    @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 setupData() {
        let detail: ASAttributedString = .init(string: "备注：全年收入是指应课税（应纳所得税）的就业或业务收入，包括工资薪金、津贴、股票期权及从其拥有的公司所得的利润。由个人投资所产生的收入不会计算在内。", .font(UIFont.PFSC_R(ofSize: 13)), .foreground(UIColor(hexString: "#8993A2") ?? .gray))
        let firstSection: [TableRow] = [.consentForHKTravel("收入情况", detail, "您在近十二个月，总收入是否达到港币100万元或以上")]
        guard incomeModel.income_over_100 == YHIncomeOver100.true.rawValue else {
            datas = [firstSection]
            tableView.reloadData()
            return
        }
        let hkdFormatter = currencyFormat("")
        var money: Double = 0
        var secondSection: [TableRow] = [.incomeSummary(false, false), .incomeCompanyTips("备注：此处有收入记录的公司为近1年您工作的公司，若需修改公司名称需返回上一节点【工作经验】处修改")]
        let rate = self.incomeModel.rate > 0 ? self.incomeModel.rate : 0.92
        let listCount = incomeModel.list.count
        incomeModel.list.enumerated().forEach { index, companyModel in
            money += companyModel.income_money
            let moneyStr = companyModel.income_money == 0 ? "" : "约" + (hkdFormatter.string(from: NSNumber(value: companyModel.income_money / rate)) ?? "0") + "港币"
            let timeStr: String = companyModel.fill_status ? "已填写" : "有\(companyModel.unfilled_count)项未填写"
            let incomeItem: TableRow = .incomeItem(false, companyModel.company_name, moneyStr, timeStr, companyModel.income_id, index != listCount - 1)
            secondSection.append(incomeItem)
        }
        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)))
        secondSection.append(.totalIncome(totalMoney))
        datas = [firstSection, secondSection]
        tableView.reloadData()
    }
    
    private func currencyFormat(_ currencySymbol: String) -> NumberFormatter {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.currencySymbol = currencySymbol
        formatter.maximumFractionDigits = 0
        return formatter
    }
}

extension YHIncomeRecordViewController: 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 .incomeSummary(isEditState, isEditEnable):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeRecordSummaryCell.cellReuseIdentifier) as? YHIncomeRecordSummaryCell {
                cell.setupCellInfo(isEditState, isEditEnable, showRightButton: false)
                return cell
            }
        case let .incomeItem(isEditState, company, money, timeStr, _, showBottomLine):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeRecordItemCell.cellReuseIdentifier) as? YHIncomeRecordItemCell {
                cell.setupCellInfo(title: company, detail: money, rightText: timeStr, isEditing: isEditState, showBottomLine: showBottomLine)
                return cell
            }
        case let .totalIncome(money):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHTotalIncomeCell.cellReuseIdentifier) as? YHTotalIncomeCell {
                cell.setupCellInfo(detail: money)
                cell.didClickInfoButton = { [weak self, weak cell] in
                    guard let self = self else {
                        return
                    }
                    guard let cell = cell else {
                        return
                    }
                    let rate = self.incomeModel.rate > 0 ? self.incomeModel.rate : 0.92
                    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 {
                over100IndexPath = indexPath
                cell.setupCellInfo(title: title, detail: detail, question: question, needShowFailButton: !isOver100OK)
                cell.didSelectSureButton = { [weak self] selected in
                    guard let self = self else {
                        return
                    }
                    switch selected {
                    case .true:
                        self.incomeModel.income_over_100 = YHIncomeOver100.true.rawValue
                        isOver100OK = true
                    case .false:
                        self.incomeModel.income_over_100 = YHIncomeOver100.false.rawValue
                        isOver100OK = true
                    case .unknown:
                        self.incomeModel.income_over_100 = YHIncomeOver100.unknown.rawValue
                        isOver100OK = false
                    }
                    self.setupData()
                }
                let over100Type = YHIncomeOver100(rawValue: incomeModel.income_over_100) ?? .unknown
                switch over100Type {
                case .true:
                    cell.selectedSureButton = .true
                case .false:
                    cell.selectedSureButton = .false
                case .unknown:
                    cell.selectedSureButton = .unknown
                }
                
                return cell
            }
        
        case let .incomeCompanyTips(detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeRecordCompanyTipsCell.cellReuseIdentifier) as? YHIncomeRecordCompanyTipsCell {
                cell.setupCellInfo(detail: detail)
                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 = YHIncomeRecordWorkExperienceViewController(incomeId: incomeId)
            ctl.submitSuccess = { [weak self] in
                guard let self = self else {
                    return
                }
                self.requestData(isNeedLoading: true, lastSelectedIncomeOver100: self.incomeModel.income_over_100)
            }
            navigationController?.pushViewController(ctl, animated: true)
        }
    }
}

extension YHIncomeRecordViewController {
    private func checkInput() -> Bool {
        if incomeModel.income_over_100 == YHIncomeOver100.unknown.rawValue {
            isOver100OK = false
            if let over100IndexPath = over100IndexPath, tableView.numberOfSections > over100IndexPath.section, tableView.numberOfRows(inSection: over100IndexPath.section) > over100IndexPath.row {
                tableView.reloadRows(at: [over100IndexPath], with: .none)
            }
            return false
        }
        isOver100OK = true
        return true
    }
    
    private func requestData(isNeedLoading: Bool = false, lastSelectedIncomeOver100: Int? = nil) {
        if isNeedLoading {
            YHHUD.show(.progress(message: "加载中..."))
        }
        viewModel.getIncomeList(orderId: orderId) { [weak self] incomeModel, error in
            guard let self = self else {
                return
            }
            
            if isNeedLoading {
                YHHUD.hide()
            }
            guard let incomeModel = incomeModel else {
                printLog("YHIncomeRecordViewController:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                self.datas = []
                self.tableView.reloadData()
                self.navigationController?.popViewController(animated: true)
                return
            }
            self.incomeModel = incomeModel
            if let lastSelectedIncomeOver100 = lastSelectedIncomeOver100 {
                self.incomeModel.income_over_100 = lastSelectedIncomeOver100
            }
            self.setupData()
        }
    }
    
    private func updateIncome(_ type: YHIncomeRecordUpdateType) {
        let msg = type == .save ? "保存中..." : "提交中..."
        YHHUD.show(.progress(message: msg))
        viewModel.incomeUpdate(orderId: orderId, incomeOver100: incomeModel.income_over_100, type: type) { [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)
            }
        }
    }
}
