//
//  YHServiceCenterViewController.swift
//  galaxy
//
//  Created by EDY on 2024/9/10.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView
import AttributedString

class YHServiceCenterViewController: YHBaseViewController {
    private lazy var princleVM: YHPrincleViewModel = {
        let vm = YHPrincleViewModel()
        return vm
    }()
    
    private let serviceCenterMainReqVM: YHServiceCenterViewModel = YHServiceCenterViewModel()
    
    var titleLabel: UIButton!
    var orderButton: UIButton!
    var headView = YHServiceCenterStepThreeTableHeadView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 100))
    var orderId: Int = 0
    var mobile: String = ""
    var model: YHContactItemModel = YHContactItemModel()
    var oldModel: YHContactItemModel = YHContactItemModel()
    var doneCount: Int = 0
    var canScroll: Bool = true
    var arrDataForSeviceCenterProgress: [YHServiceCenterProgressModel] = []
    var state: Int = 0
    var isCanSelectStep: Bool = false
    var stepID: Int = 0
    var headIndex = 0
    private weak var tipsView: YHServiceOrderTipsView?
    private var needShowYHManagerGuideView = false
    
    private lazy var topBkg: UIView = {
        let imagV = UIImageView()
        imagV.image = UIImage(named: "service_center_head_bkg4")
        imagV.contentMode = .scaleAspectFill
        imagV.isUserInteractionEnabled = true
        return imagV
        
    }()
    
    lazy var navBar: UIView = {
        let bar = UIView()
        let backBtn = UIButton()
        backBtn.setImage(UIImage(named: "back_icon"), for: .normal)
        backBtn.addTarget(self, action: #selector(didBackBtnClicked), for: .touchUpInside)
        backBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        bar.addSubview(backBtn)
        backBtn.snp.makeConstraints { make in
            make.width.height.equalTo(21)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(16)
        }
        return bar
    }()
    
    private let noDataView: YHServiceNoOrderView = {
        let view = YHServiceNoOrderView()
        view.isHidden = true
        return view
    }()
    
    var myCellHeight: CGFloat {
        get {
            return view.bounds.size.height - 90 - k_Height_TabBar
        }
    }
    
    var myDefaultIndex: Int = 0 {
        didSet {
            DispatchQueue.global().asyncAfter(wallDeadline: .now() ) {[weak self] in
                DispatchQueue.main.async {
//                    self?.cellView.myDefaultNavItemIndex = self?.myDefaultIndex ?? 0
                }
            }
        }
    }
    
    lazy var cellView: YHServerCenterHoldViewController = {
        let ttt = YHServerCenterHoldViewController()
//        ttt.myDefaultNavItemIndex = self.myDefaultIndex
        return ttt
    }()
    
    var homeTableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsHorizontalScrollIndicator = false
        tableView.showsVerticalScrollIndicator = false
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        addListView()

        noDataView.clickBackBtnClickBlock = {[weak self] in
            guard self != nil else { return }
            
            // 跳转测评页
            let vc = YHH5WebViewVC()
            vc.url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/evaluation?channel=APP-zrll"
            vc.isShowRightShareItemFlag = true
            self?.navigationController?.pushViewController(vc)
        }
        noDataView.clickShowBtnClickBlock = {
            YHServiceOrderAlertView.show()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(logoutSuccess), name: YhConstant.YhNotification.didLogoutSuccessNotifiction, object: nil)
        noDataView.isHidden = false
        homeTableView.isHidden = true
        
        NotificationCenter.default.addObserver(self, selector: #selector(leaveTopOp), name: Notification.Name(rawValue: "leaveTop0"), object: nil)
        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)
        
        NotificationCenter.default.addObserver(self, selector: #selector(didJumpToServiceProgess(_:)), name: YhConstant.YhNotification.didJumpToServiceProgressNotification, object: nil)
    }
    
    private func goToServiceProgressVC() {
        let vc = YHOrderDetailViewController()
        vc.model = oldModel
        vc.backDate = { [weak self] model in
            guard let self = self else { return }
            self.model = model
            self.state = 0
            self.headIndex = 0
            self.isCanSelectStep = false
        }
        self.navigationController?.pushViewController(vc)
    }
    
    @objc func didJumpToServiceProgess(_ notification: Notification) {
        if let userInfo = notification.userInfo, let value = userInfo["value"] as? String {
            var currentModel = YHContactItemModel()
            currentModel.id = value.intValue()
            self.model = currentModel
            self.state = 0
            self.headIndex = 0
            self.isCanSelectStep = false
            self.loadData()
        } else {
            /// 服务进度
            goToServiceProgressVC()
        }
    }
    
    @objc func logoutSuccess() {
        self.model = YHContactItemModel()
        self.oldModel = YHContactItemModel()
        self.state = 0
        self.headIndex = 0
        self.isCanSelectStep = false
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
        showAlert()
    }
    
    private func showAlert() {
        guard YHLoginManager.shared.isLogin() else {
            return
        }
        princleVM.getPrincleStatus { [weak self] success, _ in
            if success {
                guard let self = self else {
                    return
                }
                guard let model = self.princleVM.alertStatusModel else {
                    return
                }
                if model.type == 20 {
                    if UserDefaults.standard.string(forKey: "service_tip_show") == nil || tipsView?.isOn == true {
                        needShowYHManagerGuideView = true
                    } else {
                        self.showYHManagerGuideView(self.navigationController)
                    }
                }
            }
        }
    }
}

