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

import AttributedString
import UIKit

class YHGCPreviewIncomeRecordViewController: YHPreviewBaseViewController {
    enum PageType: Int {
        case pageA
        case pageBC
    }
    
    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], _ subtitle: String? = nil, _ cellType: YHResignRoundCellType = .mid)
        case infoTips(_ detail: ASAttributedString)
    }
    
    private lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无工作经验", kEmptyCommonBgName)
        if pageType == .pageA {
            view.tips = "暂无收入记录/工作经验"
        } else {
            view.tips = "暂无工作经验"
        }
        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 = YHGCPreviewViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        requestData()
    }
    
    private let orderId: Int
    private let pageType: PageType
    init(orderId: Int, pageType: PageType) {
        self.orderId = orderId
        self.pageType = pageType
        super.init(nibName: nil, bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension YHGCPreviewIncomeRecordViewController {
    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(YHGCPreviewIncomeTypeCell.self, forCellReuseIdentifier: YHGCPreviewIncomeTypeCell.cellReuseIdentifier)
        homeTableView.register(YHIncomeRecordCompanyTipsCell.self, forCellReuseIdentifier: YHIncomeRecordCompanyTipsCell.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: 28))
    }
    
    private func currencyFormat(_ currencySymbol: String) -> NumberFormatter {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.currencySymbol = currencySymbol
        formatter.maximumFractionDigits = 0
        return formatter
    }
    
    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() {
        if pageType == .pageA {
            setupDataForPageA()
        } else {
            setupDataForPageBC()
        }
    }
    
    private func setupDataForPageA() {
        guard let workExpInfoPreviewModel = viewModel.workExpInfoPreviewModel, let list = workExpInfoPreviewModel.list else {
            noDataView.isHidden = false
            datas = []
            homeTableView.reloadData()
            return
        }
        datas.removeAll()
        var basicInfoSection: [TableRow] = [.infoHeader("基本信息")]
        let currencyFmt = currencyFormat("")
        let rate = getCurrentRate()
        var totalMoney: Double = 0
        
        let listCount = workExpInfoPreviewModel.count
        let workId = workExpInfoPreviewModel.consent_work_id
        var workCompany: WorkExpInfoPreviewDetailModel?
        list.enumerated().forEach { index, model in
            if workId != 0, model.id == workId {
                workCompany = model
            }
            var incomeSection: [TableRow] = []
            var workSection: [TableRow] = []
            
            if listCount > 1 {
                incomeSection.append(.infoHeader("主申请人收入(\(index + 1))"))
                workSection.append(.infoHeader("主申请人工作经历(\(index + 1))"))
            } else {
                incomeSection.append(.infoHeader("主申请人收入"))
                workSection.append(.infoHeader("主申请人工作经历"))
            }
            
            incomeSection.append(.infoTitleAndDetail("收入来源公司：", model.company_name, .mid, 16, 8))
            let incomeMoney = Double(model.income) ?? 0
            incomeSection.append(.infoTitleAndDetail("收入金额(港元)：", currencyFmt.string(from: NSNumber(value: incomeMoney / rate)) ?? "0", .bottom, 8, 16))
            
            workSection.append(.infoTitleAndDetail("用人单位：", model.company_name, .mid, 16, 8))
            var location: String = ""
            let country = model.location?.country ?? ""
            if country.contains("中国") {
                let city = model.location?.area.reduce("") { partialResult, item in
                    partialResult.count > 0 ? partialResult + "/" + item : partialResult + item
                } ?? ""
                location = country + "-" + city
            } else {
                let city = model.location?.foreign ?? ""
                location = country + "-" + city
            }
            workSection.append(.infoTitleAndDetail("派薪地点：", location, .mid, 8, 8))
            workSection.append(.infoTitleAndDetail("职位：", model.position, .mid, 8, 8))
            
            workSection.append(.infoTitleAndDetail("入职年月：", model.entry_time, .mid, 8, 8))
            workSection.append(.infoTitleAndDetail("离职年月：", model.departure_time, .mid, 8, 8))
            workSection.append(.infoTitleAndDetail("是否可以提供工作证明文件：", model.has_work_certificate == 1 ? "是" : "否", .mid, 8, 8))
            let selectedTypes = model.type_of_income.compactMap {
                YHGCIncomeType(rawValue: $0)
            }
            if selectedTypes.count > 1 {
                workSection.append(.infoIncomeType("收入类型：", selectedTypes.enumerated().map { index, type in
                    "\(index + 1)." + type.nameString()
                }))
            } else {
                workSection.append(.infoTitleAndDetail("收入类型", selectedTypes.first?.nameString() ?? "", .mid, 8, 8))
            }
            if selectedTypes.contains(.incomeOfMainland) || selectedTypes.contains(.incomeOfHKCompanies) || selectedTypes.contains(.incomeOfMacauCompanies) || selectedTypes.contains(.incomeOfOtherOverseasCompanies) {
                let turnover = Double(model.turnover) ?? 0
                workSection.append(.infoTitleAndDetail("公司营业额/人民币 (近一年)：", currencyFmt.string(from: NSNumber(value: turnover)) ?? "0", .mid, 8, 8))
            }
            let companyType = model.company_type
            if companyType == "其他" {
                workSection.append(.infoIncomeType("职业界别：", [model.company_type_other], companyType, .bottom))
            } else {
                workSection.append(.infoTitleAndDetail("职业界别：", companyType, .bottom, 8, 16))
            }
            totalMoney += Double(model.income) ?? 0
            datas.append(incomeSection)
            datas.append(workSection)
        }
        
        basicInfoSection.append(.infoTitleAndDetail("主申请人总收入(港元)：", currencyFmt.string(from: NSNumber(value: totalMoney / rate)) ?? "0", .mid, 16, 8))
        if workExpInfoPreviewModel.has_company_consent == 1 {
            basicInfoSection.append(.infoTitleAndDetail("在职公司是否可以提供赴港同意书：", "是", .mid, 8, 8))
            if let workCompany = workCompany {
                basicInfoSection.append(.infoIncomeType("可提供赴港同意书的在职公司：", [workCompany.company_name], nil, .bottom))
            } else {
                basicInfoSection.append(.infoIncomeType("可提供赴港同意书的在职公司：", [], nil, .bottom))
            }
        } else {
            basicInfoSection.append(.infoTitleAndDetail("在职公司是否可以提供赴港同意书：", "否", .mid, 8, 8))
            let message = workExpInfoPreviewModel.has_center_consent == 1 ? "是" : "否"
            basicInfoSection.append(.infoTitleAndDetail("人才中心是否可以提供赴港同意书：", message, .bottom, 8, 16))
        }
        datas.insert(basicInfoSection, at: 0)
        if workExpInfoPreviewModel.has_work_time_overlap == 1 {
            var timeOverlapSection: [TableRow] = [.infoHeader("工作时间重叠原因")]
            let detail: ASAttributedString = .init(string: workExpInfoPreviewModel.why_work_time_overlap, .foreground(UIColor(hexString: "#8993A2") ?? .gray), .font(UIFont.PFSC_R(ofSize: 14)))
            timeOverlapSection.append(.infoTips(detail))
            datas.append(timeOverlapSection)
        }
        
        noDataView.isHidden = true
        homeTableView.reloadData()
    }
    
    private func setupDataForPageBC() {
        guard let workExpInfoPreviewModel = viewModel.workExpInfoPreviewModel, let list = workExpInfoPreviewModel.list else {
            noDataView.isHidden = false
            datas = []
            homeTableView.reloadData()
            return
        }
        datas.removeAll()
        var basicInfoSection: [TableRow] = [.infoHeader("基本信息")]
        basicInfoSection.append(.infoTitleAndDetail("主申请人是否有工作经验：", workExpInfoPreviewModel.has_work_experience == 1 ? "是" : "否", .mid, 16, 8))
        let listCount = workExpInfoPreviewModel.count
        let workId = workExpInfoPreviewModel.consent_work_id
        var workCompany: WorkExpInfoPreviewDetailModel?
        list.enumerated().forEach { index, model in
            if workId != 0, model.id == workId {
                workCompany = model
            }
            var workSection: [TableRow] = []
            
            if listCount > 1 {
                workSection.append(.infoHeader("主申请人工作经历(\(index + 1))"))
            } else {
                workSection.append(.infoHeader("主申请人工作经历"))
            }
            workSection.append(.infoTitleAndDetail("用人单位：", model.company_name, .mid, 16, 8))
            var location: String = ""
            let country = model.location?.country ?? ""
            if country.contains("中国") {
                let city = model.location?.area.reduce("") { partialResult, item in
                    partialResult.count > 0 ? partialResult + "/" + item : partialResult + item
                } ?? ""
                location = country + "-" + city
            } else {
                let city = model.location?.foreign ?? ""
                location = country + "-" + city
            }
            workSection.append(.infoTitleAndDetail("工作地点：", location, .mid, 8, 8))
            workSection.append(.infoTitleAndDetail("职位：", model.position, .mid, 8, 8))
            
            workSection.append(.infoTitleAndDetail("入职年月：", model.entry_time, .mid, 8, 8))
            workSection.append(.infoTitleAndDetail("离职年月：", model.departure_time, .mid, 8, 8))
            workSection.append(.infoTitleAndDetail("是否可以提供工作证明文件：", model.has_work_certificate == 1 ? "是" : "否", .mid, 8, 8))
           
            let companyType = model.company_type
            if companyType == "其他" {
                workSection.append(.infoIncomeType("职业界别：", [model.company_type_other], companyType, .bottom))
            } else {
                workSection.append(.infoTitleAndDetail("职业界别：", companyType, .bottom, 8, 16))
            }
            datas.append(workSection)
        }
        
        if workExpInfoPreviewModel.has_company_consent == 1 {
            basicInfoSection.append(.infoTitleAndDetail("在职公司是否可以提供赴港同意书：", "是", .mid, 8, 8))
            if let workCompany = workCompany {
                basicInfoSection.append(.infoIncomeType("可提供赴港同意书的在职公司：", [workCompany.company_name], nil, .bottom))
            } else {
                basicInfoSection.append(.infoIncomeType("可提供赴港同意书的在职公司：", [], nil, .bottom))
            }
        } else {
            basicInfoSection.append(.infoTitleAndDetail("在职公司是否可以提供赴港同意书：", "否", .mid, 8, 8))
            let message = workExpInfoPreviewModel.has_center_consent == 1 ? "是" : "否"
            basicInfoSection.append(.infoTitleAndDetail("人才中心是否可以提供赴港同意书：", message, .bottom, 8, 16))
        }
        datas.insert(basicInfoSection, at: 0)
        
        if workExpInfoPreviewModel.has_work_time_overlap == 1 {
            var timeOverlapSection: [TableRow] = [.infoHeader("工作时间重叠原因")]
            let detail: ASAttributedString = .init(string: workExpInfoPreviewModel.why_work_time_overlap, .foreground(UIColor(hexString: "#8993A2") ?? .gray), .font(UIFont.PFSC_R(ofSize: 14)))
            timeOverlapSection.append(.infoTips(detail))
            datas.append(timeOverlapSection)
        }
        
        noDataView.isHidden = true
        homeTableView.reloadData()
    }
    
    private func requestData() {
        viewModel.getPreviewForGCWorkExpInfo(params: ["order_id": orderId]) { [weak self] success, error in
            guard let self = self else {
                return
            }
            guard success else {
                printLog("YHGCPreviewIncomeRecordViewController:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                self.noDataView.isHidden = false
                self.datas = []
                self.homeTableView.reloadData()
                return
            }
            self.setupData()
        }
    }
}

// MARK: - UITableViewDelegate 和 UITableViewDataSource
extension YHGCPreviewIncomeRecordViewController {
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 16
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }

    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard datas.count > section else {
            return 0
        }
        return datas[section].count
    }
    
    override 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 .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, subtitle, cellType):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHGCPreviewIncomeTypeCell.cellReuseIdentifier) as? YHGCPreviewIncomeTypeCell {
                cell.setupCellInfo(title: title, documents: docs, subtitle: subtitle, cellType: cellType)
                return cell
            }
        case let .infoTips(detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeRecordCompanyTipsCell.cellReuseIdentifier) as? YHIncomeRecordCompanyTipsCell {
                cell.setupCellInfo(tipsDetail: detail, cellType: .bottom)
                return cell
            }
        }
        return UITableViewCell()
    }
}
