//
//  YHServiceCenterMainViewController.swift
//  galaxy
//
//  Created by EDY on 2023/12/20.
//

import UIKit
import JXSegmentedView
import AttributedString

//服务中心
class YHServiceCenterMainViewController: YHBaseViewController {
    
    private let serviceCenterMainReqVM : YHServiceCenterMainViewModel = YHServiceCenterMainViewModel()
    
    var titleLabel: UILabel!
    var nameBgImageView: UIImageView!
    var nameLabel: UILabel!
    var orderButton: UIButton!
    var orderId: Int = 0
    var mobile: String = ""
    var model: YHContactItemModel = YHContactItemModel()
    var doneCount: Int = 0
    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 controllerOne: YHServiceOrderListView = YHServiceOrderListView()
    var controllerTwo: YHServiceOrderListView = YHServiceOrderListView()
    var controllerThree: YHServiceOrderListView = YHServiceOrderListView()
    var controllerFour: YHServiceOrderListView = YHServiceOrderListView()
    var arrItemTitles = ["全部", "待开始", "进行中", "已完成"]
    var arrItemVCs: [YHServiceOrderListView] = []
    var segmentedView : JXSegmentedView = JXSegmentedView(frame: CGRect(x: 0, y: k_Height_safeAreaInsetsTop(), width: KScreenWidth, height: 48))
    lazy var segmentedDataSource: JXSegmentedDotDataSource = {
        let dataSource = JXSegmentedDotDataSource()
        dataSource.isTitleColorGradientEnabled = true
        dataSource.titles = arrItemTitles
        
        dataSource.titleNormalFont = UIFont.PFSC_M(ofSize: 14)
        dataSource.titleNormalColor = .labelTextColor2
        
        dataSource.titleSelectedFont = UIFont.PFSC_M(ofSize: 14)
        dataSource.titleSelectedColor = .mainTextColor
        
        dataSource.isItemSpacingAverageEnabled = false
        dataSource.itemWidth = JXSegmentedViewAutomaticDimension
        dataSource.itemSpacing = 16
        dataSource.dotStates = [false, false, false, false]
        dataSource.dotSize = CGSize(width: 6, height: 6)
        return dataSource
    }()
    
    //分类title 所对应的VC
    lazy var listContainerView: JXSegmentedListContainerView! = {
        return JXSegmentedListContainerView(dataSource: self, type: .scrollView)
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        addListView()

        noDataView.clickBackBtnClickBlock = {[weak self] in
            guard self != nil else { return }
            let vc = YHHomeWebViewController()
            vc.vcTitle = "香港身份测评码"
            vc.showSavePicBottomFlag = true
            vc.url = "https://cdn-public.galaxy-immi.com/app/cepingma.png"
            self?.navigationController?.pushViewController(vc)
        }
        noDataView.clickShowBtnClickBlock = {
            YHServiceOrderAlertView.show()
        }
        
        
        noDataView.isHidden = false
        nameBgImageView.isHidden = true
        segmentedView.isHidden = true
        listContainerView.isHidden = true
        orderButton.isHidden = true
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
}

extension YHServiceCenterMainViewController {
    func loadData() {
        if model.id != -1 && self.navigationController?.viewControllers.count != 1 {
            noDataView.isHidden = true
            nameBgImageView.isHidden = false
            segmentedView.isHidden = false
            listContainerView.isHidden = false
            orderButton.isHidden = false
            if self.navigationController?.viewControllers.count != 1 {
                orderButton.isHidden = true
            }
            orderId = model.id
            mobile = model.mobile
            UserDefaults.standard.set(orderId, forKey: "orderIdForPreview")
            UserDefaults.standard.synchronize()
            for i in 0..<arrItemTitles.count {
                let vc = arrItemVCs[i] as YHServiceOrderListView
                vc.type = i
                if i == 1 {
                    vc.type = 2
                }
                if i == 2 {
                    vc.type = 1
                }
                vc.orderID = orderId
                vc.mobile = mobile
                vc.loadData()
            }
            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(202)
        }
        
        titleLabel = {
            let label = UILabel()
            label.text = "我的服务"
            label.font = UIFont.PFSC_M(ofSize: 21)
            label.textColor = UIColor.mainTextColor
            return label
        }()
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(53)
            make.left.equalTo(20)
            make.height.equalTo(29)
            make.right.equalTo(-20)
        }
        
        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.setTitle("我的订单", for: .normal)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
            button.setTitleColor(UIColor(hex: 0x94a3b8), 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(20)
            make.width.equalTo(56)
        }
        