extension YHServiceCenterViewController {
    func loadData() {
        if model.id != -1 {
            noDataView.isHidden = true
            homeTableView.isHidden = false
            if self.navigationController?.viewControllers.count != 2 && self.navigationController?.viewControllers.count != 1 {
                orderButton.isHidden = true
            }
            orderId = model.id
            mobile = model.mobile
            UserDefaults.standard.set(orderId, forKey: "orderIdForPreview")
            UserDefaults.standard.synchronize()
            getStep()
        } else {
            serviceCenterMainReqVM.getContactList {[weak self] success, error in
                guard let self = self else { return }
                if success == true {
                    
                } else {
                    YHHUD.flash(message: error?.errorMsg ?? "请求出错")
                }
                self.handleRightUI()
            }
        }
    }
    
    @objc func didBackBtnClicked() {
        self.navigationController?.popViewController(animated: true)
    }
    
    func setupUI() {
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        view.backgroundColor = .white
        view.addSubview(topBkg)
        
        topBkg.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(90)
        }
        
        titleLabel = {
            let button = UIButton(type: .custom)
            button.setTitle("我的服务     ", for: .normal)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 21)
            button.setTitleColor(UIColor.mainTextColor, for: .normal)
            button.setImage(UIImage(named: "service_center_select_step"), for: .normal)
            button.addTarget(self, action: #selector(selectTimeStep), for: .touchUpInside)
            return button
        }()
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(53)
            make.left.equalTo(20)
            make.height.equalTo(29)
            make.width.equalTo(18 + 126)
        }
        titleLabel.iconInRight(with: 8)
        
        view.addSubview(navBar)
        navBar.snp.makeConstraints { make in
            make.left.equalToSuperview()
//            make.top.equalToSuperview().offset(k_Height_statusBar())
            make.height.equalTo(k_Height_NavContentBar)
            make.width.equalTo(47)
            make.centerY.equalTo(titleLabel.snp.centerY)
        }
        orderButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "service_center_more"), for: .normal)
            button.addTarget(self, action: #selector(pushOrderView), for: .touchUpInside)
            return button
        }()
        view.addSubview(orderButton)
        orderButton.snp.makeConstraints { make in
            make.right.equalTo(-20)
            make.centerY.equalTo(titleLabel.snp.centerY)
            make.height.equalTo(24)
            make.width.equalTo(24)
        }
        
        homeTableView.delegate = self
        homeTableView.dataSource = self
        view.addSubview(homeTableView)
        homeTableView.snp.makeConstraints { make in
            make.top.equalTo(90)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-k_Height_TabBar)
        }
        
        if self.navigationController?.viewControllers.count != 2 && self.navigationController?.viewControllers.count != 1 {
            titleLabel.setTitle("订单详情", for: .normal)
            orderButton.isHidden = true
            titleLabel.snp.remakeConstraints { make in
                make.top.equalTo(53)
                make.left.equalTo(47)
                make.height.equalTo(29)
                make.width.equalTo(18 + 126)
            }
        } else {
            navBar.isHidden = true
        }
        
    }
    
    @objc func pushOrderView() {
        var flag = false
        if self.state == 1 {
            flag = true
        }
        YHServiceMoreAlertView.show(flag) {[weak self] index in
            guard let self = self else { return }
            if index == 1 {
                self.goToServiceProgressVC()
            } else {
                if self.state == 1 {
                    let view = YHServiceOrderGuideTipsView.sheetView(serviceCenterMainReqVM.hasTTPS, model.product_type)
                    view.show()
                }
                if self.state == 2 {
                    let view = YHOffivialApprovalGuildLineCheckView.sheetView()
                    view.show()
                }
            }
        }
        
    }
    
    @objc func selectTimeStep() {
        if !isCanSelectStep {
            return
        }
        var flag = true
        if self.state == 3 {
           flag = false
        }
        YHServiceStepAlertView.show(flag) {[weak self] index in
            guard let self = self else { return }
            if index == 1 {
                self.state = 3
            } else {
                self.state = 2
            }
            
            if self.state == 2 {
                self.arrDataForSeviceCenterProgress = self.serviceCenterMainReqVM.mainModel.certificateSection.list
                self.homeTableView.tableHeaderView = UIView()
                if self.model.product_type == 1 {
                    self.titleLabel.setTitle("优才审批阶段", for: .normal)
                } else {
                    self.titleLabel.setTitle("高才审批阶段", for: .normal)
                }
                self.titleLabel.setImage(UIImage(named: "service_center_select_step"), for: .normal)
            }
            if self.state == 3 {
                guard headIndex < self.serviceCenterMainReqVM.mainModel.renewalSection.list.count else { return }
                self.arrDataForSeviceCenterProgress = self.serviceCenterMainReqVM.mainModel.renewalSection.list[headIndex].list
                self.stepID = self.serviceCenterMainReqVM.mainModel.renewalSection.list[headIndex].id
                self.homeTableView.tableHeaderView = headView
                self.headView.block = {[weak self] stepIndex, id, array in
                    guard let self = self else { return }
                    self.headIndex = stepIndex
                    self.stepID = id
                    self.arrDataForSeviceCenterProgress = array
                    self.homeTableView.reloadData()
                }
                self.headView.selectIndex = self.headIndex
                self.headView.dataSource = self.serviceCenterMainReqVM.mainModel.renewalSection.list
                if self.model.product_type == 1 {
                    self.titleLabel.setTitle("优才续签阶段", for: .normal)
                } else {
                    self.titleLabel.setTitle("高才续签阶段", for: .normal)
                }
                self.titleLabel.setImage(UIImage(named: "service_center_select_step"), for: .normal)
                self.isCanSelectStep = true
            }
            self.homeTableView.reloadData()
        }
    }
}

