//
//  RolesRootPageController.swift
//  Visual_Novel_iOS
//
//  Created by mh on 2025/10/14.
//

import UIKit
import Combine


class RolesRootPageController: CLTabRootController<RolesRootPageView> {
    
    private var cancellables = Set<AnyCancellable>()
    var page: Int = 1
    var viewModel: ChatRoleViewModel = ChatRoleViewModel()
    var tagViewModel: ChatRoleTagViewModel = ChatRoleTagViewModel()
    var currentTagIds: [String]? = nil  // 当前选中的标签ID数组，nil表示全部
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let baseImageView = UIImageView(image: R.image.base_bg())
        baseImageView.contentMode = .scaleAspectFill
        self.view.insertSubview(baseImageView, at: 0)
        baseImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        view.backgroundColor = .clear
        bgTopIv.isHidden = true
        
        setupViews()
        setupEvent()
        
        // 设置刷新和加载回调
        container.onRefresh = { [weak self] in
            guard let self = self else { return }
            self.page = 1
            self.loadRoles(page: 1, tagIds: self.currentTagIds)
        }
        
        container.onLoadMore = { [weak self] in
            guard let self = self else { return }
            // 上拉加载时，先增加 page，然后加载数据
            // 如果返回的数据为空，page 会在 loadRoles 中回退
            let nextPage = self.page + 1
            self.loadRoles(page: nextPage, tagIds: self.currentTagIds, isLoadMore: true)
        }
        
        // 设置标签选择回调
        container.tagsView.onTagSelected = { [weak self] tagIds in
            guard let self = self else { return }
            self.currentTagIds = tagIds
            self.page = 1
            self.loadRoles(page: 1, tagIds: tagIds)
        }
        
        loadRoles(page: 1, tagIds: nil)
        loadTags()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    private func setupViews() {
        navigationView.bgView.alpha = 0
        navigationView.setupBgViewToStatusBarHeight()
        navigationView.isUserInteractionEnabled = false
    }
    
    private func setupEvent() {
        self.container.jumpPublisher
            .receive(on: RunLoop.main)
            .sink { [weak self] target in
                self?.handleJump(target)
            }
            .store(in: &cancellables)
    }
    
    func loadRoles(page: Int, name: String = "", tagIds: [String]? = nil, isLoadMore: Bool = false) {
        viewModel.loadRoles(index: page, name: name, tagId: tagIds) { [weak self] datas in
            guard let self = self else { return }
            
            // 确保在主线程更新 UI
            DispatchQueue.main.async {
                let isFirstPage = page == 1
                let rows = datas?.rows ?? []
                let hasData = !rows.isEmpty
                
                if isLoadMore {
                    // 上拉加载：只有当返回数据时才更新 page，否则保持原值
                    if hasData {
                        // 有数据，更新 page
                        self.page = page
                        // 追加数据
                        self.container.config(rows, isFirstPage: false)
                    } else {
                        // 没有数据，page 保持不变，显示"没有更多数据"
                        self.container.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                    }
                } else {
                    // 下拉刷新或首次加载：直接更新 page
                    self.page = page
                    self.container.config(rows, isFirstPage: isFirstPage)
                }
                
                // 结束刷新动画
                self.container.endRefreshing()
            }
        }
    }
    
    func loadTags() {
        tagViewModel.loadRoleTags(name: "") { [weak self] datas in
            guard let self = self else { return }
            self.container.configureTags(datas?.rows)
        }
    }
    
    // 点击顶部 实现跳转
    private func handleJump(_ target: JumpTarget) {
        switch target {
        case .search:
            let vc = TestEntrancesController()
            navigationController?.pushViewController(vc, animated: true)
        case .check:
            let vc = TestEntrancesController()
            navigationController?.pushViewController(vc, animated: true)
        case .discord:
            let vc = TestEntrancesController()
            navigationController?.pushViewController(vc, animated: true)
        }
    }
}
