//
//  DiscoverRolesGridController.swift

//
//  Created by Leon on 2025/9/8.
//

import JXPagingView
import UIKit

class DiscoverRolesGridController: CLBaseGridController {
    var viewModel: DiscoverHomeRolesViewModel!

    var tagsChooseView = HorizontalScrollTagsView()
    
    var selectTagCodes = [String]()
    var allCatogryTab: Bool = false
    
    // 分页加载过的aiId，第一页请求时清空
    var loadedAiIds = [Int]()
    
    // Flag
    var refreshDatasWhenAppear:Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = .clear
        setupViews()
        setupDatas()
        setupEvents()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if refreshDatasWhenAppear{
            collectionView.mj_header?.beginRefreshing()
            refreshDatasWhenAppear = false
        }
    }

    private func setupViews() {
        
        if allCatogryTab{
            collectionView.snp.remakeConstraints { make in
                make.edges.equalToSuperview()
            }
        }else{
            view.addSubview(tagsChooseView)
            tagsChooseView.snp.makeConstraints { make in
                make.top.leading.trailing.equalToSuperview()
                make.height.equalTo(56)
            }
            
            collectionView.snp.remakeConstraints { make in
                make.top.equalTo(tagsChooseView.snp.bottom)
                make.leading.trailing.bottom.equalToSuperview()
            }
        }
        
        navigationView.isHidden = true
        collectionView.register(MeRootPageRollCell.self, forCellWithReuseIdentifier: "MeRootPageRollCell")
        collectionView.register(UICollectionReusableView.self,
                    forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
                    withReuseIdentifier: "UICollectionReusableView")
        
        let lr = CGFloat.lrs
        let itemW = (UIScreen.width - lr * 2 - 16) * 0.5
        let itemH = itemW * 260 / 165.0 + 112

        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 16
        layout.sectionInset = .init(top: 12, left: lr, bottom: 24 + UIWindow.safeAreaBottom, right: lr)
        layout.itemSize = .init(width: itemW, height: itemH)
        layout.invalidateLayout()
        
       

        addRefreshHeaderFooter()
    }

    private func setupDatas() {
        // collectionView.mj_header?.beginRefreshing()
        loadNewData()
        
        if allCatogryTab == false{
            var tagsName = [String]()
            for per in viewModel.tags ?? [] {
                let formatString = "#\(per.name)"
                tagsName.append(formatString)
            }
            
            tagsChooseView.setTags(tagsName)
        }
    }

    override func loadData() {
        
        if page == 1{
            loadedAiIds.removeAll()
        }
    
        viewModel.loadRoles(pn: page, codes: selectTagCodes, exList: loadedAiIds) { [weak self] status, roles in
            self?.collectionView.mj_header?.endRefreshing()
            self?.collectionView.mj_footer?.endRefreshing()
            if status {
                let array = roles ?? []
                
                for per in array {
                    if let theId = per.aiId{
                        self?.loadedAiIds.append(theId)
                    }
                }
                
                if self?.page == 1 {
                    self?.collectionView.contentOffset = .zero
                    self?.datas = array
                    self?.collectionView.mj_footer?.resetNoMoreData()
                    // self?.view.setupEmpty(empty: array.count <= 0, msg: "暂无角色")
                    if array.count > 0 {
                        self?.view.hideEmpty()
                    } else {
                        self?.view.showStartYEmpty(text: "暂无角色", startY: 96)
                    }
                } else {
                    self?.datas.append(contentsOf: array)
                    if array.count <= 0 {
                        self?.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                    }
                }
                self?.collectionView.reloadData()
            }
        }
    }

    private func setupEvents() {
        
        tagsChooseView.selectionCallback = {[weak self] selectedTags, selectedIndices in
            guard let `self` = self else {
                return
            }
            print("选中的标签: \(selectedTags)")
            print("选中的索引: \(selectedIndices)")
            
            self.selectTagCodes.removeAll()
            for (index, tag) in (self.viewModel.tags ?? []).enumerated() {
                if selectedIndices.contains(index) {
                    if let code = tag.code {
                        self.selectTagCodes.append(code)
                    }
                } 
            }
            self.loadNewData()
        }
    }

    // MARK: - Public

//    func tryLoad(code: String) {
//        if let tagCode = viewModel.selectTagCode, code == tagCode {
//            return
//        }
//        viewModel.selectTagCode = code
//        loadNewData()
//    }

    // MARK: - UICollectionView

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datas.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MeRootPageRollCell", for: indexPath) as! MeRootPageRollCell
        cell.cellType = .discoverList
        if let data = datas[indexPath.item] as? AIRoleInfo {
            cell.config(data: data)
        }
        return cell
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let data = datas[indexPath.item] as? AIRoleInfo {
            AppRouter.goChatVC(aiId: data.aiId)
        }
    }
    
//    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//        if kind == UICollectionView.elementKindSectionHeader {
//            let header = collectionView.dequeueReusableSupplementaryView(
//                ofKind: kind,
//                withReuseIdentifier: "UICollectionReusableView",
//                for: indexPath
//            )
//            
//            if !allCatogryTab{
//                if tagsChooseView.superview == nil || tagsChooseView.superview != header {
//                    tagsChooseView.removeFromSuperview()
//                }
//                
//                header.addSubview(tagsChooseView)
//                tagsChooseView.snp.makeConstraints { make in
//                    make.top.leading.trailing.equalToSuperview()
//                    make.bottom.equalToSuperview()
//                }
//            }
//
//            return header
//        }
//        return UICollectionReusableView()
//    }
//    
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
//        let height = allCatogryTab ? 0.0 : 56.0
//        return CGSize(width: UIScreen.width, height: height)
//    }
}

extension DiscoverRolesGridController {

}

extension DiscoverRolesGridController: JXPagingViewListViewDelegate {
    func listView() -> UIView {
        return view
    }

    func listScrollView() -> UIScrollView {
        return collectionView
    }

    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> Void) {
        listViewDidScrollCallback = callback
    }
}