extension YHServiceCenterViewController {
    private func handleRightUI() {
        if serviceCenterMainReqVM.arrContactList.isEmpty {
            noDataView.isHidden = false
            homeTableView.isHidden = true
            titleLabel.setImage(UIImage(named: ""), for: .normal)
        } else {
            guard let model = serviceCenterMainReqVM.arrContactList.first else {
                return
            }
            noDataView.isHidden = true
            homeTableView.isHidden = false
            if self.navigationController?.viewControllers.count != 2 && self.navigationController?.viewControllers.count != 1 {
                orderButton.isHidden = true
            }
            orderId = model.id
            mobile = model.mobile
            self.model = model
            self.oldModel = model
            UserDefaults.standard.set(orderId, forKey: "orderIdForPreview")
            UserDefaults.standard.synchronize()
            getStep()
        }
    }
    
    func getStep() {
        serviceCenterMainReqVM.getServiceMainData(orderId: orderId) {[weak self] _, _ in
            guard let self = self else { return }
            self.model.product_type = self.serviceCenterMainReqVM.mainModel.category_type
            if self.serviceCenterMainReqVM.mainModel.stage == 3 {
                self.isCanSelectStep = true
            }
            if self.state == 0 {
                self.state = self.serviceCenterMainReqVM.mainModel.stage
            }
            if self.state == 1 {
                self.arrDataForSeviceCenterProgress = self.serviceCenterMainReqVM.mainModel.applySection.list
                self.homeTableView.tableHeaderView = UIView()
                if self.model.product_type == 1 {
                    self.titleLabel.setTitle("优才申请阶段", for: .normal)
                } else {
                    self.titleLabel.setTitle("高才申请阶段", for: .normal)
                }
                self.titleLabel.setImage(UIImage(named: ""), for: .normal)
            }
            if self.state == 2 {
                self.arrDataForSeviceCenterProgress = self.serviceCenterMainReqVM.mainModel.certificateSection.list
                self.homeTableView.tableHeaderView = UIView()
                if self.model.product_type == 1 {
                    self.titleLabel.setTitle("优才审批阶段", for: .normal)
                } else {
                    self.titleLabel.setTitle("高才审批阶段", for: .normal)
                }
                if isCanSelectStep {
                    self.titleLabel.setImage(UIImage(named: "service_center_select_step"), for: .normal)
                } else {
                    self.titleLabel.setImage(UIImage(named: ""), for: .normal)
                }
            }
            if self.state == 3 {
                if self.serviceCenterMainReqVM.mainModel.renewalSection.list.count > headIndex {
                    self.arrDataForSeviceCenterProgress = self.serviceCenterMainReqVM.mainModel.renewalSection.list[headIndex].list
                    self.stepID = self.serviceCenterMainReqVM.mainModel.renewalSection.list[headIndex].id
                    self.homeTableView.tableHeaderView = headView
                    self.headView.block = {[weak self] stepIndex, id, array in
                        guard let self = self else { return }
                        self.headIndex = stepIndex
                        self.stepID = id
                        self.arrDataForSeviceCenterProgress = array
                        self.homeTableView.reloadData()
                    }
                    self.headView.selectIndex = self.headIndex
                    self.headView.dataSource = self.serviceCenterMainReqVM.mainModel.renewalSection.list
                    if self.model.product_type == 1 {
                        self.titleLabel.setTitle("优才续签阶段", for: .normal)
                    } else {
                        self.titleLabel.setTitle("高才续签阶段", for: .normal)
                    }
                    self.titleLabel.setImage(UIImage(named: "service_center_select_step"), for: .normal)
                }
            }
            
            if self.state == 4 {
                if self.serviceCenterMainReqVM.mainModel.permanentSection.list.count > headIndex {
                    self.arrDataForSeviceCenterProgress = self.serviceCenterMainReqVM.mainModel.permanentSection.list[headIndex].list
                    self.stepID = self.serviceCenterMainReqVM.mainModel.permanentSection.list[headIndex].id
                    self.homeTableView.tableHeaderView = headView
                    self.headView.block = {[weak self] stepIndex, id, array in
                        guard let self = self else { return }
                        self.headIndex = stepIndex
                        self.stepID = id
                        self.arrDataForSeviceCenterProgress = array
                        self.homeTableView.reloadData()
                    }
                    self.headView.selectIndex = self.headIndex
                    self.headView.dataSource = self.serviceCenterMainReqVM.mainModel.permanentSection.list
                    self.titleLabel.setTitle("续签阶段", for: .normal)
                    self.titleLabel.setImage(UIImage(named: ""), for: .normal)
                }
            }
            self.homeTableView.reloadData()
            // 首次显示指引
            if UserDefaults.standard.string(forKey: "service_tip_show") != nil {
            } else {
                tipsView = YHServiceOrderTipsView.show()
                tipsView?.dismissEvent = { [weak self] in
                    guard let self = self else {
                        return
                    }
                    
                    if self.needShowYHManagerGuideView == true {
                        self.needShowYHManagerGuideView = false
                        self.showYHManagerGuideView(self.navigationController)
                    }
                }
            }
        }
    }
    
