//
//  YHServiceOrderListView.swift
//  galaxy
//
//  Created by EDY on 2024/4/16.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView

/// *
// 银河订单类型 列表
// */
// enum YHProductType: Int {
//    case productType_Yc = 0 //优才订单
//    case productType_Gc_A = 1 //高才A
//    case productType_Gc_B = 2 //高才B
//    case productType_Gc_C = 3 //高才C
// }

class YHServiceOrderListViewController: YHBaseViewController {
    let principleViewModel: YHPrincleViewModel = YHPrincleViewModel()
    let appointViewModel = YHCerAppointViewModel()
    public var vcCanScroll: Bool = true

    typealias Block = (Int, Int, Bool) -> Void
    var block: Block?
    var orderID: Int = 0
    var type: Int = 0
    var mobile: String = ""
    var homeTableView: UITableView!
    var orderType: Int = 0
    var state: Int = 0
    var stepID: Int = 0
    var productInfoMode: YHContactItemModel = YHContactItemModel()
    var arrDataForSeviceCenterProgress: [YHServiceCenterProgressModel] = []

    lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无", kEmptyCommonBgName)
        view.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 150)
        view.backgroundColor = .clear
        return view
    }()
    
    lazy var footView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 590))
        view.addSubview(self.noDataView)
        self.noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(150)
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
        NotificationCenter.default.addObserver(self, selector: #selector(beginDragging), name: Notification.Name(rawValue: "scrollViewWillBeginDragging0"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(endDragging), name: Notification.Name(rawValue: "scrollViewDidEndDragging0"), object: nil)
    }
    
    class func jumpToMessageController(type: Int, orderId: Int, _ stepId: Int = 0, productType: Int = 0) {
        if type == 1 {
            // 我的证件
            let vc = YHMineCertificateEntryViewController()
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
            
        } else if type == 2 {
            // 我的信息
            let vc = YHInformationPerfectListVC()
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
            
        } else if type == 3 {
            // 我的评分
            let vc = YHScoreDetailViewController()
            vc.orderId = orderId
//                vc.model = serviceCenterMainReqVM.allInfoScoreModel
            UIViewController.current?.navigationController?.pushViewController(vc)
                    
        } else if type == 4 { // 方案
            // 我的方案
            YHMyNewSchemeViewController.shared.goToSchemePage()

        } else if type == 5 {
            // 我的签字
            let vc = YHMySignatureListViewController()
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
            
        } else if type == 6 {
            // 我的文书
            let vc = YHMyDocumentsListViewController()
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
            
        } else if type == 7 {
            // 递交确认
            let viewModel = YHServiceCenterViewModel()
            viewModel.getServiceMainDocUrl(orderId: orderId) {_, _ in
                let vc = YHH5WebViewVC()
                vc.url = viewModel.url
                vc.isNeedRefreshDataFlag = true
                UIViewController.current?.navigationController?.pushViewController(vc)
            }
            
        } else if type == 11 || type == 12 || type == 14 {
            
            // 11 原则批等待结果
            // 12 原则批待补件
            // 14 原则批未获批准
            
            let vc = YHPrincipleWaitResultViewController()
            vc.status = type
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
            
        } else if type == 13 {
            // 原则批已获批~
            let vc = YHPrincipleApprovedResultVC()
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
            
        } else if type == 15 {
            // 正式批已获批~
            let vc = YHOfficialApprovalResultVC()
            UIViewController.current?.navigationController?.pushViewController(vc)
        } else if type == 21 {
            // 新增受养人
            let vc = YHAddAdoptersViewController()
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
        } else if type == 22 {
            // 家庭信息确认
            let vc = YHFamilyInfoConfirmViewController()
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
        } else if type == 23 {
            // 电子签字缴费
            let vc = YHVisaPaymentVC()
            vc.orderID = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
        } else if type == 24 {
            // 赴港时间预约
            let vc = YHCertificateAppointViewController()
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
            
        } else if type == 25 {
            // 赴港行程指引
            YHHUD.show(.progress(message: "加载中..."))
            let appointViewModel = YHCerAppointViewModel()
            appointViewModel.getIsNeedGoToHK(orderId: orderId) {
                // needGoHK 1需要赴港 0不需要 2没有选择
                // reservationToHK 0 没有预约 1 已经预約
                needGoHK, reservationToHK in
                YHHUD.hide()
                var isNeedAppoint = true
                if needGoHK == 1, reservationToHK == 1 { // 选择赴港且已预约
                    isNeedAppoint = false
                } else if needGoHK == 0 { // 赴港选择否
                    isNeedAppoint = false
                }
                
                if isNeedAppoint {
                    // 预约弹窗
                    let alert = YHDisappointHKAlertView.alertView()
                    alert.confirmBlock = {
                        let vc = YHCertificateAppointViewController()
                        vc.orderId = orderId
                        UIViewController.current?.navigationController?.pushViewController(vc)
                    }
                    alert.show()
                    
                } else { // 已预约过直接进入赴港行程指引
                    if let token = YHLoginManager.shared.userModel?.token, token.count > 5 {
                        var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/tohkList"
                        url = url + "?paramO=\(orderId)" + "&param=" + YHLoginManager.shared.h5Token
                        url = url + "&app_platform=ios" + "&app_version=" + UIDevice.appVersion()
                        printLog("UURL: \(url)")
                        let vc = YHH5WebViewVC()
                        vc.title = "赴港行程指引"
                        vc.url = url
                        vc.isFullScreenFlag = false
                        vc.navTitle = "赴港行程指引"
                        vc.isNeedRefreshDataFlag = true
                        UIViewController.current?.navigationController?.pushViewController(vc)
                    }
                }
            }
            
        } else if type == 26 {
            // 旅行证件准备
            let vc = YHTravelDocsPreparationListViewController()
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
        } else if type == 27 {
            // 上传过关证件
            let vc = YHUploadCertificateVC()
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
        } else if type == 31 {
            // 续签资料管理
            let vc = YHResinMaterialManageContainerVC()
            vc.orderId = orderId
            vc.batchId = stepId
            UIViewController.current?.navigationController?.pushViewController(vc)

        } else if type == 32 {
            // 续签文书管理
            let vc = YHResignDocumentManagementVC(orderId: orderId, id: stepId)
            UIViewController.current?.navigationController?.pushViewController(vc)
            
        } else if type == 33 {
            // 续签信息确认
            let vc = YHResignConfirmInfoListViewController()
            vc.orderId = orderId
            vc.stepId = stepId
            UIViewController.current?.navigationController?.pushViewController(vc)
            
        } else if type == 34 {
            // 在港递交预约
            let vc = YHResignAppointContainerViewController()
            vc.orderId = orderId
            vc.renewalId = stepId
            UIViewController.current?.navigationController?.pushViewController(vc)
        
        } else if type == 35 {
            // 查看续签结果
            let vc = YHLookResignResultViewController()
            vc.orderId = orderId
            vc.batchId = stepId
            UIViewController.current?.navigationController?.pushViewController(vc)
        } else if type == 36 {
            // 续签补件
            let vc = YHResignUploadDocListViewController()
            vc.orderId = orderId
            vc.batchId = stepId
            UIViewController.current?.navigationController?.pushViewController(vc)
        } else if type == 37 {
            // 在港签证缴费
            let vc = YHHKVisaRenewalPaymentVC(orderId: orderId, renewalId: stepId)
            UIViewController.current?.navigationController?.pushViewController(vc)
        } else if type == 38 {
            // 上传旅行证件
            let vc = YHResignUploadTravelCardListViewController()
            vc.orderId = orderId
            vc.batchId = stepId
            UIViewController.current?.navigationController?.pushViewController(vc)
        } else if type == 101 {
            // 身份续签指引
            gotoResignGuideVC()
        } else if type == 102 {
            // 我的续签方案
            gotoResignMethod(orderID: orderId, stepID: stepId)
        } else if type == 103 {
            // 添加在港记录
            gotoHKImmigrationRecordsVC(orderID: orderId)
        } else if type == 104 {
            // 续签证件管理
            gotoResignCertificateListVC(orderID: orderId)
        }
        
        /*
         高才部分
         */
        else if type == 201 {
            // 高才我的信息
//            let vc = YHGCWorkExperienceListViewController()
//            vc.orderId = orderId
//            UIViewController.current?.navigationController?.pushViewController(vc)
            
            YHAnalytics.track("APP_high_end_Document_Service_MyInformation")
            let vc = YHInformationPerfectListVC()
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
            
        } else if type == 202 {
            // 高才我的方案
            YHAnalytics.track("APP_high_end_Document_Service_MyPlan")
            let vc = YHGCMineSchemeViewController(orderId: orderId)
            UIViewController.current?.navigationController?.pushViewController(vc)
            
        } else if type == 203 {
            // 高才我的证件
            YHAnalytics.track("APP_high_end_Document_Service_MyCertificate")
            
            let vc = YHGCMineCertificateEntryViewController()
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
            
        } else if type == 204 {
            // 高才我的签字
            YHAnalytics.track("APP_high_end_Document_Service_MySignature")
            let vc = YHGCMySignatureListViewController()
            vc.orderId = orderId
            UIViewController.current?.navigationController?.pushViewController(vc)
        }
    }
}

