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

import UIKit
import SmartCodable

// MARK: - 公司列表响应模型
class YHResourceListResponse: SmartCodable {
    required init() {}
    
    var total: Int = 0
    var list: [YHResourceListModel] = []
}

// MARK: - 公司头像模型
class YHCompanyAvatar: SmartCodable {
    required init() {}
    
    var name: String = ""
    var url: String = ""
}

// MARK: - 公司文档模型
class YHCompanyDocument: SmartCodable {
    required init() {}
    
    var name: String = ""
    var url: String = ""
}

// MARK: - 公司详情模型
class YHResourceDetailModel: SmartCodable {
    required init() {}
    
    var company_avatar: YHCompanyAvatar?
    var id: Int = 0
    var company_name: String = ""
    var company_english_name: String = ""
    var customer_id: Int = 0
    var customer_name: String = ""
    var last_processed_time: String = ""
    var processor_id: Int = 0
    var processor: String = ""
    var settlement_status: Int = 0 // 1,2 已授权 3.未授权
    var settlement_status_str: String = ""
    var resource_provided: String = ""
    var demand_published: String = ""
    var settlement_time: String = ""
    var industry_type: Int = 0
    var industry_type_str: String = ""
    var company_introduction: String = ""    // 公司介绍
    var company_business: String = ""        // 主营业务
    var company_information: [YHCompanyDocument] = []  // 公司资料图片
    var created_at: String = ""
    var updated_at: String = ""
    var yh_id: String = ""
    
    // 计算属性
    var companyLogoUrl: String {
        return company_avatar?.url ?? ""
    }
    
    var displayName: String {
        return company_name.isEmpty ? company_english_name : company_name
    }
    
    var isSettlement: Bool {
        return settlement_status != 3 && settlement_status != 0
    }
}

// MARK: - 资源列表模型（公司信息）
class YHResourceListModel: SmartCodable {
    
    required init() {}
    var isService = true
    
    // MARK: - 基本信息（匹配列表API）
    var is_owner: Int = 0 // 0-非所属公司，1-所属公司
    var id: Int = 0
    var company_avatar: YHCompanyAvatar?
    var company_name: String = ""
    var company_english_name: String = ""
    var resource_provided: String = ""      // 提供的服务
    var demand_published: String = ""       // 发布的需求
    var industry_type: Int = 0
    var industry_type_str: String = ""
    
    // MARK: - 详情字段（从详情接口获取后填充）
    var company_introduction: String = ""   // 公司介绍
    var company_business: String = ""       // 主营业务
    var company_information: [YHCompanyDocument] = []  // 公司资料
    var settlement_status: Int = 0 // 1,2 已授权 3.未授权
    var settlement_status_str: String = ""
    
    // MARK: - 计算属性
    
    /// 公司Logo URL
    var companyLogoUrl: String {
        return company_avatar?.url ?? ""
    }
    
    /// 显示名称（优先显示中文名）
    var displayName: String {
        return company_name.isEmpty ? "-" : company_name
    }
    
    /// 是否有英文名
    var hasEnglishName: Bool {
        return !company_english_name.isEmpty
    }
    
    /// 行业类型显示文本
    var industryDisplayText: String {
        return industry_type_str.isEmpty ? "-" : industry_type_str
    }
    
    /// 是否提供服务
    var hasResourceProvided: Bool {
        return !resource_provided.isEmpty
    }
    
    /// 是否有需求
    var hasDemandPublished: Bool {
        return !demand_published.isEmpty
    }
    
    /// 服务和需求显示文本
    var serviceInfoText: String {
        var texts: [String] = []
        if hasResourceProvided {
            texts.append("服务: \(resource_provided)")
        }
        if hasDemandPublished {
            texts.append("需求: \(demand_published)")
        }
        return texts.joined(separator: " | ")
    }
    
    /// ID字符串（用于兼容旧代码）
    var idString: String {
        return "\(id)"
    }
    
    // MARK: - 兼容旧字段的计算属性
    
    /// 企业介绍（兼容旧字段 content）
    var content: String {
        return company_introduction.isEmpty ?
               (resource_provided.isEmpty ? demand_published : resource_provided) :
               company_introduction
    }
    
    /// 分类名称（兼容旧字段 category_name）
    var category_name: String {
        return industry_type_str
    }
    
    /// 服务周期（兼容旧字段 service_duration）
    var service_duration: String {
        return company_business
    }
    
    /// 图片数组（兼容旧字段 images）
    var images: [String] {
        return company_information.map { $0.url }
    }
    
    // MARK: - 便利方法
    
    /// 验证数据完整性
    func isValid() -> Bool {
        return id > 0 && !displayName.isEmpty
    }
    
    /// 更新详情数据（从详情接口获取后调用）
    func updateWithDetail(_ detail: YHResourceDetailModel) {
        self.company_introduction = detail.company_introduction
        self.company_business = detail.company_business
        self.company_information = detail.company_information
        self.settlement_status = detail.settlement_status
        self.settlement_status_str = detail.settlement_status_str
        // 如果需要，可以更新其他字段
        if self.resource_provided.isEmpty {
            self.resource_provided = detail.resource_provided
        }
        if self.demand_published.isEmpty {
            self.demand_published = detail.demand_published
        }
    }
}

// MARK: - 资源分类模型
class YHResourceCategory: SmartCodable {
    
    static var allCategory: YHResourceCategory = {
        let all = YHResourceCategory()
        all.name = "全部行业"
        all.id = "-9999"
        return all
    }()
    
    required init() {}
    
    var id: String = ""
    var name: String = ""
    var icon: String = ""
    var sort: Int = 0
    var parent_id: String = ""
    var children: [YHResourceCategory] = []
    var description_text: String = ""
    var is_hot: Bool = false
    var resource_count: Int = 0
    
    // 计算属性
    var hasChildren: Bool {
        return !children.isEmpty
    }
    
    var isTopLevel: Bool {
        return parent_id.isEmpty
    }
}

// MARK: - 行业分类响应模型
class YHIndustryTypeResponse: SmartCodable {
    required init() {}
    
    var industry_type: [YHIndustryTypeModel] = []
}

// MARK: - 行业类型模型
class YHIndustryTypeModel: SmartCodable {
    required init() {}
    
    var id: String = ""
    var name: String = ""
    
    /// 转换为YHResourceCategory（用于兼容现有UI）
    func toResourceCategory() -> YHResourceCategory {
        let category = YHResourceCategory()
        category.id = id
        category.name = name
        return category
    }
}

// MARK: - String Extension
extension String {
    func toDisplayTime() -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        guard let date = formatter.date(from: self) else {
            return self
        }
        
        let now = Date()
        let interval = now.timeIntervalSince(date)
        
        if interval < 60 {
            return "刚刚"
        } else if interval < 3600 {
            return "\(Int(interval / 60))分钟前"
        } else if interval < 86400 {
            return "\(Int(interval / 3600))小时前"
        } else if interval < 2592000 {
            return "\(Int(interval / 86400))天前"
        } else {
            formatter.dateFormat = "MM-dd"
            return formatter.string(from: date)
        }
    }
}