    func addListView() {
        view.addSubview(noDataView)
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(236)
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(265)
        }
    }
}

extension YHServiceCenterViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.001))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.001))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return myCellHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cellView.view.frame = CGRect(x: 0, y: 0, width: cell.contentView.bounds.size.width, height: myCellHeight)
        cell.contentView.addSubview(cellView.view)
        cellView.view.snp.makeConstraints { make in
            make.edges.equalTo(0)
        }
        cellView.arrDataForSeviceCenterProgress = arrDataForSeviceCenterProgress
        cellView.orderType = serviceCenterMainReqVM.mainModel.status
        cellView.mobile = model.mobile
        cellView.state = state
        cellView.stepID = stepID
        cellView.productInfoMode = model
        cellView.orderId = orderId
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

extension YHServiceCenterViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let bottomCellOffset: CGFloat = homeTableView.rect(forSection: 0).origin.y
        if scrollView.contentOffset.y >= bottomCellOffset {
            scrollView.contentOffset = CGPoint(x: 0, y: bottomCellOffset)
            if canScroll == true {
//                canScroll = false
//                //传递参数到 子VC
//                cellView.canScroll = true
            }
            
            canScroll = false
            // 传递参数到 子VC
            cellView.canScroll = true
        } else {
            if canScroll == false {
                scrollView.contentOffset = CGPoint(x: 0, y: bottomCellOffset)
            }
        }
        self.homeTableView.showsVerticalScrollIndicator = false
    }
}

