import Vue from 'vue'

import Cookies from 'js-cookie'

import Element from 'element-ui'
import './assets/styles/element-variables.scss'

import '@/assets/styles/index.scss' // global css
import '@/assets/styles/ruoyi.scss' // ruoyi css
// 自定义设计系统样式 - 在最后引入以确保覆盖优先级
import '@/styles/tokens.scss' // 设计令牌
import '@/styles/overrides-element.scss' // Element UI 主题覆盖
import App from './App'
import store from './store'
import router from './router'
import directive from './directive' // directive
import plugins from './plugins' // plugins
import { download } from '@/utils/request'

import './assets/icons' // icon
import './permission' // permission control
import { getDicts } from "@/api/system/dict/data";
import { getConfigKey } from "@/api/system/config";
import { parseTime, resetForm, addDateRange, selectDictLabel, selectDictLabels, handleTree } from "@/utils/ruoyi";
// 分页组件
import Pagination from "@/components/Pagination";
// 自定义表格工具组件
import RightToolbar from "@/components/RightToolbar"
// 富文本组件
import Editor from "@/components/Editor"
// 文件上传组件
import FileUpload from "@/components/FileUpload"
// 图片上传组件
import ImageUpload from "@/components/ImageUpload"
// 图片预览组件
import ImagePreview from "@/components/ImagePreview"
// 字典标签组件
import DictTag from '@/components/DictTag'
// 头部标签组件
import VueMeta from 'vue-meta'
// 字典数据组件
import DictData from '@/components/DictData'

// 全局方法挂载
Vue.prototype.getDicts = getDicts
Vue.prototype.getConfigKey = getConfigKey
Vue.prototype.parseTime = parseTime
Vue.prototype.resetForm = resetForm
Vue.prototype.addDateRange = addDateRange
Vue.prototype.selectDictLabel = selectDictLabel
Vue.prototype.selectDictLabels = selectDictLabels
Vue.prototype.download = download
Vue.prototype.handleTree = handleTree

// 全局组件挂载
Vue.component('DictTag', DictTag)
Vue.component('Pagination', Pagination)
Vue.component('RightToolbar', RightToolbar)
Vue.component('Editor', Editor)
Vue.component('FileUpload', FileUpload)
Vue.component('ImageUpload', ImageUpload)
Vue.component('ImagePreview', ImagePreview)

Vue.use(directive)
Vue.use(plugins)
Vue.use(VueMeta)
DictData.install()

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online! ! !
 */

Vue.use(Element, {
  size: Cookies.get('size') || 'medium' // set element-ui default size
})

Vue.config.productionTip = false

// 主题切换功能
const THEME_KEY = 'xt-theme'
const THEME_DARK = 'dark'
const THEME_LIGHT = 'light'
const THEME_AUTO = 'auto'

/**
 * 获取存储的主题
 */
function getStoredTheme() {
  try {
    return localStorage.getItem(THEME_KEY) || THEME_AUTO
  } catch (error) {
    console.warn('无法访问 localStorage:', error)
    return THEME_AUTO
  }
}

/**
 * 存储主题设置
 */
function setStoredTheme(theme) {
  try {
    localStorage.setItem(THEME_KEY, theme)
  } catch (error) {
    console.warn('无法保存主题设置:', error)
  }
}

/**
 * 获取系统主题偏好
 */
function getSystemTheme() {
  if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    return THEME_DARK
  }
  return THEME_LIGHT
}

/**
 * 获取实际应用的主题
 */
function getEffectiveTheme(theme) {
  if (theme === THEME_AUTO) {
    return getSystemTheme()
  }
  return theme
}

/**
 * 应用主题到 DOM
 */
function applyTheme(theme) {
  const effectiveTheme = getEffectiveTheme(theme)
  const htmlElement = document.documentElement
  
  // 移除所有主题类
  htmlElement.classList.remove(THEME_DARK, THEME_LIGHT)
  
  // 应用新主题
  if (effectiveTheme === THEME_DARK) {
    htmlElement.classList.add(THEME_DARK)
  }
  
  // 设置主题属性
  htmlElement.setAttribute('data-theme', effectiveTheme)
  
  // 触发自定义事件
  const event = new CustomEvent('theme-changed', {
    detail: {
      theme: theme,
      effectiveTheme: effectiveTheme,
      isDark: effectiveTheme === THEME_DARK,
      isLight: effectiveTheme === THEME_LIGHT,
      isAuto: theme === THEME_AUTO
    }
  })
  window.dispatchEvent(event)
}

/**
 * 切换主题（在明暗主题间切换）
 */
function toggleTheme() {
  const currentTheme = getStoredTheme()
  const currentEffective = getEffectiveTheme(currentTheme)
  const newTheme = currentEffective === THEME_DARK ? THEME_LIGHT : THEME_DARK
  
  setStoredTheme(newTheme)
  applyTheme(newTheme)
  
  console.log(`主题已切换: ${currentEffective} -> ${newTheme}`)
}

/**
 * 设置指定主题
 */
function setTheme(theme) {
  if (![THEME_LIGHT, THEME_DARK, THEME_AUTO].includes(theme)) {
    console.warn('无效的主题名称:', theme)
    return
  }
  
  setStoredTheme(theme)
  applyTheme(theme)
  
  console.log(`主题已设置: ${theme}`)
}

/**
 * 获取当前主题
 */
function getCurrentTheme() {
  return getStoredTheme()
}

/**
 * 是否为暗色主题
 */
function isDarkTheme() {
  const theme = getStoredTheme()
  return getEffectiveTheme(theme) === THEME_DARK
}

// 挂载主题切换功能到 window
window.toggleTheme = toggleTheme
window.setTheme = setTheme
window.getCurrentTheme = getCurrentTheme
window.isDarkTheme = isDarkTheme

// 监听系统主题变化
if (window.matchMedia) {
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  mediaQuery.addEventListener('change', function() {
    const currentTheme = getStoredTheme()
    if (currentTheme === THEME_AUTO) {
      applyTheme(THEME_AUTO)
    }
  })
}

// 初始化主题
const initialTheme = getStoredTheme()
applyTheme(initialTheme)

// 在控制台输出主题状态（开发环境）
if (process.env.NODE_ENV === 'development') {
  console.log('🎨 主题系统已初始化')
  console.log('当前主题:', initialTheme)
  console.log('实际主题:', getEffectiveTheme(initialTheme))
  console.log('可用方法: window.toggleTheme(), window.setTheme(theme), window.getCurrentTheme(), window.isDarkTheme()')
  console.log('支持的主题: "light", "dark", "auto"')
}

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})