//
//  YHMaterialListViewController.swift
//  galaxy
//
//  Created by edy on 2024/3/15.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView

// 统计数量
public let countStatisticsNotify = NSNotification.Name("didCertificateCountStatistics")

class YHCertificateCategoryItem {
    var type : YHCertificateUploadStatus = .all
    var title : String {
        switch type {
        case .all:
            return "全部".local
        case .review:
            return "审核中".local
        case .rejected:
            return "已驳回".local
        case .preUpload:
            return "待上传".local
        case .finish:
            return "已完成".local
        }
    }
    
    init(type: YHCertificateUploadStatus) {
        self.type = type
    }
}

class YHCertificateListContainerVC: YHBaseViewController {
    
    static let segmentHeight = 49.0
    
    var orderId : Int?
    var filterDict : [String: String] = [:]
    var categoryInfo: YHCategoryData = YHCategoryData()
    lazy var navBar: YHCustomNavigationBar = {
        let bar = YHCustomNavigationBar.navBar()
        bar.backgroundColor = .white
        bar.showLeftSecondButtonType(.search)
        bar.backBlock = {
            [weak self] in
            guard let self = self else { return }
            self.navigationController?.popViewController(animated: true)
        }
        bar.leftSecondBtnClick = {
            [weak self] in
            guard let self = self else { return }
            let vc = YHCertificateSearchViewController()
            vc.orderId = orderId
            self.navigationController?.pushViewController(vc)
        }
        return bar
    }()
    
    var titles = ["全部", "待上传(0)", "已驳回(0)", "审核中(0)", "已完成(0)"]
    let categoryItems = [ YHCertificateCategoryItem(type: .all),
                          YHCertificateCategoryItem(type: .preUpload),
                          YHCertificateCategoryItem(type: .rejected),
                          YHCertificateCategoryItem(type: .review),
                          YHCertificateCategoryItem(type: .finish)]
    var itemVCs:[YHCertificateListVC] = []
    
    lazy var segmentContainerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    lazy var segmentedView : JXSegmentedView = {
        let segview = JXSegmentedView(frame: CGRect(x: 0, y: k_Height_NavigationtBarAndStatuBar, width: KScreenWidth, height: Self.segmentHeight))
        segview.dataSource = segmentedDataSource
        segview.delegate = self
        //配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 16
        indicator.indicatorHeight = 4.0
        indicator.indicatorColor = .brandMainColor
        segview.indicators = [indicator]
        segview.backgroundColor = .clear
        segview.listContainer = listContainerView
        segview.backgroundColor = .white
        return segview
    }()
    
