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

import UIKit

class YHGCMineSchemeViewController: YHBaseViewController {
    var tableView: UITableView!
    var dataSource: [YHScemeItemModel]? = []

    lazy var reqSchemeVM: YHGCMySchemeViewModel = {
        let vm = YHGCMySchemeViewModel()
        return vm
    }()

    lazy var headView: YHGCSchemeTableHeadView = {
        let headView = YHGCSchemeTableHeadView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 422))
        headView.update(type: .typeA, name: "--")
        return headView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "我的方案"
        gk_navTitleColor = .white
        gk_navBarAlpha = 1
        gk_navBackgroundImage = UIImage(named: "my_scheme_nav")
        gk_backImage = UIImage(named: "nav_icon_back_white")
        setView()
        loadData()
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    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 YHGCMineSchemeViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let dataSource = dataSource, dataSource.count > indexPath.row else {
            return UITableViewCell()
        }
        let cell = tableView.dequeueReusableCell(withClass: YHGCSchemeTableViewCell.self)
        let model = dataSource[indexPath.row]
        cell.dataSource = model
        cell.schemeBlock = { [weak self] in
            guard let self = self else {
                return
            }
            if model.title == "资料清单" {
                if self.reqSchemeVM.schemeModel?.certificate_skip_status == true {
                    let vc = YHGCMineCertificateEntryViewController()
                    vc.orderId = orderId
                    self.navigationController?.pushViewController(vc)
                } else {
                    YHHUD.flash(message: "您的资料清单正在准备中，请耐心等待。")
                }
            }
        }
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
}

extension YHGCMineSchemeViewController {
    func setView() {
        view.backgroundColor = .contentBkgColor
        tableView = {
            let tableView = UITableView(frame: .zero, style: .plain)
            if #available(iOS 11.0, *) {
                tableView.contentInsetAdjustmentBehavior = .never
            }
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.tableFooterView = YHSchemeTableFooterView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 112))

            tableView.tableHeaderView = headView
            tableView.register(cellWithClass: YHGCSchemeTableViewCell.self)
            tableView.bounces = false
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.bottom.equalToSuperview()
        }
    }

    func loadData() {
        let param = ["order_id": orderId]
        reqSchemeVM.getMySchemeData(params: param) { [weak self] success, error in
            guard let self = self else {
                return
            }
            if success == true {
                guard let model = self.reqSchemeVM.schemeModel else { return }

                let industry = model.industry
                if !industry.isEmpty {
                    let model1 = YHScemeItemModel(title: "职业界别", mainMessage: "根据您目前给来的材料，初步建议您申请的行业：\n" + industry, lightMessage: industry, subMessage: "后续会根据您文书准备的补充情况来最终确定，如有修改会再告知您。", lightFont: UIFont.PFSC_B(ofSize: 16))
                    self.dataSource?.append(model1)
                }
                
                let contentStr: String
                if model.content.count > 1 {
                    contentStr = model.content.enumerated().reduce("") { partialResult, current in
                        let (index, content) = current
                        return partialResult + "\n" + "（\(index + 1)）" + content
                    }
                } else if model.content.count > 0 {
                    contentStr = model.content.reduce("") { partialResult, current in
                        return partialResult + "\n" + current
                    }
                } else {
                    contentStr = ""
                }
                
                let model2 = YHScemeItemModel(title: "资料清单", buttonTitle: "资料清单", mainMessage: "这是您的资料清单，请您前往查看，请您在1-2周内准备好文件并上传：", lightMessage: "1-2周内", subMessage: "按照您填报的收入信息， 证明文件如下：\(contentStr)")
                self.dataSource?.append(model2)
                self.tableView.reloadData()
                let type = YHGCApplicationType(rawValue: model.application_type) ?? .typeA
                let name = model.user_name.isEmpty ? "--" : "尊敬的\(model.user_name)"
                self.headView.update(type: type, name: name)
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "请求出错")
            }
        }
    }
}
