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

import UIKit

class YHPreviewIncomeRecordViewController: YHPreviewBaseViewController {
    enum TableRow {
        case infoHeader(_ title: String)
        case infoSectionHeader(_ title: String)
        case infoTitleAndDetail(_ title: String, _ detail: String, _ cellType: YHResignRoundCellType, _ topMargin: CGFloat, _ bottomMargin: CGFloat)
        case infoIncomeType(_ title: String, _ types: [String])
    }
    
    private lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无收入记录", kEmptyCommonBgName)
        view.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 164)
        view.backgroundColor = .clear
        view.isHidden = true
        return view
    }()
    
    private lazy var datas: [TableRow] = []
    private lazy var viewModel = YHIncomeRecordViewModel()
    private var incomeModel = YHIncomeRecordCompleteModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        requestData()
    }
    
    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")
    }
}

extension YHPreviewIncomeRecordViewController {
    private func setupUI() {
        view.addSubview(noDataView)
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-100)
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(164)
        }
        homeTableView.snp.remakeConstraints { make in
            make.left.right.top.bottom.equalToSuperview()
        }
        homeTableView.register(YHPreviewInfoHeaderCell.self, forCellReuseIdentifier: YHPreviewInfoHeaderCell.cellReuseIdentifier)
        homeTableView.register(YHPreviewInfoNameAndDetailCell.self, forCellReuseIdentifier: YHPreviewInfoNameAndDetailCell.cellReuseIdentifier)
        homeTableView.register(YHPreviewInfoSectionHeaderCell.self, forCellReuseIdentifier: YHPreviewInfoSectionHeaderCell.cellReuseIdentifier)
        homeTableView.register(YHPreviewInfoIncomeTypeCell.self, forCellReuseIdentifier: YHPreviewInfoIncomeTypeCell.cellReuseIdentifier)
        homeTableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 16))
        homeTableView.tableFooterView = UIView(frame: CGRect(x: 16, y: 0, width: KScreenWidth, height: 44))
    }
    
    private func currencyFormat(_ currencySymbol: String) -> NumberFormatter {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.currencySymbol = currencySymbol
        formatter.maximumFractionDigits = 0
        return formatter
    }
    
    private func setupData() {
        datas.removeAll()
        datas.append(.infoHeader("收入情况"))
        guard incomeModel.income_over_100 == YHIncomeOver100.true.rawValue else {
            if incomeModel.income_over_100 == YHIncomeOver100.false.rawValue {
                datas.append(.infoTitleAndDetail("前一年全年收入是否达港币100万元或以上：", "否", .bottom, 16, 16))
                noDataView.isHidden = true
                homeTableView.reloadData()
            } else {
                noDataView.isHidden = false
                datas = []
                homeTableView.reloadData()
            }
            return
        }
        datas.append(.infoTitleAndDetail("前一年全年收入是否达港币100万元或以上：", "是", .mid, 16, 8))
        let currencyFmt = currencyFormat("")
        let rate = incomeModel.rate > 0 ? incomeModel.rate : 0.92
        var totalMoney: Double = 0
        let listCount = incomeModel.list.count
        incomeModel.list.enumerated().forEach { index, model in
            datas.append(.infoSectionHeader("收入\(index + 1)"))
            datas.append(.infoTitleAndDetail("收入来源公司：", model.company_name, .mid, 8, 8))
            let selectedTypes = model.income_type.compactMap {
                YHIncomeType(rawValue: $0)
            }
            datas.append(.infoIncomeType("收入类型：", selectedTypes.map {
                $0.nameString()
            }))
            if selectedTypes.contains(.incomeOfMainland) || selectedTypes.contains(.incomeOfHKCompanies) || selectedTypes.contains(.incomeOfMacauCompanies) || selectedTypes.contains(.incomeOfOtherOverseasCompanies) {
                datas.append(.infoTitleAndDetail("公司营业额/人民币 (近一年)：", currencyFmt.string(from: NSNumber(value: model.corporate_turnover)) ?? "0", .mid, 8, 8))
            }
            let isLast = (listCount - 1 == index)
            datas.append(.infoTitleAndDetail("收入金额(港元)：", currencyFmt.string(from: NSNumber(value: model.income_money / rate)) ?? "0", isLast ? .bottom : .mid, 8, 16))
            totalMoney += model.income_money
        }
        if datas.count >= 2 {
            if incomeModel.list.count == 0 {
                datas.insert(.infoTitleAndDetail("主申请人总收入(港元)：", currencyFmt.string(from: NSNumber(value: totalMoney / rate)) ?? "0", .bottom, 8, 16), at: 2)
            } else {
                datas.insert(.infoTitleAndDetail("主申请人总收入(港元)：", currencyFmt.string(from: NSNumber(value: totalMoney / rate)) ?? "0", .mid, 8, 16), at: 2)
            }
        }
        noDataView.isHidden = true
        homeTableView.reloadData()
    }
    
    private func requestData() {
        viewModel.getIncomeList(orderId: orderId) { [weak self] incomeModel, error in
            guard let self = self else {
                return
            }
            guard let incomeModel = incomeModel else {
                printLog("YHPreviewIncomeRecordViewController:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                self.noDataView.isHidden = false
                self.datas = []
                self.homeTableView.reloadData()
                return
            }
            self.incomeModel = incomeModel
            self.setupData()
        }
    }
}

// MARK: - UITableViewDelegate 和 UITableViewDataSource
extension YHPreviewIncomeRecordViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard datas.count > indexPath.row else {
            return UITableViewCell()
        }
        let tableRow = datas[indexPath.row]
        switch tableRow {
            
        case let .infoHeader(title):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHPreviewInfoHeaderCell.cellReuseIdentifier) as? YHPreviewInfoHeaderCell {
                cell.setup(title: title)
                return cell
            }
        case let .infoSectionHeader(title):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHPreviewInfoSectionHeaderCell.cellReuseIdentifier) as? YHPreviewInfoSectionHeaderCell {
                cell.setup(title: title)
                return cell
            }
        case let .infoTitleAndDetail(title, detail, cellType, top, bottom):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHPreviewInfoNameAndDetailCell.cellReuseIdentifier) as? YHPreviewInfoNameAndDetailCell {
                cell.setup(title: title, detail: detail, cellType: cellType, topMargin: top, bottomMargin: bottom)
                return cell
            }
        case let .infoIncomeType(title, docs):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHPreviewInfoIncomeTypeCell.cellReuseIdentifier) as? YHPreviewInfoIncomeTypeCell {
                cell.setupCellInfo(title: title, documents: docs)
                return cell
            }
        }
        return UITableViewCell()
    }
}
