//
//  YHMyNewSchemeViewController.swift
//  galaxy
//
//  Created by Dufet on 2024/11/15.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

enum YHSchemeItemType: Int {
    case none = 0
    case evaluate = 1 // 综合评估
    case industryLocation = 2 // 行业定位
    case materialList = 3 // 资料清单
    case documentList = 4 // 文书清单
    case improveScheme = 5 // 提升方案
    case modifyInfo = 6 // 修改信息
    case improveTarget = 7 // 提升目标
    case hkRequireList = 8 // 港府要求
}

class YHSchemeItem {
    var type: YHSchemeItemType
    init(type: YHSchemeItemType) {
        self.type = type
    }
}

class YHMyNewSchemeViewController: YHBaseViewController {

    var orderId: Int = 0
    // 通过的至少要求数量
    let passMinCount: Int = 6
    var tipsType = YHSchemeTipsType.none

    var items: [[YHSchemeItem]] = []
    var passArr: [YHComprehensiveEevaluationModel] = []
    var unpassArr: [YHComprehensiveEevaluationModel] = []
    var isPass: Bool = false
    let viewModel = YHSchemeViewModel()
    
    static let shared = YHMyNewSchemeViewController()

    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame: .zero, style: .grouped)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHComprehensiveEvaluationCell.self, forCellReuseIdentifier: YHComprehensiveEvaluationCell.cellReuseIdentifier)
        tableView.register(YHHKRequiredItemListCell.self, forCellReuseIdentifier: YHHKRequiredItemListCell.cellReuseIdentifier)
        tableView.register(YHIndustryLocationCell.self, forCellReuseIdentifier: YHIndustryLocationCell.cellReuseIdentifier)
        tableView.register(YHMaterialListCell.self, forCellReuseIdentifier: YHMaterialListCell.cellReuseIdentifier)
        tableView.register(YHDocumentListCell.self, forCellReuseIdentifier: YHDocumentListCell.cellReuseIdentifier)
        tableView.register(YHImproveSchemeCell.self, forCellReuseIdentifier: YHImproveSchemeCell.cellReuseIdentifier)
        tableView.register(YHImproveTargetCell.self, forCellReuseIdentifier: YHImproveTargetCell.cellReuseIdentifier)
        tableView.register(YHModifySchemeInfoCell.self, forCellReuseIdentifier: YHModifySchemeInfoCell.cellReuseIdentifier)

        tableView.bounces = false
        tableView.tableFooterView = bottomLogoView
        tableView.isHidden = true
        return tableView
    }()
    
    lazy var bgView: UIView = {
        
        let view = UIView()
        view.isHidden = true
        
        let bgImgView = UIImageView(image: UIImage(named: "my_scheme_head_img"))
        view.addSubview(bgImgView)
        
        let leftWheatearImgV = UIImageView(image: UIImage(named: "my_scheme_wheatear_left"))
        view.addSubview(leftWheatearImgV)
        
        let rightWheatearImgV = UIImageView(image: UIImage(named: "my_scheme_wheatear_right"))
        view.addSubview(rightWheatearImgV)
        
        view.addSubview(titleLabel)
        view.addSubview(subTitleLabel)
        
        bgImgView.snp.makeConstraints { make in
            make.left.equalTo(-0)
            make.right.equalTo(0)
            make.top.equalToSuperview()
            make.height.equalTo(416.0)
        }

        leftWheatearImgV.snp.makeConstraints { make in
            make.left.equalTo(35)
            make.top.equalTo(27)
            make.width.equalTo(65)
            make.height.equalTo(80)
        }
        
        rightWheatearImgV.snp.makeConstraints { make in
            make.right.equalTo(-35)
            make.top.equalTo(27)
            make.width.equalTo(65)
            make.height.equalTo(80)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(27)
            make.height.equalTo(34)
            make.left.equalTo(subTitleLabel)
            make.right.equalTo(subTitleLabel)
        }
        
        subTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(leftWheatearImgV.snp.left).offset(38)
            make.right.equalTo(rightWheatearImgV.snp.right).offset(-38)
            make.top.equalTo(titleLabel.snp.bottom).offset(8)
        }

        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_B(ofSize: 24)
        label.textColor = .white
        label.text = "尊敬的先生"
        label.textAlignment = .center
        label.lineBreakMode = .byTruncatingMiddle
        return label
    }()
    
    lazy var subTitleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.textColor = .white
        label.textAlignment = .center
        label.text = "您好，根据您的信息，这是我们为您定制的申请方案，方案详情如下："
        return label
    }()
    
    lazy var bottomLogoView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 66+k_Height_safeAreaInsetsBottom()))
        
        let leftImgV = UIImageView(image: UIImage(named: "my_scheme_logo_line_left"))
        let rightImgV = UIImageView(image: UIImage(named: "my_scheme_logo_line_right"))
        let logoImgV = UIImageView(image: UIImage(named: "my_scheme_logo"))
        view.addSubview(leftImgV)
        view.addSubview(rightImgV)
        view.addSubview(logoImgV)
        
        logoImgV.snp.makeConstraints { make in
            make.width.equalTo(90)
            make.height.equalTo(17)
            make.top.equalTo(32)
            make.bottom.equalTo(-16-k_Height_safeAreaInsetsBottom())
            make.centerX.equalToSuperview()
        }
        leftImgV.snp.makeConstraints { make in
            make.height.equalTo(2.75)
            make.left.equalTo(11)
            make.right.equalTo(logoImgV.snp.left).offset(-10)
            make.bottom.equalTo(logoImgV.snp.bottom).offset(-3)
        }
        
        rightImgV.snp.makeConstraints { make in
            make.height.equalTo(2.75)
            make.right.equalTo(-11)
            make.left.equalTo(logoImgV.snp.right).offset(10)
            make.bottom.equalTo(logoImgV.snp.bottom).offset(-3)
        }
        return view
    }()
    
    func goToSchemePage() {
        
        if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") as? Int {
            orderId = orderID
        }
        YHHUD.show(.progress(message: "加载中..."))
        
        viewModel.getMySchemeData(orderId: orderId) {
            [weak self] _, _ in
            YHHUD.hide()
            guard let self = self else { return }
            
            passArr = self.viewModel.schemeModel.comprehensive_evaluation.filter {
                $0.isPass == true
            }
            
            if passArr.count >= passMinCount { // 满足至少6项
                let vc = YHMyNewSchemeViewController()
                UIViewController.current?.navigationController?.pushViewController(vc)
                
            } else { // 不满足条件
                
                if self.viewModel.schemeModel.comprehensive_evaluation_selected.count > 0 {
                    // 进入提升方案界面
                    let vc1 = YHMyNewSchemeViewController()
                    let vc2 = YHImproveSchemeViewController()
                    vc2.isPass = false
                    vc2.orderId = orderId
                    
                    UIViewController.current?.navigationController?.pushViewController(vc1, animated: false)
                    UIViewController.current?.navigationController?.pushViewController(vc2, animated: false)
                    
                } else {
                    let vc = YHMyNewSchemeViewController()
                    UIViewController.current?.navigationController?.pushViewController(vc)
                }
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        gk_navTitle = "我的方案"
        gk_navTitleColor = .white
        gk_navBarAlpha = 1
        gk_navBackgroundImage = UIImage(named: "my_scheme_nav")
        gk_backImage = UIImage(named: "back_icon_white")
        view.backgroundColor = .init(hex: 0x090B26)

        self.view.addSubview(bgView)
        self.view.addSubview(tableView)
        bgView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.height.equalTo(415)
        }
        tableView.snp.makeConstraints { make in
            make.left.equalTo(8.3)
            make.right.equalTo(-8.5)
            make.bottom.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
        }
        tableView.reloadData()
        requestData()
    }
    
    func requestData() {
        
        if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") as? Int {
            orderId = orderID
        }

        YHHUD.show(.progress(message: "加载中..."))
        viewModel.getMySchemeData(orderId: orderId) {
            [weak self] _, _ in
            YHHUD.hide()
            guard let self = self else { return }
            titleLabel.text = "尊敬的\(viewModel.schemeModel.username)\(viewModel.schemeModel.sex)"
            passArr = self.viewModel.schemeModel.comprehensive_evaluation.filter {
                $0.isPass == true
            }
            unpassArr = self.viewModel.schemeModel.comprehensive_evaluation.filter {
                $0.isPass == false
            }
            
            for item in unpassArr {
                if self.viewModel.schemeModel.comprehensive_evaluation_selected.contains(item.standardKey) {
                    item.is_select = true
                } else {
                    item.is_select = false
                }
            }
            
            items.removeAll()
            
            // 至少满足6项才通过
            isPass = passArr.count >= passMinCount
            
            var arr1 = [YHSchemeItem]()
            if passArr.count == 0 { // 一项都不满足 不通过
                
                tipsType = .neverPass
                
                let item1 = YHSchemeItem(type: .evaluate)
                let item2 = YHSchemeItem(type: .modifyInfo)
                arr1 = [item1, item2]
                
            } else if 1 <= passArr.count, passArr.count < passMinCount { // 不满足至少通过数 不通过
                
                tipsType = .partPass

                let item1 = YHSchemeItem(type: .evaluate)
                let item2 = YHSchemeItem(type: .hkRequireList)
                let item3 = YHSchemeItem(type: .modifyInfo)
                arr1 = [item1, item2, item3]

            } else if passArr.count >= passMinCount { // 满足至少通过数
                
                tipsType = .pass

                let item1 = YHSchemeItem(type: .evaluate)
                arr1.append(item1)
                
                let item2 = YHSchemeItem(type: .hkRequireList)
                arr1.append(item2)

                let item3 = YHSchemeItem(type: .industryLocation)
                arr1.append(item3)
                
                let item4 = YHSchemeItem(type: .materialList)
                arr1.append(item4)

                let item5 = YHSchemeItem(type: .documentList)
                arr1.append(item5)

                if passArr.count < self.viewModel.schemeModel.comprehensive_evaluation.count { // 不是全满足则显示提升方案
                    let item6 = YHSchemeItem(type: .improveScheme)
                    arr1.append(item6)
                }
            }
            
            items.append(arr1)
                        
            if !isPass {
                let item11 = YHSchemeItem(type: .improveTarget)
                let arr2: [YHSchemeItem] = [item11]
                items.append(arr2)
            }
            self.tableView.reloadData()
            self.tableView.isHidden = false
            self.bgView.isHidden = false

        }
    }
    
    func submitTargets() {
        
        let selectTargets: [YHComprehensiveEevaluationModel] = unpassArr.filter {
            return $0.is_select
        }
        let selectKeys: [String] = selectTargets.map {
            return $0.standardKey
        }
        
        if selectKeys.count <= 0 {
            YHHUD.flash(message: "请选择提升目标")
            return
        }
        
        YHHUD.show(.progress(message: "提交中..."))
        viewModel.postSelectImproveTargets(orderId: orderId, targets: selectKeys) {
            [weak self] success, error in
            YHHUD.hide()
            guard let self = self else { return }

            if success {
                let vc = YHImproveSchemeViewController()
                vc.orderId = orderId
                vc.isPass = self.isPass
                UIViewController.current?.navigationController?.pushViewController(vc)
                return
            }
            YHHUD.flash(message: error?.errorMsg ?? "提交失败")
        }
    }
    
    func modifyInfo() {
        YHHUD.show(.progress(message: "修改中..."))
        viewModel.modifyInfo(orderId: orderId) {
            [weak self] success, error in
            YHHUD.hide()
            guard let self = self else { return }
            
            if success {
                let vc = YHInformationPerfectListVC()
                vc.orderId = orderId
                navigationController?.pushViewController(vc)
                return
            }
            YHHUD.flash(message: error?.errorMsg ?? "修改失败")
        }
    }
    
    func getIndustryDetail() -> String {
        let target = viewModel.schemeModel.industry_positioning
        if target == "15" {
            return "其他（\(viewModel.schemeModel.industry_positioning_other)）"
        }
        for(_, item) in YHConstantArrayData.arrSkill.enumerated() {
            if target == item["value"] {
                return item["title"] ?? ""
            }
        }
        return ""
    }

}