        if self.navigationController?.viewControllers.count != 1 {
            titleLabel.textAlignment = .center
            titleLabel.text = "订单详情"
            orderButton.isHidden = true
        } else {
            navBar.isHidden = true
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(goToServiceTabFromFileListPage), name: YhConstant.YhNotification.didClickFileListBackToServiceTabNotifiction, object: nil)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        nameBgImageView.snp.remakeConstraints { make in
            make.top.equalTo(92)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalTo(nameLabel.snp.bottom).offset(11)
        }
        segmentedView.snp.remakeConstraints { make in
            make.right.equalTo(-4)
            make.left.equalTo(4)
            make.top.equalTo(nameBgImageView.snp.bottom).offset(14)
            make.height.equalTo(48)
        }
        if self.navigationController?.viewControllers.count != 1 {
            listContainerView.snp.remakeConstraints { make in
                make.right.left.equalToSuperview()
                make.top.equalTo(segmentedView.snp.bottom)
                make.bottom.equalToSuperview()
            }
        } else {
            listContainerView.snp.remakeConstraints { make in
                make.right.left.equalToSuperview()
                make.top.equalTo(segmentedView.snp.bottom)
                make.bottom.equalTo(-k_Height_TabBar)
            }
        }
    }
    
    @objc func pushOrderView() {
        let vc = YHOrderDetailViewController()
        vc.model = model
        self.navigationController?.pushViewController(vc)
    }
}

extension YHServiceCenterMainViewController: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
//        NotificationCenter.default.post(name:  Notification.Name(rawValue: "scrollViewDidEndDragging"), object: nil)
    }

    /// 正在滚动中的回调
    ///
    /// - Parameters:
    ///   - segmentedView: JXSegmentedView
    ///   - leftIndex: 正在滚动中，相对位置处于左边的index
    ///   - rightIndex: 正在滚动中，相对位置处于右边的index
    ///   - percent: 从左往右计算的百分比
    func segmentedView(_ segmentedView: JXSegmentedView, scrollingFrom leftIndex: Int, to rightIndex: Int, percent: CGFloat) {
//        NotificationCenter.default.post(name:  Notification.Name(rawValue: "scrollViewWillBeginDragging"), object: nil)
    }
}

extension YHServiceCenterMainViewController: JXSegmentedListContainerViewDataSource {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        if let titleDataSource = segmentedView.dataSource as? JXSegmentedBaseDataSource {
            return titleDataSource.dataSource.count
        }
        return 0
    }

    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        return arrItemVCs[index]
    }
}


extension YHServiceCenterMainViewController {
    private func handleRightUI() {
        if serviceCenterMainReqVM.arrContactList.isEmpty {
            noDataView.isHidden = false
            nameBgImageView.isHidden = true
            segmentedView.isHidden = true
            listContainerView.isHidden = true
            orderButton.isHidden = true
        } else {
            guard let model = serviceCenterMainReqVM.arrContactList.first else {
                return
            }
            noDataView.isHidden = true
            nameBgImageView.isHidden = false
            segmentedView.isHidden = false
            listContainerView.isHidden = false
            orderButton.isHidden = false
            if self.navigationController?.viewControllers.count != 1 {
                orderButton.isHidden = true
            }
            orderId = model.id
            mobile = model.mobile
            self.model = model
            UserDefaults.standard.set(orderId, forKey: "orderIdForPreview")
            UserDefaults.standard.synchronize()
            for i in 0..<arrItemTitles.count {
                let vc = arrItemVCs[i] as YHServiceOrderListView
                vc.type = i
                if i == 1 {
                    vc.type = 2
                }
                if i == 2 {
                    vc.type = 1
                }
                vc.orderID = orderId
                vc.mobile = mobile
                vc.loadData()
            }
            getStep()
        }
    }
    
    func getStep() {
        serviceCenterMainReqVM.getPersonInfoFillStep(params: ["orderId":orderId]) {[weak self] success, error in
            guard let self = self else { return }
            var name = ""
            if let applicant = self.serviceCenterMainReqVM.informationFillStepModel {
                if applicant.applicantName.isEmpty {
                    name = "尊敬的客户"
                } else {
                    name = applicant.applicantName
                    if applicant.sex == 1 {
                        name = "尊敬的" + name + "先生"
                    } else if applicant.sex == 2 {
                        name = "尊敬的" + name + "女士"
                    } else {
                        
                    }
                }
            }
            if doneCount == 6 {
                let a: ASAttributedString = .init("您好，\(name)，您的资料已全部准备完成，已进入", .font(UIFont.PFSC_R(ofSize: 13)),.foreground(UIColor.mainTextColor))
                let aa: ASAttributedString = .init(NSAttributedString(string: "全套资料审核"), .font(UIFont.PFSC_M(ofSize: 13)),.foreground(UIColor.brandMainColor))
                let aaa: ASAttributedString = .init("阶段，审核没问题会安排递交入境处哦~", .font(UIFont.PFSC_R(ofSize: 13)),.foreground(UIColor.mainTextColor))
                self.nameLabel.attributed.text = a + aa + aaa
            } else {
                let a: ASAttributedString = .init("您好，\(name)，您现处于", .font(UIFont.PFSC_R(ofSize: 13)),.foreground(UIColor.mainTextColor))
                let aa: ASAttributedString = .init(NSAttributedString(string: "信息提交"), .font(UIFont.PFSC_M(ofSize: 13)),.foreground(UIColor.brandMainColor))
                let aaa: ASAttributedString = .init("阶段，让我们一起共同完成您的身份申请之旅吧~", .font(UIFont.PFSC_R(ofSize: 13)),.foreground(UIColor.mainTextColor))
                self.nameLabel.attributed.text = a + aa + aaa
            }
        }
    }
    