extension YHServiceOrderListViewController {
    func loadData() {
        var array: [YHServiceCenterProgressModel] = []
        for item in arrDataForSeviceCenterProgress {
            if type == 0 {
                array.append(item)
            } else if item.status == type {
                array.append(item)
            } else if item.status == 4, type == 2 {
                array.append(item)
            }
        }
        self.arrDataForSeviceCenterProgress = array
        
        if self.homeTableView != nil {
            if self.arrDataForSeviceCenterProgress.count == 0 {
                self.homeTableView.tableFooterView = footView
                self.homeTableView.reloadData()
                if state == 3 && (type == 0 || type == 2) {
                    self.homeTableView.tableFooterView = UIView()
                    self.homeTableView.reloadData()
                }
            } else {
                self.homeTableView.tableFooterView = UIView()
                self.homeTableView.reloadData()
            }
        }
        if let block = self.block {
            if type == 3 {
                var oneflag = false
                var twoflag = false
                for item in self.arrDataForSeviceCenterProgress {
                    if item.type == 3 {
                        oneflag = isNeedShowRedPointFor(key: kMyScoreRedPointInfoKey, proVersion: item.pro_version)
                    }
                    if item.type == 4 {
                        twoflag = isNeedShowRedPointFor(key: kMyPlanRedPointInfoKey, proVersion: item.pro_version)
                    }
                }
                block(type, self.arrDataForSeviceCenterProgress.count, oneflag||twoflag)
            } else {
                block(type, self.arrDataForSeviceCenterProgress.count, false)
            }
        }
    }
    