extension YHServiceCenterViewController {
    @objc func leaveTopOp() {
        canScroll = true
    }
    
    @objc func beginDragging() {
        homeTableView.isScrollEnabled = false
        canScroll = false
    }
    
    @objc func endDragging() {
        homeTableView.isScrollEnabled = true
        canScroll = true
    }
}

extension YHServiceCenterViewController {
    // MARK: - 跳银河管家
    
    private func showYHManagerGuideView(_ navigationController: UINavigationController?) {
        if YHUatHelper.shared.getUatModuleStatusBy(module: .QiYu_Service) != 1 {
            printLog("非目标用户")
            return
        }
        if let key = YHButlerServiceManager.shared.guideWindowShowedKey, YHButlerServiceManager.shared.didShowWindowDict[key] == true {
            return
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
            if let key = YHButlerServiceManager.shared.guideWindowShowedKey {
                YHButlerServiceManager.shared.didShowWindowDict[key] = true
            }
            let view = YHConversationGuideView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
            view.checkButtonEvent = { [weak self] in
                guard let self = self else {
                    return
                }
                self.princleVM.postAlertStatus(20) { _, _ in
                }
                self.gotoYinHeManager(navigationController)
            }
            view.show()
        }
    }
    
    private func gotoYinHeManager(_ navigationController: UINavigationController?) {
        guard let userId = YHLoginManager.shared.userModel?.id, userId.count > 0 else {
            return
        }
        // YHAnalytics.track("APP_HomeTab_IntelligentAssistant")
        YHHUD.show(.progress(message: "加载中..."))
        YHButlerServiceManager.shared.gotoButlerServiceSessionVC(navigationController: navigationController, completion: { _ in
            YHHUD.hide()
        })
    }
}
