//
//  YHResourceViewController.swift
//  galaxy
//
//  Created by alexzzw on 2025/9/24.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import ESPullToRefresh
import JXSegmentedView
import SnapKit

class YHResourceViewController: YHBaseViewController {
    static let selectTypeKey = "selectTypeKey"
    
    // 添加高度约束属性
    private var categoryViewHeightConstraint: Constraint?
    
    private var searchWorkItem: DispatchWorkItem?
    
    lazy var viewModel: YHResourceViewModel = {
        let viewModel = YHResourceViewModel()
        return viewModel
    }()
    
    // 消息处理器
    private lazy var messageHandler: YHIMMessageHandler = {
        return YHIMMessageHandler(
            viewController: self,
            navigationController: navigationController
        )
    }()
    
    // 筛选条件
    var selectedCategories: [YHResourceCategory] = []
    
    // 行业分类数据
    var allCategories: [YHResourceCategory] = []
    
    // MARK: - UI Components
    
    // 自定义搜索视图
    lazy var customSearchView: YHCustomSearchView = {
        let searchView = YHCustomSearchView()
        searchView.delegate = self
        searchView.placeholder = "搜索企业名称、企业供需"
        return searchView
    }()
    
    // 筛选按钮容器
    lazy var filterContainerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    // 企业服务按钮
    lazy var serviceButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("企业服务", for: .normal)
        btn.setTitleColor(UIColor.brandGrayColor7, for: .normal)
        btn.setTitleColor(UIColor.brandGrayColor8, for: .selected)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 13)
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.brandGrayColor4.cgColor
        btn.addTarget(self, action: #selector(serviceButtonClicked), for: .touchUpInside)
        return btn
    }()
    
    // 企业需求按钮
    lazy var demandButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("企业需求", for: .normal)
        btn.setTitleColor(UIColor.brandGrayColor7, for: .normal)
        btn.setTitleColor(UIColor.brandGrayColor8, for: .selected)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 13)
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.brandGrayColor4.cgColor
        btn.addTarget(self, action: #selector(demandButtonClicked), for: .touchUpInside)
        return btn
    }()
    
    // 全部行业按钮
    lazy var industryButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("行业", for: .normal)
        btn.setTitleColor(UIColor.brandGrayColor7, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 13)
        btn.setImage(UIImage(named: "resource_filter_down"), for: .normal)
        btn.addTarget(self, action: #selector(industryButtonClicked), for: .touchUpInside)
        return btn
    }()
    
    // 行业分类视图
    lazy var categoryView: YHResourceCategoryView = {
        let view = YHResourceCategoryView()
        view.backgroundColor = .white
        view.isHidden = true
        view.delegate = self
        return view
    }()
    
    // 遮罩视图
    lazy var maskView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        view.isHidden = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideCategoryView))
        view.addGestureRecognizer(tapGesture)
        return view
    }()
    
    // 资源列表
    lazy var resourceTableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.backgroundColor = UIColor.systemGray6
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.register(YHResourceTableViewCell.self, forCellReuseIdentifier: YHResourceTableViewCell.cellReuseIdentifier)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.showsVerticalScrollIndicator = false
        tableView.keyboardDismissMode = .onDrag
        return tableView
    }()
    
    // 空状态视图
    private lazy var noDataView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("暂无内容", kEmptyOrderBgName)
        view.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 164)
        view.backgroundColor = .clear
        view.isHidden = true
        return view
    }()
    
    // 发布需求按钮
    lazy var publishButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = UIColor.brandGrayColor8
        btn.setImage(UIImage(named: "circle_publish_icon"), for: .normal)
        btn.setTitle("发布需求", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 15)
        btn.layer.cornerRadius = 22
        btn.addTarget(self, action: #selector(publishButtonClicked), for: .touchUpInside)
        return btn
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadCategories()  // 先加载分类数据
//        addDefaultData()
        getData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if viewModel.arrResourceData?.isEmpty == true {
            getData()
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    func handleTypeChangeNotification(_ userInfo: [AnyHashable: Any]) {
        guard let selectTypeKey = userInfo[YHResourceViewController.selectTypeKey] as? String,
              let type = YHResourceFilterType(rawValue: selectTypeKey) else {
            return
        }
        setResourceType(type)
    }
}

// MARK: - 私有方法
private extension YHResourceViewController {
    
    func setupUI() {
        gk_navigationBar.isHidden = true
        view.backgroundColor = UIColor.white
        
        // 添加子视图
        view.addSubview(customSearchView)
        view.addSubview(filterContainerView)
        filterContainerView.addSubview(serviceButton)
        filterContainerView.addSubview(demandButton)
        filterContainerView.addSubview(industryButton)
        view.addSubview(resourceTableView)
        view.addSubview(noDataView)
        view.addSubview(publishButton)
        
        // 分类视图要最后添加,确保在最上层
        view.addSubview(maskView)
        view.addSubview(categoryView)
        
        setupConstraints()
        setupFilterButtons()
        setupPullToRefresh()
    }
    
    func setupConstraints() {
        customSearchView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(60)
        }
        
        filterContainerView.snp.makeConstraints { make in
            make.top.equalTo(customSearchView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        
        serviceButton.setContentCompressionResistancePriority(.required, for: .horizontal)
        demandButton.setContentCompressionResistancePriority(.required, for: .horizontal)
        industryButton.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        
        serviceButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.centerY.equalToSuperview()
            make.width.equalTo(76)
            make.height.equalTo(26)
        }
        
        demandButton.snp.makeConstraints { make in
            make.left.equalTo(serviceButton.snp.right).offset(10)
            make.centerY.equalToSuperview()
            make.width.equalTo(76)
            make.height.equalTo(26)
        }
        
        industryButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalToSuperview()
            make.width.greaterThanOrEqualTo(32)
            make.left.greaterThanOrEqualTo(demandButton.snp.right).offset(8)
            make.height.equalTo(26)
        }
        
        categoryView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(filterContainerView.snp.bottom)
            self.categoryViewHeightConstraint = make.height.equalTo(0).constraint
        }
        
        maskView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(filterContainerView.snp.bottom)
        }
        
        resourceTableView.snp.makeConstraints { make in
            make.top.equalTo(filterContainerView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        noDataView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.equalTo(KScreenWidth)
            make.height.equalTo(164)
        }
        
        publishButton.snp.makeConstraints { make in
            make.width.equalTo(134)
            make.height.equalTo(44)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-30)
        }
        
        publishButton.iconInLeft(spacing: 6)
        industryButton.iconInRight(with: 6)
    }
    
    func setupFilterButtons() {
        // 默认选中企业服务
        selectFilterType(.service)
    }
    
    func setupPullToRefresh() {
        resourceTableView.es.addYHPullToRefresh { [weak self] in
            guard let self = self else { return }
            self.loadCategories()
            self.getData()
        }
        
        resourceTableView.es.addInfiniteScrolling { [weak self] in
            guard let self = self else { return }
            self.loadMoreData()
        }
        
        resourceTableView.es.stopPullToRefresh()
        resourceTableView.es.stopLoadingMore()
    }
    
    func addDefaultData() {
        getCacheDataForResourceData()
    }
    
    func getCacheDataForResourceData() {
        let arrString = UserDefaults.standard.value(forKey: "resourceFirstPageData")
        if let tmp = arrString as? String {
            guard let result = [YHResourceListModel].deserialize(from: tmp) else {
                return
            }
            
            if !result.isEmpty {
                self.viewModel.arrResourceData = result
                self.updateUI()
            }
        }
    }
    
    /// 加载行业分类数据
    func loadCategories() {
        viewModel.getResourceCategories { [weak self] categories, error in
            guard let self = self else { return }
            
            if var categories = categories {
                let all = YHResourceCategory.allCategory
                categories.insert(all, at: 0)
                self.allCategories = categories
                self.categoryView.setCategories(categories)
            } else if let error = error {
                printLog("加载分类失败: \(error)")
            }
        }
    }
    
    func getData() {
        loadFirstData()
    }
    
    func loadFirstData() {
        // 显示loading状态
        if viewModel.arrResourceData?.isEmpty ?? true {
            YHHUD.show(.progress(message: "加载中..."))
        }
        
        viewModel.getResourceList(firstFlag: true) { [weak self] success, message in
            guard let self = self else { return }
            
            DispatchQueue.main.async {
                YHHUD.hide()
                if !success, let errorMessage = message {
                    YHHUD.flash(message: errorMessage)
                }
                self.resourceTableView.es.stopPullToRefresh()
                
                if self.viewModel.hasMoreForResource == false {
                    self.resourceTableView.es.noticeNoMoreData()
                    self.resourceTableView.footer?.alpha = 1
                }
                
                self.updateUI()
            }
        }
    }
    
    func loadMoreData() {
        viewModel.getResourceList(firstFlag: false) { [weak self] _, _ in
            guard let self = self else { return }
            
            DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.35, execute: {
                self.resourceTableView.reloadData()
                
                self.resourceTableView.es.stopLoadingMore()
                if self.viewModel.hasMoreForResource == false, (self.viewModel.arrResourceData?.count ?? 0) > 0 {
                    self.resourceTableView.es.noticeNoMoreData()
                    self.resourceTableView.footer?.alpha = 1
                }
            })
        }
    }
    
    func updateUI() {
        let hasData = viewModel.arrResourceData?.count ?? 0 > 0
        resourceTableView.isHidden = !hasData
        noDataView.isHidden = hasData
        
        if hasData {
            resourceTableView.reloadData()
        }
    }
    
    func updateIndustryButtonTitle() {
        if selectedCategories.isEmpty {
            industryButton.setTitle("行业", for: .normal)
            industryButton.setTitleColor(UIColor.brandGrayColor7, for: .normal)
            industryButton.titleLabel?.font = UIFont.PFSC_R(ofSize: 13)
        } else if selectedCategories.count == 1 {
            if selectedCategories.first?.id == YHResourceCategory.allCategory.id {
                industryButton.setTitle("全部行业", for: .normal)
                industryButton.setTitleColor(UIColor.brandGrayColor8, for: .normal)
                industryButton.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
            } else {
                industryButton.setTitle(selectedCategories.first?.name ?? "全部行业", for: .normal)
                industryButton.setTitleColor(UIColor.brandGrayColor8, for: .normal)
                industryButton.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
            }
        } else {
            industryButton.setTitle("已选\(selectedCategories.count)个行业", for: .normal)
            industryButton.setTitleColor(UIColor.brandGrayColor8, for: .normal)
            industryButton.titleLabel?.font = UIFont.PFSC_M(ofSize: 13)
        }
        industryButton.iconInRight(with: 6)
    }
    
    func resetCategorySelection() {
        selectedCategories.removeAll()
        viewModel.selectedCategories.removeAll()
        updateIndustryButtonTitle()
    }
    
    func resetAllFilters() {
        // 重置所有筛选条件
        customSearchView.clearText()
        viewModel.searchKeyword = nil
        resetCategorySelection()
        getData()
    }
    
    func setResourceType(_ type: YHResourceFilterType) {
        selectFilterType(type)
        viewModel.currentType = type
        // 重置分类选择
        resetCategorySelection()
        getData()
    }
    
    // MARK: - 按钮事件处理
    
    @objc func serviceButtonClicked() {
        setResourceType(.service)
    }
    
    @objc func demandButtonClicked() {
        setResourceType(.demand)
    }
    
    @objc func industryButtonClicked() {
        if categoryView.isHidden {
            showCategoryView()
        } else {
            hideCategoryView()
        }
    }
    
    func showCategoryView() {
        // 设置当前选中的分类
        categoryView.setSelectedCategories(selectedCategories)

        // 显示遮罩和分类视图
        maskView.isHidden = false
        categoryView.isHidden = false
        maskView.alpha = 0

        // 目标高度（可以根据实际内容调整）
        let targetHeight: CGFloat = UIScreen.main.bounds.width

        // 高度约束动画
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
            // 更新高度约束
            self.categoryViewHeightConstraint?.update(offset: targetHeight)

            // 更新遮罩透明度
            self.maskView.alpha = 1

            // 触发布局更新
            self.view.layoutIfNeeded()
        })

        // 更新按钮状态
        industryButton.setImage(UIImage(named: "resource_filter_up"), for: .normal)
    }

    @objc func hideCategoryView() {
        // 高度约束动画
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: {
            // 更新高度约束为0
            self.categoryViewHeightConstraint?.update(offset: 0)

            // 更新遮罩透明度
            self.maskView.alpha = 0

            // 触发布局更新
            self.view.layoutIfNeeded()
        }) { _ in
            // 动画完成后隐藏视图
            self.categoryView.isHidden = true
            self.maskView.isHidden = true
        }

        // 更新按钮状态
        industryButton.setImage(UIImage(named: "resource_filter_down"), for: .normal)
    }
    
    @objc func publishButtonClicked() {
        if !YHLoginManager.shared.isLogin() {
            YHOneKeyLoginManager.shared.oneKeyLogin()
            return
        }
        
        YHGrayCommonAlertView.show("需联系银河管家进行发布信息", "联系银河管家发布企业服务与企业需求，快来与我们联系吧~", "返回", "前往联系", fullGuestureEnable: false) {
        } callBack: { [weak self] in
            guard let self = self else {
                return
            }
            YHHUD.show(.progress(message: "加载中..."))
            self.viewModel.getDemandYhId { [weak self] id in
                guard let self = self else {
                    return
                }
                YHHUD.hide()
                if id.isEmpty {
                    YHHUD.flash(message: "获取银河ID失败")
                    return
                }
                self.messageHandler.gotoChatVC(senderID: id)
            }
        }
    }
    
    func selectFilterType(_ type: YHResourceFilterType) {
        // 重置所有按钮状态
        [serviceButton, demandButton].forEach { btn in
            btn.isSelected = false
            btn.layer.borderColor = UIColor.brandGrayColor4.cgColor
        }
        
        // 设置选中状态
        let selectedButton = type == .service ? serviceButton : demandButton
        selectedButton.isSelected = true
        selectedButton.layer.borderColor = UIColor.brandGrayColor8.cgColor
    }
}