    func setupUI() {
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        view.backgroundColor = UIColor(hex: 0xf4f6fa)
        homeTableView = {
            let tableView = YHGestureTableView(frame: .zero, style: .grouped)
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.showsHorizontalScrollIndicator = false
            tableView.showsVerticalScrollIndicator = false
            tableView.rowHeight = UITableView.automaticDimension
            tableView.estimatedRowHeight = 81.0
            tableView.dataSource = self
            tableView.delegate = self
            tableView.register(cellWithClass: YHServiceOrderProgressTableViewCell.self)
            return tableView
        }()
        view.addSubview(homeTableView)
        homeTableView.snp.makeConstraints { make in
            make.top.right.left.bottom.equalToSuperview()
        }
    }
    
    func isNeedShowRedPointFor(key: String, proVersion: Int) -> Bool {
        if key != kMyPlanRedPointInfoKey && key != kMyScoreRedPointInfoKey {
            return false
        }
        let targetKey = key + "_\(self.orderID)"
        if let dict = UserDefaults.standard.object(forKey: targetKey) as? [String: Any] {
            if !dict.keys.contains(kProVersionKey) ||  !dict.keys.contains(kClickKey) {
                return false
            }
            if let version = dict[kProVersionKey] as? Int {
                if version != proVersion { // 版本不一致一定显示红点
                    return true
                }
                // 版本一致但是未点击显示红点
                if let isClicked = dict[kClickKey] as? Bool, isClicked == false {
                    return true
                }
            }
            return false
        }
        // 本地没有红点记录存储则必展示红点
        return true
    }
    
    static func gotoResignGuideVC() {
        if let param = YHLoginManager.shared.userModel?.token, param.count>5 {
            var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/guide/identity"
//                        var url = "http://192.168.23.35:10300/" + "superAppBridge.html#/guide/identity"
            url = url + "?param=" + YHLoginManager.shared.h5Token
            let vc = YHH5WebViewVC()
            vc.title = "身份续签指引"
            vc.navTitle = "身份续签指引"
            vc.url = url
            vc.isFullScreenFlag = false
            vc.isNeedRefreshDataFlag = true
            vc.isSupportWebviewInterBackFlag = true
            UIViewController.current?.navigationController?.pushViewController(vc)
        }
    }
    
    static func gotoResignMethod(orderID: Int, stepID: Int) {
        if let param = YHLoginManager.shared.userModel?.token, param.count>5 {
            printLog(param)
            var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/report/program"
//                        var url = "http://192.168.23.75:10301/" + "superAppBridge.html#/report/program"
            
            url = url + "?param=" + YHLoginManager.shared.h5Token + "&batchID=\(stepID)" + "&order_id=\(orderID)"
            let vc = YHH5WebViewVC()
            vc.title = "我的续签方案"
            vc.navTitle = "我的续签方案"
            vc.url = url
            vc.isSupportWebviewInterBackFlag = true
            UIViewController.current?.navigationController?.pushViewController(vc)
        }
    }
    
    static func gotoHKImmigrationRecordsVC(orderID: Int) {
        let vc = YHHKImmigrationRecordsVC(orderId: orderID)
        UIViewController.current?.navigationController?.pushViewController(vc)
    }
    
