import { ref, computed } from 'vue'
import { useI18n } from '#imports'

// 静态数据缓存
let staticDataCache = null

// 获取静态数据
const getStaticData = () => {
  if (staticDataCache) {
    return staticDataCache
  }
  
  try {
    // 在客户端环境下，从window对象获取预渲染的数据
    if (typeof window !== 'undefined' && window.__NUXT_STATIC_DATA__) {
      staticDataCache = window.__NUXT_STATIC_DATA__
      return staticDataCache
    }
    
    // 在服务端环境下，尝试读取静态数据文件
    if (typeof window === 'undefined') {
      const fs = require('fs')
      const path = require('path')
      const dataPath = path.join(process.cwd(), 'src', 'static-data', 'api-data.json')
      
      if (fs.existsSync(dataPath)) {
        const data = JSON.parse(fs.readFileSync(dataPath, 'utf8'))
        staticDataCache = data
        return data
      }
    }
    
    return null
  } catch (error) {
    console.warn('获取静态数据失败:', error)
    return null
  }
}

// 使用静态数据的composable
export const useStaticData = () => {
  const { locale } = useI18n()
  
  // 获取当前语言的数据
  const getCurrentLocaleData = computed(() => {
    const data = getStaticData()
    return data ? data[locale.value] || data.en : null
  })
  
  // 轮播图数据
  const carouselData = computed(() => {
    const data = getCurrentLocaleData.value
    return data?.carousel?.rows || []
  })
  
  // 产品分类数据
  const categoryData = computed(() => {
    const data = getCurrentLocaleData.value
    return data?.categories?.rows || []
  })
  
  // 产品列表数据
  const productData = computed(() => {
    const data = getCurrentLocaleData.value
    return data?.products?.rows || []
  })
  
  // 新闻数据
  const newsData = computed(() => {
    const data = getCurrentLocaleData.value
    return data?.news?.rows || []
  })
  
  // 证书数据
  const certificateData = computed(() => {
    const data = getCurrentLocaleData.value
    return data?.certificates?.rows || []
  })
  
  // APP下载数据
  const downloadData = computed(() => {
    const data = getCurrentLocaleData.value
    return data?.downloads?.rows || []
  })
  
  // 检查是否有静态数据
  const hasStaticData = computed(() => {
    return !!getStaticData()
  })
  
  return {
    carouselData,
    categoryData,
    productData,
    newsData,
    certificateData,
    downloadData,
    hasStaticData,
    getCurrentLocaleData
  }
}
