import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useThemeStore = defineStore('theme', () => {
  // 可用主题列表
  const themes = ref({
    default: {
      '--primary-color': '#1890ff',
      '--bg-color': '#f8f9fa',
      '--text-color': '#333',
      '--card-bg': '#ffffff'
    },
    aydzBlue: {
      '--primary-color': '#2a5caa',
      '--bg-color': '#e6f7ff',
      '--text-color': '#1a3353',
      '--card-bg': '#d0e8ff'
    },
    darkMode: {
      '--primary-color': '#52c41a',
      '--bg-color': '#1a1a1a',
      '--text-color': '#e6e6e6',
      '--card-bg': '#2a2a2a'
    }
  })
  
  // 当前主题
  const currentTheme = ref('aydzBlue')
  
  // 初始化主题
  const initTheme = () => {
    const savedTheme = uni.getStorageSync('selectedTheme') || 'aydzBlue'
    setTheme(savedTheme)
  }
  
  // 设置主题
  const setTheme = (themeName) => {
    if (!themes.value[themeName]) return
    
    currentTheme.value = themeName
    uni.setStorageSync('selectedTheme', themeName)
    
    // 应用CSS变量
    const root = document.documentElement
    const themeVars = themes.value[themeName]
    
    Object.keys(themeVars).forEach(key => {
      root.style.setProperty(key, themeVars[key])
    })
    
    // 动态设置导航栏颜色
    if (themeName === 'darkMode') {
      uni.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#1a1a1a'
      })
    } else if (themeName === 'aydzBlue') {
      uni.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#2a5caa'
      })
    } else {
      uni.setNavigationBarColor({
        frontColor: '#000000',
        backgroundColor: '#f8f9fa'
      })
    }
  }
  
  // 主题配置（用于UI显示）
  const themeOptions = computed(() => {
    return Object.keys(themes.value).map(key => ({
      name: key,
      label: getThemeLabel(key),
      colors: themes.value[key]
    }))
  })
  
  // 获取主题显示名称
  const getThemeLabel = (themeKey) => {
    const labels = {
      default: '默认主题',
      aydzBlue: '哎呀科技蓝',
      darkMode: '深色模式'
    }
    return labels[themeKey] || themeKey
  }

  return { 
    themes,
    currentTheme,
    themeOptions,
    initTheme,
    setTheme,
    getThemeLabel
  }
})