    static func gotoResignCertificateListVC(orderID: Int) {
        let vc = YHResignCertificateListViewController()
        vc.orderId = orderID
        UIViewController.current?.navigationController?.pushViewController(vc)
    }
}

extension YHServiceOrderListViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.arrDataForSeviceCenterProgress.count
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if orderType == 3 {
            return 42.fix + 20
        }
        if state == 3 && (type == 0 || type == 2) {
            return 104
        } else {
            return kMargin
        }
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if orderType == 3 {
            let view = YHServiceOrderInIncubationSectionView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 42.fix + 20))
            view.block = { [weak self] _ in
                guard let self = self else { return }
                YHServiceOrderInIncubationView.show(false) {
                    
                }
            }
            return view
        }
        if state == 3 && (type == 0 || type == 2) {
            let view = YHServiceStepThreeSectionView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 104))
            view.block = { [weak self] tag in
                guard let self = self else { return }
                if tag == 1 {
                    // 身份续签指引
                    printLog("身份续签指引")
                    YHServiceOrderListViewController.gotoResignGuideVC()
                    
                } else if tag == 2 {
                    // 我的续签方案
                    printLog("续签方案")
                    YHServiceOrderListViewController.gotoResignMethod(orderID: orderID, stepID: stepID)
                } else if tag == 3 {
                    // 添加在港记录
                    YHServiceOrderListViewController.gotoHKImmigrationRecordsVC(orderID: orderID)
                } else if tag == 4 {
                    // 续签证件管理
                    YHServiceOrderListViewController.gotoResignCertificateListVC(orderID: orderID)
                }
            }
            return view
        } else {
            let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: kMargin))
            return view
        }
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let arr = self.arrDataForSeviceCenterProgress
        if  0 <= indexPath.row, indexPath.row < arr.count {
            let model = arr[indexPath.row]
            if model.type == 27 || model.type == 32 || model.type == 31 || model.type == 34 {
                return 162
            }
            return 144
        }
        return 144
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell0 = tableView.dequeueReusableCell(withClass: YHServiceOrderProgressTableViewCell.self)
        cell0.selectionStyle = .none

        if indexPath.row < self.arrDataForSeviceCenterProgress.count {
            cell0.set(dataModel: self.arrDataForSeviceCenterProgress[indexPath.row], orderId: orderID)
        }
        return cell0
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.arrDataForSeviceCenterProgress[indexPath.row]
        if model.status == 1 || model.status == 4 {
            return
        } else {
            YHServiceOrderListViewController.jumpToMessageController(type: model.type, orderId: orderID, stepID, productType: productInfoMode.product_type)
            if model.type == 3 {
                // 我的评分
                handleRedPointFor(key: kMyScoreRedPointInfoKey, model: model)
            } else if model.type == 4 { // 方案
                // 我的方案
                handleRedPointFor(key: kMyPlanRedPointInfoKey, model: model)
            }
        }
    }
    
    func handleRedPointFor(key: String, model: YHServiceCenterProgressModel) {
        if key != kMyPlanRedPointInfoKey && key != kMyScoreRedPointInfoKey {
            return
        }
        if model.type != 3 && model.type != 4 { // 只有我的评分和我的方案进行红点处理
            return
        }
        
        if model.status != 3 { // 只有已完成状态才进行红点处理
            return
        }
        
        let dict: [String: Any] = [kProVersionKey: model.pro_version,
                                  kOrderIdKey: orderID,
                                  kClickKey: true]
        let targetKey = key + "_\(orderID)"
        UserDefaults.standard.set(dict, forKey: targetKey)
        UserDefaults.standard.synchronize()
    }
}

extension YHServiceOrderListViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

extension YHServiceOrderListViewController: UIScrollViewDelegate {
    // 控制滑动交互
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let scrollViewSet: CGFloat = scrollView.contentOffset.y
        if vcCanScroll == false {// 不能滚动时
            scrollView.contentOffset = CGPoint(x: 0, y: 0)
        } else {
            if scrollViewSet <= 0 {
                scrollView.contentOffset = CGPoint(x: 0, y: 0)
                vcCanScroll = false
                NotificationCenter.default.post(name: Notification.Name(rawValue: "leaveTop0"), object: nil)
            } else {
                scrollView.contentOffset = CGPoint(x: 0, y: scrollViewSet)
            }
        }
    }
}

extension YHServiceOrderListViewController {
    @objc func beginDragging() {
        homeTableView.isScrollEnabled = false
        vcCanScroll = false
    }
    
    @objc func endDragging() {
        homeTableView.isScrollEnabled = true
        vcCanScroll = true
    }
}
