/**
 * 数据管理器 - 用于加载和管理JSON配置数据
 */
class DataManager {
  constructor() {
    this.data = null
    this.loadPromise = null
  }

  /**
   * 加载数据配置文件
   */
  async loadData() {
    if (this.loadPromise) {
      return this.loadPromise
    }

    this.loadPromise = this._fetchData()
    return this.loadPromise
  }

  async _fetchData() {
    try {
      console.log('正在加载数据配置文件: /data-config.json')
      const response = await fetch('/data-config.json')
      console.log('响应状态:', response.status, response.statusText)
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`)
      }
      
      const text = await response.text()
      console.log('响应内容长度:', text.length)
      
      this.data = JSON.parse(text)
      console.log('数据配置加载成功:', this.data)
      console.log('realTimeStats数据:', this.data.realTimeStats)
      return this.data
    } catch (error) {
      console.error('加载数据配置失败:', error)
      console.error('错误详情:', error.message)
      console.log('使用默认数据')
      // 返回默认数据
      this.data = this.getDefaultData()
      return this.data
    }
  }

  /**
   * 获取指定模块的数据
   */
  getData(moduleName) {
    if (!this.data) {
      console.warn('数据尚未加载，请先调用 loadData()')
      return null
    }
    return this.data[moduleName] || null
  }

  /**
   * 获取所有数据
   */
  getAllData() {
    return this.data
  }

  /**
   * 重新加载数据（用于热更新）
   */
  async reloadData() {
    this.loadPromise = null
    this.data = null
    return await this.loadData()
  }

  /**
   * 默认数据配置（当加载失败时使用）
   */
  getDefaultData() {
    return {
      realTimeStats: {
        yakTotalVolume: 0,
        orderTotalVolume: 0,
        sellerCount: 0,
        buyerCount: 0,
        systemStatus: "系统异常"
      },
      yakTradingData: {
        totalCount: 0,
        avgPrice: 0,
        monthlyGrowth: 0,
        topRegion: "暂无数据"
      },
      countySalesStats: [],
      yakPriceTrend: {
        months: [],
        prices: [],
        volumes: []
      },
      chinaMapData: [],
      exchangeMonitor: {
        onlineUsers: 0,
        activeTransactions: 0,
        systemLoad: 0,
        networkStatus: "未知"
      },
      yakSalesTypeStats: [],
      purchaserAnalysis: [],
      marketEnvironment: {
        temperature: "--",
        humidity: "--",
        airQuality: "--",
        weather: "--"
      },
      marketRealtime: {
        currentPrice: 0,
        priceChange: "0%",
        volume: 0,
        volumeChange: "0%",
        lastUpdate: "--"
      },
      supplyDemandData: {
        supply: { total: 0, available: 0, reserved: 0 },
        demand: { total: 0, pending: 0, matched: 0 },
        ratio: 0
      },
      transactionDetails: [],
      announcements: ["暂无公告"]
    }
  }

  /**
   * 格式化数字显示
   */
  formatNumber(num, decimals = 0) {
    if (typeof num !== 'number') return num
    return num.toLocaleString('zh-CN', {
      minimumFractionDigits: decimals,
      maximumFractionDigits: decimals
    })
  }

  /**
   * 格式化百分比
   */
  formatPercentage(num, decimals = 1) {
    if (typeof num !== 'number') return num
    return `${num.toFixed(decimals)}%`
  }

  /**
   * 格式化金额
   */
  formatCurrency(amount, unit = '万元') {
    if (typeof amount !== 'number') return amount
    return `${this.formatNumber(amount, 1)}${unit}`
  }
}

// 创建单例实例
export const dataManager = new DataManager()

// 导出类供其他地方使用
export default DataManager 