//
//  DiscoverRootPageView.swift
//
//
//  Created by Leon on 2025/7/22.
//

import JXPagingView
import JXSegmentedView
import UIKit

class DiscoverRootPageView: CLContainer {
    private var bgBdView : UIView!
    private lazy var pagingView = JXPagingListRefreshView(delegate: self)

    lazy var headerView: DiscoverHeadView = DiscoverHeadView()
    lazy var pinHeaderView: DiscoverHeadPinHeader = DiscoverHeadPinHeader()

    private var headerViewHeight: CGFloat = 288
    private var headerPinHeadHeight: Int = 96

    private var controllers = [JXPagingViewListViewDelegate]()

    // Data
    var characterNodes: [DictNode] = [DictNode]()
    var tagsNodes: [DictNode] = [DictNode]()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        setupData()
        setupEvent()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupViews() {
        bgBdView = {
            let v = UIView()
            v.backgroundColor = .c.cbd
            addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            v.alpha = 0
            return v
        }()
        
        pagingView.mainTableView.backgroundColor = UIColor.clear
        pagingView.mainTableView.gestureDelegate = self
        pagingView.pinSectionHeaderVerticalOffset = Int(UIWindow.statusBarHeight)
        pagingView.listContainerView.listCellBackgroundColor = .clear
        addSubview(pagingView)
        pagingView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview()
            make.top.equalToSuperview()
        }

        pinHeaderView.segmentedView.listContainer = pagingView.listContainerView
        pinHeaderView.segmentedView.delegate = self
        //pinHeaderView.subSegementedView.delegate = self
    }

    // 初始化
    private func setupData() {
        guard let characterNodes = AppDictManager.shared.aiDict?.characterDictList else {
            return
        }

        self.characterNodes = characterNodes

        controllers.removeAll()
        var titles = [String]()
        
        // First Tab: All
        do{
            titles.append("All")
            let vc = DiscoverRolesGridController()
            vc.allCatogryTab = true
            // 一些默认情况
            let viewModel = DiscoverHomeRolesViewModel()
            viewModel.character = nil
            vc.viewModel = viewModel
            controllers.append(vc)
        }
        
        for per in characterNodes {
            titles.append(per.name)
            let vc = DiscoverRolesGridController()
            // 一些默认情况
            let viewModel = DiscoverHomeRolesViewModel()
            viewModel.character = per
            viewModel.tags = per.childDictList
            viewModel.selectTagCode = per.childDictList?.first?.code
            vc.viewModel = viewModel
            controllers.append(vc)
        }
        pinHeaderView.dataSource.titles = titles

        refreshSubTagsSegmentView()
    }

    /// 仅刷新父标题文案
    private func refreshSubTagsSegmentView() {
        let titleIndex = pinHeaderView.segmentedView.selectedIndex
        
        //⚠️ First tab is All
        if titleIndex > 0{
            let selectCharacterNode = characterNodes[titleIndex - 1]
            tagsNodes = selectCharacterNode.childDictList ?? []
        }else{
            tagsNodes = []
        }
        // let selectTagNode = tagsNodes[pinHeaderView.subSegementedView.selectedIndex]

//        var titles = [String]()
//        for per in tagsNodes {
//            titles.append("#\(per.name)")
//        }
//        pinHeaderView.subDataSouce.titles = titles
//        pinHeaderView.subSegementedView.reloadData()
    }

    private func setupEvent() {
        headerView.heightChangeBlock = { [weak self] height in
            self?.headerViewHeight = height
            self?.pagingView.resizeTableHeaderViewHeight()
        }

        // pinHeaderView.filterButton.addTarget(self, action: #selector(tapFilterButton(button:)), for: .touchUpInside)
    }
    
    // MARK: - Public
    
    func setupFilter(filter: RolesFilterModel){
        dlog("当前： params:\(filter.toNonNilDictionary())")
        for (index, vc) in controllers.enumerated() {
            if let gridVc = vc as? DiscoverRolesGridController{
//                #warning("test")
                gridVc.viewModel.filterModel = filter
                if index == pinHeaderView.segmentedView.selectedIndex{
                    gridVc.loadNewData()
                }else{
                    gridVc.refreshDatasWhenAppear = true
                }
            }
        }
    }

    // MARK: Action

//     @objc private func tapFilterButton(button: UIButton){
//         if pinHeaderView.filterConditionCount >= 2{
//             pinHeaderView.setupFilterCount(0)
//         }else{
//             pinHeaderView.setupFilterCount(2)
//         }
//    }
}

extension DiscoverRootPageView {
}

extension DiscoverRootPageView: JXPagingViewDelegate, JXSegmentedViewDelegate {
    func tableHeaderViewHeight(in _: JXPagingView) -> Int {
        return Int(headerViewHeight)
    }

    func tableHeaderView(in _: JXPagingView) -> UIView {
        return headerView
    }

    func heightForPinSectionHeader(in _: JXPagingView) -> Int {
        return headerPinHeadHeight
    }

    func viewForPinSectionHeader(in _: JXPagingView) -> UIView {
        return pinHeaderView
    }

    func numberOfLists(in _: JXPagingView) -> Int {
        return controllers.count
    }

    func pagingView(_: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        let vc = controllers[index]
        return vc
    }

    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        if segmentedView == pinHeaderView.segmentedView {
            refreshSubTagsSegmentView()
        }
//        else if segmentedView == pinHeaderView.subSegementedView {
//            let selectTag = tagsNodes[index]
//            if let currentVc = controllers[pinHeaderView.segmentedView.selectedIndex] as? DiscoverRolesGridController {
//                currentVc.tryLoad(code: selectTag.code!)
//            }
//        }
    }

    func mainTableViewDidScroll(_ scrollView: UIScrollView) {
//        NaviAlphaHandle.changeNaviViewsAlpha(scrollView: scrollView, alphaViews: [bgBdView, navigationView?.bgView], oppositeViews: [])
    }
}

extension DiscoverRootPageView: JXPagingMainTableViewGestureDelegate {
    func mainTableViewGestureRecognizer(
        _ gestureRecognizer: UIGestureRecognizer,
        shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        // 如果是 UICollectionView 的手势，先判断滚动方向
        if let panGesture = otherGestureRecognizer as? UIPanGestureRecognizer,
           let otherView = otherGestureRecognizer.view,
           otherView is UICollectionView {
            let velocity = panGesture.velocity(in: otherView)
            // 横向滚动时禁止
            if abs(velocity.x) > abs(velocity.y) {
                return false
            }
        }
        // 禁止segmentedView左右滑动的时候，上下和左右都可以滚动
//        if otherGestureRecognizer == segmentedView.collectionView.panGestureRecognizer {
//            return false
//        }
        return gestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
            && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
    }
}
