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

import UIKit
import JXSegmentedView

class YHServerCenterHoldViewController: UIViewController {
    
    private let serviceCenterMainReqVM : YHServiceCenterViewModel = YHServiceCenterViewModel()
    var stepID: Int = 0
    var mobile: String = ""
    var orderType: Int = 0
    var productInfoMode : YHContactItemModel = YHContactItemModel()
    var orderId: Int = 0 {
        didSet {
            for i in 0..<arrItemTitles.count {
                let vc = arrItemVCs[i] as YHServiceOrderListViewController
                vc.type = i
                if i == 1 {
                    vc.type = 2
                }
                if i == 2 {
                    vc.type = 1
                }
                vc.orderID = orderId
                vc.mobile = mobile
                vc.arrDataForSeviceCenterProgress = arrDataForSeviceCenterProgress
                vc.state = state
                vc.stepID = stepID
                vc.orderType = orderType
                vc.productInfoMode = productInfoMode
                vc.loadData()
            }
        }
    }
    var arrDataForSeviceCenterProgress: [YHServiceCenterProgressModel] = []
    var state: Int = 0
    var canScroll : Bool = false {
        didSet {
            for vc in arrItemVCs {
                vc.vcCanScroll = canScroll
            }
        }
    }
    var controllerOne: YHServiceOrderListViewController = YHServiceOrderListViewController()
    var controllerTwo: YHServiceOrderListViewController = YHServiceOrderListViewController()
    var controllerThree: YHServiceOrderListViewController = YHServiceOrderListViewController()
    var controllerFour: YHServiceOrderListViewController = YHServiceOrderListViewController()
    var arrItemTitles = ["全部", "进行中", "待开始", "已完成"]
    var arrItemVCs: [YHServiceOrderListViewController] = []
    var segmentedView : JXSegmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, 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()
        setupView()
        
        controllerOne.productInfoMode = productInfoMode
        controllerTwo.productInfoMode = productInfoMode
        controllerThree.productInfoMode = productInfoMode
        controllerFour.productInfoMode = productInfoMode
        
        NotificationCenter.default.addObserver(self, selector: #selector(goToServiceTabFromFileListPage), name: YhConstant.YhNotification.didClickFileListBackToServiceTabNotifiction, object: nil)
        // Do any additional setup after loading the view.
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        segmentedView.snp.remakeConstraints { make in
            make.right.equalTo(-4)
            make.left.equalTo(4)
            make.top.equalTo(0)
            make.height.equalTo(48)
        }
        listContainerView.snp.remakeConstraints { make in
            make.right.left.equalToSuperview()
            make.top.equalTo(segmentedView.snp.bottom)
            make.bottom.equalToSuperview()
        }
    }
        
    func setupView() {
        view.backgroundColor = .clear
        controllerOne.type = 0
        controllerOne.orderID = orderId
        controllerOne.stepID = stepID
        controllerOne.orderType = orderType
        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.stepID = stepID
        controllerTwo.orderType = orderType
        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.stepID = stepID
        controllerThree.orderType = orderType
        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.stepID = stepID
        controllerFour.orderType = orderType
        controllerFour.block = {[weak self] type, count, flag in
            guard let self = self else { return }
            arrItemTitles[3] = "已完成(\(count))"
            self.updata(flag: flag, type: 3)
        }
        arrItemVCs.append(controllerOne)
        arrItemVCs.append(controllerTwo)
        arrItemVCs.append(controllerThree)
        arrItemVCs.append(controllerFour)
        
        //segmentedViewDataSource一定要通过属性强持有！！！！！！！！！
//        segmentedView.backgroundColor = .clear
        segmentedView.collectionView.backgroundColor = .white
//        segmentedView.contentScrollView?.backgroundColor = .clear
        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.indicatorHeight = 2
        indicator.indicatorCornerRadius = 0
        indicator.verticalOffset = 4
        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()
        }
    }
    
    @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: false)
            goTabBarBy(tabType: .service)
        }
    }
}

extension YHServerCenterHoldViewController: 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 YHServerCenterHoldViewController: 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]
    }
}