// MARK: - YHCustomSearchViewDelegate
extension YHResourceViewController: YHCustomSearchViewDelegate {
    
    func searchView(_ searchView: YHCustomSearchView, didSearchWithText text: String?) {
        // 取消之前的延迟任务
        searchWorkItem?.cancel()
        
        // 创建新的延迟任务
        let workItem = DispatchWorkItem { [weak self] in
            self?.viewModel.searchKeyword = text
            self?.getData()
        }
        
        searchWorkItem = workItem
        
        // 1秒后执行
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: workItem)
    }
    
    func searchViewDidBeginEditing(_ searchView: YHCustomSearchView) {
        // 搜索开始编辑时的处理
    }
    
    func searchViewDidEndEditing(_ searchView: YHCustomSearchView) {
        // 搜索结束编辑时的处理
    }
}

// MARK: - UITableViewDelegate, UITableViewDataSource
extension YHResourceViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.arrResourceData?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let datas = viewModel.arrResourceData,
              datas.count > indexPath.row,
              let cell = tableView.dequeueReusableCell(withIdentifier: YHResourceTableViewCell.cellReuseIdentifier, for: indexPath) as? YHResourceTableViewCell else {
            return UITableViewCell()
        }
        let model = datas[indexPath.row]
        model.isService = viewModel.currentType == .service
        cell.resourceModel = model
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let model = viewModel.arrResourceData?[indexPath.row] else { return }
        
        // 跳转到详情页
        let vc = YHResourceDetailViewController()
        if model.is_owner == 1 {
            vc.isMyCompany = true
            vc.companyId = model.id
        } else {
            vc.isMyCompany = false
            vc.companyId = model.id
        }
        
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - JXSegmentedListContainerViewListDelegate
extension YHResourceViewController: JXSegmentedListContainerViewListDelegate {
    
    func listView() -> UIView {
        return view
    }
}

// MARK: - YHResourceCategoryViewDelegate
extension YHResourceViewController: YHResourceCategoryViewDelegate {
    func categoryView(_ view: YHResourceCategoryView, didSelectCategories categories: [YHResourceCategory], isSet: Bool) {
        selectedCategories = categories
        viewModel.selectedCategories = categories
        updateIndustryButtonTitle()
        
        if isSet {
            // 隐藏分类视图
            hideCategoryView()
            // 重新加载数据
            getData()
        }
    }
}

// MARK: - 枚举定义
enum YHResourceFilterType: String {
    case service
    case demand
}
