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

import UIKit

class YHResourceViewModel: NSObject {
    
    // MARK: - 属性
    var arrResourceData: [YHResourceListModel]?
    var hasMoreForResource: Bool = true
    var currentPage: Int = 1
    var pageSize: Int = 10
    var preloadItemIndex: Int = 10
    var totalCount: Int = 0
    
    // 筛选条件
    var currentType: YHResourceFilterType = .service
    var selectedCategories: [YHResourceCategory] = []
    var searchKeyword: String?
    
    var isMyCompanyOpen: Bool = false
    
    override init() {
        super.init()
    }
    
    // MARK: - 网络请求
    
    /// 获取资源列表（公司列表）
    /// - Parameters:
    ///   - firstFlag: 是否首次加载
    ///   - completion: 完成回调
    func getResourceList(firstFlag: Bool, completion: @escaping (Bool, String?) -> Void) {
        
        if firstFlag {
            currentPage = 1
            arrResourceData?.removeAll()
            hasMoreForResource = true
        } else {
            if !hasMoreForResource {
                completion(false, "没有更多数据")
                return
            }
        }
        
        // 构建请求参数
        var params: [String: Any] = [
            "page": currentPage,
            "page_size": pageSize,
            "type": currentType == .service ? 1 : 2  // 1-服务 2-需求
        ]
        // 如果包含全部行业就移除
        selectedCategories.removeAll(where: { $0.id == YHResourceCategory.allCategory.id })
        // 添加分类筛选（多选）- 转为Int数组
        if !selectedCategories.isEmpty {
            let categoryIds = selectedCategories.compactMap { Int($0.id) }
            params["industry_type"] = categoryIds
        }
        
        // 添加搜索关键词
        if let keyword = searchKeyword, !keyword.isEmpty {
            params["keyword"] = keyword
        }
        
        // 调用真实API
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Resource.companyList
        
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any],
                      let result = YHResourceListResponse.deserialize(from: dic) else {
                    completion(false, "数据解析失败")
                    return
                }
                
                if firstFlag {
                    self.totalCount = result.total
                    self.arrResourceData = result.list
                } else {
                    self.arrResourceData?.append(contentsOf: result.list)
                }
                
                self.currentPage += 1
                
                // 判断是否还有更多数据
                if (self.arrResourceData?.count ?? 0) >= self.totalCount {
                    self.hasMoreForResource = false
                } else {
                    self.hasMoreForResource = true
                }
                
                completion(true, nil)
                
            } else {
                let errorMsg = json.msg.isEmpty ? "获取数据失败" : json.msg
                completion(false, errorMsg)
            }
            
        } failBlock: { err in
            let errorMsg = err.errorMsg
            completion(false, errorMsg)
        }
    }
    
    /// 获取资源分类（行业类型）
    /// - Parameter completion: 完成回调
    func getResourceCategories(completion: @escaping ([YHResourceCategory]?, String?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Resource.categoryList
        
        _ = YHNetRequest.getRequest(url: strUrl, params: [:]) { json, _ in
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any],
                      let result = YHIndustryTypeResponse.deserialize(from: dic) else {
                    completion(nil, "数据解析失败")
                    return
                }
                
                // 转换为YHResourceCategory数组
                let categories = result.industry_type.map { $0.toResourceCategory() }
                completion(categories, nil)
            } else {
                let errorMsg = json.msg.isEmpty ? "获取分类失败" : json.msg
                completion(nil, errorMsg)
            }
            
        } failBlock: { err in
            let errorMsg = err.errorMsg
            completion(nil, errorMsg)
        }
    }
    
    /// 获取公司详情
    /// - Parameters:
    ///   - companyId: 公司ID
    ///   - completion: 完成回调
    func getCompanyDetail(companyId: Int, completion: @escaping (YHResourceDetailModel?, String?) -> Void) {
        let params: [String: Any] = ["id": companyId]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Resource.companyDetail
        
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { json, _ in
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any],
                      let result = YHResourceDetailModel.deserialize(from: dic) else {
                    completion(nil, "数据解析失败")
                    return
                }
                
                completion(result, nil)
            } else {
                let errorMsg = json.msg.isEmpty ? "获取详情失败" : json.msg
                completion(nil, errorMsg)
            }
            
        } failBlock: { err in
            let errorMsg = err.errorMsg
            completion(nil, errorMsg)
        }
    }
    
    func getDemandYhId(callback: @escaping (String) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Resource.yhManagerId + "?mode=1"
        _ = YHNetRequest.getRequest(url: strUrl) { json, _ in
            if json.code == 200 {
                guard let dic = json.data?.peel as?  [String: Any], let result = ActiticyIdModel.deserialize(from: dic) else {
                    return
                }
                callback(result.yh_id)
            } else {
                callback("")
            }
        } failBlock: { _ in
            callback("")
        }
        
    }
    
    /// 获取公司详情
    /// - Parameters:
    ///   - completion: 完成回调 // 错误码10005表示客户未注册公司
    func getMyCompanyDetail(completion: @escaping (YHResourceDetailModel?, YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Resource.myCompany
        
        _ = YHNetRequest.getRequest(url: strUrl, params: [:]) { json, _ in
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any],
                      let result = YHResourceDetailModel.deserialize(from: dic) else {
                    let errorModel: YHErrorModel = YHErrorModel(errorCode: -10001, errorMsg: "数据解析失败")
                    completion(nil, errorModel)
                    return
                }
                completion(result, nil)
            } else {
                let errorMsg = json.msg.isEmpty ? "获取详情失败" : json.msg
                let errorModel: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: errorMsg)
                completion(nil, errorModel)
            }
        } failBlock: { err in
            completion(nil, err)
        }
    }
    
    /// 授权公司公开
    /// - Parameters:
    ///   - status: 2-开启，3-关闭
    ///   - completion: 完成回调
    func companyAuthor(status: Int, completion: @escaping (Bool, String?) -> Void) {
        let params: [String: Any] = ["status": status]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Resource.author
        
        _ = YHNetRequest.putRequest(url: strUrl, params: params) { json, _ in
            if json.code == 200 {
                completion(true, nil)
            } else {
                let errorMsg = json.msg.isEmpty ? "授权失败" : json.msg
                completion(false, errorMsg)
            }
            
        } failBlock: { err in
            let errorMsg = err.errorMsg
            completion(false, errorMsg)
        }
    }
}
