//
//  YHIncomeRecordAndWorkExperienceVC.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 YHIncomeRecordAndWorkExperienceVC: YHBaseViewController {
    enum TableRow {
        case incomeSummary(_ isEditing: Bool = false, _ isEditEnable: Bool = false)
        case incomeItem(_ isEditState: Bool = false, _ company: String, _ money: String, _ timeStr: String)
        case incomeOccupyingItem(_ title: String, _ detail: String)
        case addItem
        case totalImcome(_ money: ASAttributedString)
        case consentForHKTravel(_ isSelectSureBtn: Bool = true)
        case currentCompany(_ company: String?)
        case timeHeader
        case timeStatement(_ placeholder: String, _ remark: String?, _ detail: ASAttributedString)
    }
    
    private lazy var datas: [[TableRow]] = []
    
    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(YHAddIncomeRecordCell.self, forCellReuseIdentifier: YHAddIncomeRecordCell.cellReuseIdentifier)
        view.register(YHInfoConsentForHKTravelCell.self, forCellReuseIdentifier: YHInfoConsentForHKTravelCell.cellReuseIdentifier)
        view.register(YHTotalIncomeCell.self, forCellReuseIdentifier: YHTotalIncomeCell.cellReuseIdentifier)
        view.register(YHEmploymentVerificationAvailableCell.self, forCellReuseIdentifier: YHEmploymentVerificationAvailableCell.cellReuseIdentifier)
        view.register(YHWorkingHoursStatementCell.self, forCellReuseIdentifier: YHWorkingHoursStatementCell.cellReuseIdentifier)
        view.register(YHIncomeItemOccupyingCell.self, forCellReuseIdentifier: YHIncomeItemOccupyingCell.cellReuseIdentifier)
        view.register(YHWorkingHourHeaderCell.self, forCellReuseIdentifier: YHWorkingHourHeaderCell.cellReuseIdentifier)
        
        view.keyboardDismissMode = .onDrag
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = true
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = false
    }
}

extension YHIncomeRecordAndWorkExperienceVC {
    @objc private func clickSaveButton() {
        //
    }

    @objc private func clickSubmitButton() {
        //
    }

    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 totalMoney: ASAttributedString = .init(string: "约", .font(.PFSC_R(ofSize: 14))) + .init(string: "1,351,517", .font(UIFont(name: "DINAlternate-Bold", size: 16) ?? UIFont.systemFont(ofSize: 16))) + .init(string: "港币", .font(.PFSC_R(ofSize: 14)))
        let firstSection: [TableRow] = [.incomeSummary(false, false), .incomeItem(false, "华为有限公司", "约1,234,234港币", "2019.07-至今"), .incomeItem(false, "腾讯有限公司", "约1,234,234港币", "2015.07-2019.06"), .totalImcome(totalMoney), .addItem]
        
        let secondSection: [TableRow] = [.timeHeader, .timeStatement("如：工作时间灵活，可自由安排", nil, getOverlappingTimeAttributedTips())]
        let thirdSection: [TableRow] = [.consentForHKTravel(true), .currentCompany("华为科技有限公司")]
        datas = [firstSection, secondSection, thirdSection]
        tableView.reloadData()
    }
    
    private func getOverlappingTimeAttributedTips() -> ASAttributedString {
        let starStr: ASAttributedString = .init(.image(UIImage(named: "gc_red_dot") ?? UIImage(), bounds: CGRect(x: 0, y: 0, width: 6, height: 6)))
        let indentStr: ASAttributedString = .init(.image(UIImage(), bounds: CGRect(x: 0, y: 0, width: 5, height: 5)))
        let firstStr: ASAttributedString = .init(string: "检测到您的", .font(UIFont.PFSC_R(ofSize: 13)), .foreground(UIColor(hexString: "#8993A2") ?? .gray))
        let secondStr: ASAttributedString = .init(string: "工作时间有重叠", .font(UIFont.PFSC_B(ofSize: 13)), .foreground(UIColor.failColor))
        let thirdStr: ASAttributedString = .init(string: "。请确认是否正确填报，若填报无误请在此处说明工作时间重叠的原因~", .font(UIFont.PFSC_R(ofSize: 13)), .foreground(UIColor(hexString: "#8993A2") ?? .gray))
        let attributedText = (starStr + indentStr + firstStr + secondStr + thirdStr)
        return attributedText
    }
}

extension YHIncomeRecordAndWorkExperienceVC: 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)
                return cell
            }
        case let .incomeItem(isEditState, company, money, timeStr):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeRecordItemCell.cellReuseIdentifier) as? YHIncomeRecordItemCell {
                cell.setupCellInfo(title: company, detail: money, rightText: timeStr, isEditing: isEditState, showBottomLine: false)
                return cell
            }
        case .addItem:
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHAddIncomeRecordCell.cellReuseIdentifier) as? YHAddIncomeRecordCell {
                cell.addButtonClickEvent = {
                    //
                }
                return cell
            }
        case let .totalImcome(money):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHTotalIncomeCell.cellReuseIdentifier) as? YHTotalIncomeCell {
                cell.setupCellInfo(detail: money)
                cell.didClickInfoButton = {
                    YHHUD.flash(message: "注：按1港币≈0.92人民币计算，实际金额按递交时入境处给出的汇率为准")
                }
                return cell
            }
        case let .consentForHKTravel(isSelectSureBtn):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHInfoConsentForHKTravelCell.cellReuseIdentifier) as? YHInfoConsentForHKTravelCell {
                cell.textClicked = {
                    //
                }
                cell.didSelectSureButton = { _ in
                    //
                }
                cell.selectedSureButton = isSelectSureBtn
                return cell
            }
        case let .currentCompany(company):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHEmploymentVerificationAvailableCell.cellReuseIdentifier) as? YHEmploymentVerificationAvailableCell {
                cell.setupCellInfo(detail: company)
                return cell
            }
        case let .timeStatement(placeholder, remark, detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHWorkingHoursStatementCell.cellReuseIdentifier) as? YHWorkingHoursStatementCell {
                cell.setupCellInfo(placeholder: placeholder, remark: remark, detail: detail, isShowBottomLine: false)
                return cell
            }
        case let .incomeOccupyingItem(title, detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeItemOccupyingCell.cellReuseIdentifier) as? YHIncomeItemOccupyingCell {
                cell.setupCellInfo(title: title, rightText: detail)
                return cell
            }
        case .timeHeader:
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHWorkingHourHeaderCell.cellReuseIdentifier) as? YHWorkingHourHeaderCell {
                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)
        //
    }
}