    func addListView() {
        nameBgImageView = {
            let view = UIImageView()
            view.image = UIImage(named: "service_name_bg")?.resizableImage(withCapInsets: UIEdgeInsets(top: 21, left: 68, bottom: 11, right: 14), resizingMode: .stretch)
            return view
        }()
        view.addSubview(nameBgImageView)
        nameBgImageView.snp.makeConstraints { make in
            make.top.equalTo(92)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(68)
        }
        
        nameLabel = {
            let label = UILabel()
            label.text = "您好，张先生，您当前处于身份申请阶段"
            label.font = UIFont.PFSC_M(ofSize: 12)
            label.textColor = UIColor.brandMainColor
            label.numberOfLines = 0
            return label
        }()
        nameBgImageView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.top.equalTo(21)
            make.left.equalTo(14)
            make.right.equalTo(-14)
        }
        
        view.addSubview(noDataView)
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(236)
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(265)
        }
        
        controllerOne.type = 0
        controllerOne.orderID = orderId
        controllerOne.block = {[weak self] type, count, flag in
            guard let self = self else { return }
            arrItemTitles[0] = "全部(\(count))"
            self.updata(flag: flag, type: 0)
        }
        controllerTwo.type = 2
        controllerTwo.orderID = orderId
        controllerTwo.block = {[weak self] type, count, flag in
            guard let self = self else { return }
            arrItemTitles[1] = "进行中(\(count))"
            self.updata(flag: flag, type: 2)
        }
        controllerThree.type = 1
        controllerThree.orderID = orderId
        controllerThree.block = {[weak self] type, count, flag in
            guard let self = self else { return }
            arrItemTitles[2] = "待开始(\(count))"
            self.updata(flag: flag, type: 1)
        }
        controllerFour.type = 3
        controllerFour.orderID = orderId
        controllerFour.block = {[weak self] type, count, flag in
            guard let self = self else { return }
            arrItemTitles[3] = "已完成(\(count))"
            self.updata(flag: flag, type: 3)
            doneCount = count
            self.getStep()
        }
        arrItemVCs.append(controllerOne)
        arrItemVCs.append(controllerTwo)
        arrItemVCs.append(controllerThree)
        arrItemVCs.append(controllerFour)
        
        //segmentedViewDataSource一定要通过属性强持有！！！！！！！！！
        segmentedView.collectionView.backgroundColor = .white
        view.addSubview(segmentedView)

        segmentedView.listContainer = listContainerView
        view.addSubview(listContainerView)
        
        
        //分类Title
        segmentedView.dataSource = segmentedDataSource
        segmentedView.delegate = self
        
        //配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 16
        indicator.indicatorColor = UIColor.brandMainColor
        indicator.indicatorCornerRadius = 0
        segmentedView.indicators = [indicator]
        segmentedView.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)
        
        segmentedView.defaultSelectedIndex = 1
    }
    
    func updata(flag: Bool, type: Int){
        DispatchQueue.main.async {
            self.segmentedDataSource.titles = self.arrItemTitles
            if type == 3 {
                self.segmentedDataSource.dotStates = [false,false,false,flag]
            }
            self.segmentedView.reloadData()
        }
    }
}

extension YHServiceCenterMainViewController {
    
    @objc func goToServiceTabFromFileListPage() {
        
        // 进行中有数据则切换到进行中，进行中无数据则切换到全部
        YHHUD.show(.progress(message: "加载中..."))
        self.serviceCenterMainReqVM.getServiceCenterProgressList(self.orderId, 2) {
            [weak self] success, error in
            YHHUD.hide()
            guard let self = self else { return }
            var targetTabIndex = 0 // 全部
            if self.serviceCenterMainReqVM.arrDataForSeviceCenterProgress.count > 0 {
                // 进行中
                targetTabIndex = 1
            }
            self.segmentedView.selectItemAt(index: targetTabIndex)
            self.segmentedView.listContainer?.didClickSelectedItem(at: targetTabIndex)
            UIViewController.current?.navigationController?.popToRootViewController(animated: true)
            goTabBarBy(tabType: .service)
        }
    }
}

