import './assets/main.css'
import './styles/index.scss'
import './styles/icons/iconfont.js'
import VXETable from 'vxe-table'
import 'vxe-table/lib/style.css'
import enUS from 'vxe-table/lib/locale/lang/en-US'
import VxeUI from 'vxe-pc-ui'
import 'element-plus/dist/index.css'
import 'vxe-pc-ui/lib/style.css'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/reset.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import VXETablePluginExportXLSX from 'vxe-table-plugin-export-xlsx'
import ExcelJS from 'exceljs'
import { VLoading } from './directive/VLoading'

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'
import { useThemeStore } from '@/stores/modules/theme'

const app = createApp(App)

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
// 让VxeTable支持导出Excel
VXETable.use(VXETablePluginExportXLSX, {
  ExcelJS
})
VXETable.setI18n('en-US', enUS)
VXETable.setLanguage('en-US')

app.use(createPinia())
app.use(VXETable)
app.use(VxeUI)
app.use(router)
app.use(Antd)

// 注册全局指令
app.directive('vloading', VLoading)

const themeStore = useThemeStore()

// 动态加载暗黑主题
async function loadDarkTheme() {
  await import('element-plus/theme-chalk/dark/css-vars.css') // 动态导入暗黑主题
}
// 动态移除暗黑主题
function unloadDarkTheme() {
  const darkThemeStylesheet = document.getElementById('dark-theme-style')
  if (darkThemeStylesheet) {
    darkThemeStylesheet.remove()
  }
}
// 用户没有手动切换主题时，根据系统设置自动切换
if (!themeStore.isManualChange) {
  // 根据用户偏好或系统设置决定是否添加暗黑模式类名
  if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    themeStore.toggleTheme('dark')
    loadDarkTheme()
  } else {
    unloadDarkTheme()
    themeStore.toggleTheme('light')
  }
} else {
  // 用户手动切换主题时，根据用户设置切换
  if (themeStore.theme === 'dark') {
    loadDarkTheme()
    themeStore.toggleTheme('dark')
  }
}

// 提供一个全局方法来切换主题
app.config.globalProperties.$toggleDarkMode = () => {
  const html = document.documentElement
  if (html.classList.contains('dark')) {
    unloadDarkTheme()
    html.classList.remove('dark')
    localStorage.setItem('theme', 'light')
  } else {
    loadDarkTheme()
    html.classList.add('dark')
    localStorage.setItem('theme', 'dark')
  }
}

app.mount('#app')