    lazy var segmentedDataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.isTitleColorGradientEnabled = true
        dataSource.titles = titles
        dataSource.titleNormalFont = UIFont.PFSC_R(ofSize: 14)
        dataSource.titleNormalColor = .labelTextColor2
        dataSource.titleSelectedFont = UIFont.PFSC_M(ofSize: 16)
        dataSource.titleSelectedColor = UIColor(hexString: "#000000")!
        dataSource.isItemSpacingAverageEnabled = false
        dataSource.itemWidth = JXSegmentedViewAutomaticDimension
        dataSource.itemSpacing = 24
        return dataSource
    }()
    
    //分类title 所对应的VC
    lazy var listContainerView: JXSegmentedListContainerView! = {
        return JXSegmentedListContainerView(dataSource: self, type: .collectionView)
    }()
    
    lazy var filterBtn: YHCertificateFilterButton = {
        let btn = YHCertificateFilterButton.filterBtn()
        btn.clickBlock = {
            [weak self] select in
            guard let self = self else { return }
            filterSheetView.show()
        }
        return btn
    }()
    
    lazy var filterSheetView: YHCertificateFilterView = {
        let view = YHCertificateFilterView.sheetView()
        view.confirmBlock = {
           [weak self] dict in
           guard let self = self else { return }
           self.filterDict =  dict
           let allValues = Array(dict.values)
           var isNoFilterCondition = true
            for value in allValues {
                if !value.isEmpty {
                    isNoFilterCondition = false
                }
            }
            self.filterBtn.isSelect = !isNoFilterCondition

           if let vc = itemVCs.first {
              vc.requestList(status:vc.status, extra:dict)
           }
           self.segmentedView.selectItemAt(index: 0)

        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navigationBar.isHidden = true
        self.view.backgroundColor = .white
        
        self.navBar.title = "资料".local
        if categoryInfo.categoryId == YHCertificateCategoryId.mainApplicant.rawValue {
            self.navBar.title = "主申请人资料".local
            
        } else if categoryInfo.categoryId == YHCertificateCategoryId.spouse.rawValue {
            self.navBar.title = "配偶资料".local
            
        } else if categoryInfo.categoryId == YHCertificateCategoryId.child.rawValue {
            self.navBar.title = "子女资料".local
        }

        NotificationCenter.default.addObserver(self, selector: #selector(didCertificateCountStatistics(_:)), name:countStatisticsNotify , object: nil)

        for item in categoryItems {
            let vc = YHCertificateListVC()
            vc.orderId = orderId
            vc.status = item.type
            vc.categoryInfo = categoryInfo
            itemVCs.append(vc)
        }
        view.addSubview(navBar)
        view.addSubview(segmentContainerView)
        segmentContainerView.addSubview(segmentedView)
        segmentContainerView.addSubview(filterBtn)
        view.addSubview(listContainerView)
        
        navBar.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_statusBar())
            make.height.equalTo(k_Height_NavContentBar)
        }
        segmentContainerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.height.equalTo(Self.segmentHeight+4)
        }
        
        segmentedView.snp.makeConstraints { make in
            make.top.left.equalToSuperview()
            make.right.equalToSuperview().offset(-21-18)
            make.height.equalTo(Self.segmentHeight)
        }
        
        filterBtn.snp.makeConstraints { make in
            make.width.height.equalTo(YHCertificateFilterButton.width)
            make.centerY.equalToSuperview().offset(-2)
            make.right.equalToSuperview().offset(-18)
        }

        listContainerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(segmentContainerView.snp.bottom)
            make.bottom.equalToSuperview()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //处于第一个item的时候，才允许屏幕边缘手势返回
        navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0)
        
        // 请求每个tab列表数据计算数量
        for (index, vc) in itemVCs.enumerated() {
            if index == 0 {
                vc.requestList(status: vc.status, extra:self.filterDict)
            } else {
                vc.requestList(status: vc.status)
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //离开页面的时候，需要恢复屏幕边缘手势，不能影响其他页面
        navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    @objc func didCertificateCountStatistics(_ notification: Notification) {
        guard let dic = notification.object as? [YHCertificateUploadStatus: Int] else { return }
        print(dic)
        
        if let count =  dic[YHCertificateUploadStatus.preUpload] {
            titles[1] = "待上传(\(count))"
            
        } else if let count = dic[YHCertificateUploadStatus.rejected] {
            titles[2] = "已驳回(\(count))"
                               
        } else if let count = dic[YHCertificateUploadStatus.review] {
            titles[3] = "审核中(\(count))"
                              
        } else if let count = dic[YHCertificateUploadStatus.finish] {
            titles[4] = "已完成(\(count))"
        }
        DispatchQueue.main.async {
            self.segmentedDataSource.titles = self.titles
            self.segmentedView.reloadData()
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}


extension YHCertificateListContainerVC: JXSegmentedViewDelegate {
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        if 0 <= index && index < itemVCs.count {
            let vc = itemVCs[index]
            if index == 0 {
                vc.requestList(status: vc.status, extra: self.filterDict)
            } else {
                vc.requestList(status: vc.status)
            }
        }
    }
    /// 正在滚动中的回调
    ///
    /// - Parameters:
    ///   - segmentedView: JXSegmentedView
    ///   - leftIndex: 正在滚动中，相对位置处于左边的index
    ///   - rightIndex: 正在滚动中，相对位置处于右边的index
    ///   - percent: 从左往右计算的百分比
    func segmentedView(_ segmentedView: JXSegmentedView, scrollingFrom leftIndex: Int, to rightIndex: Int, percent: CGFloat) {
        
    }
}

extension YHCertificateListContainerVC: 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 itemVCs[index]
    }
}