extension YHMyNewSchemeViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if 0 <= section, section < items.count {
            let arr = items[section]
            return arr.count
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if 0 <= indexPath.section, indexPath.section < items.count {
            let arr = items[indexPath.section]
            var targetCell: UITableViewCell?
            
            if 0 <= indexPath.row && indexPath.row < arr.count {
                let item = arr[indexPath.row]
                
                if item.type == .evaluate {
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: YHComprehensiveEvaluationCell.cellReuseIdentifier, for: indexPath) as? YHComprehensiveEvaluationCell else {
                        return UITableViewCell()
                    }
                    cell.tipsType = self.tipsType
                    targetCell = cell
                }
                
                if item.type == .hkRequireList {
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRequiredItemListCell.cellReuseIdentifier, for: indexPath) as? YHHKRequiredItemListCell else {
                        return UITableViewCell()
                    }
                    cell.passArr = self.passArr
                    targetCell = cell
                }
                
                if item.type == .industryLocation {
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: YHIndustryLocationCell.cellReuseIdentifier, for: indexPath) as? YHIndustryLocationCell else { return UITableViewCell() }
                    cell.industry = self.getIndustryDetail()
                    targetCell = cell
                }
                
                if item.type == .materialList {
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: YHMaterialListCell.cellReuseIdentifier, for: indexPath) as? YHMaterialListCell else { return UITableViewCell() }
                    cell.rightBtnClick = {
                        [weak self] in
                        guard let self = self else { return }
                        
                        if !self.viewModel.schemeModel.certificate_skip_status {
                            YHHUD.flash(message: "您的资料清单正在准备中，请耐心等待")
                            return
                        }
                        if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") {
                            let vc = YHMineCertificateEntryViewController()
                            vc.orderId = orderID as? Int ?? 0
                            UIViewController.current?.navigationController?.pushViewController(vc)
                        } else {
                            YHHUD.flash(message: "订单号为空")
                        }
                    }
                    targetCell = cell
                }
                
                if item.type == .documentList {
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: YHDocumentListCell.cellReuseIdentifier, for: indexPath) as? YHDocumentListCell else { return UITableViewCell() }
                    cell.rightBtnClick = {
                        [weak self] in
                        guard let self = self else { return }
                        
                        if !self.viewModel.schemeModel.supplement_skip_status {
                            YHHUD.flash(message: "您的文书正在制作中，请耐心等待")
                            return
                        }
                        if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") {
                            let vc = YHMyDocumentsListViewController()
                            vc.orderId = orderID as? Int ?? 0
                            UIViewController.current?.navigationController?.pushViewController(vc)
                            
                        } else {
                            YHHUD.flash(message: "订单号为空")
                        }
                    }
                    targetCell = cell
                }
                
                if item.type == .improveScheme {
                    
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: YHImproveSchemeCell.cellReuseIdentifier, for: indexPath) as? YHImproveSchemeCell else { return UITableViewCell() }
                    cell.rightBtnClick = {
                        [weak self] in
                        guard let self = self else { return }
                        
                        if !self.viewModel.schemeModel.plan_skip_status {
                            YHHUD.flash(message: "您的提升方案正在制作中，请耐心等待")
                            return
                        }
                        let vc = YHImproveSchemeViewController()
                        vc.orderId = orderId
                        vc.isPass = self.isPass
                        UIViewController.current?.navigationController?.pushViewController(vc)
                    }
                    targetCell = cell
                }
                
                if item.type == .modifyInfo {
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: YHModifySchemeInfoCell.cellReuseIdentifier, for: indexPath) as? YHModifySchemeInfoCell else { return UITableViewCell() }
                    cell.modifyBlock = {
                        [weak self] in
                        guard let self = self else { return }
                        self.modifyInfo()
                    }
                    targetCell = cell
                }
                
                if item.type == .improveTarget {
                    guard let cell = tableView.dequeueReusableCell(withIdentifier: YHImproveTargetCell.cellReuseIdentifier, for: indexPath) as? YHImproveTargetCell else { return UITableViewCell() }
                    cell.unpassArr = unpassArr
                    cell.submitClick = {
                        [weak self] in
                        guard let self = self else { return }
                        self.submitTargets()
                    }
                    targetCell = cell
                }
                
                if let targetCell = targetCell {
                    return targetCell
                }
            }
        }
        
        let defaultCell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath) 
        return defaultCell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if 0 <= indexPath.section, indexPath.section < items.count {
            let arr = items[indexPath.section]
            if 0 <= indexPath.row && indexPath.row < arr.count {
                // 最后一个cell切底部圆角
                self.createCorner(cell: cell, isLastCell: indexPath.row == arr.count-1)
            }
        }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 12.0
    }
    
    func createCorner(cell: UITableViewCell, isLastCell: Bool) {
        if isLastCell {
            let corner = UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue)
            cell.createCorner(CGSize(width: 6.0, height: 6.0), corner)
            
        } else {
            cell.layer.mask = nil
        }
    }
}

extension YHMyNewSchemeViewController: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let scrollY = scrollView.contentOffset.y
        if scrollY >= 0.0 {
            bgView.frame.origin.y = k_Height_NavigationtBarAndStatuBar-scrollY
        } else {
            bgView.frame.origin.y = k_Height_NavigationtBarAndStatuBar
        }
    }
}
