import config from '@/config/defaultSetting'
import colorUtil from '@/utils/color'
import { themeStyleList } from '@/utils/constants'

export const useThemeStore = defineStore('theme', () => {
  const themeColor = useStorage('themeColor', config.themeColor)
  const themeStyleName = useStorage('themeStyle', config.themeStyle)
  const themeStyle = computed(
    () => themeStyleList.find(item => item.name === themeStyleName.value) || themeStyleList[0]
  )

  const setThemeColor = (color: string) => {
    themeColor.value = color
    initThemeColor()
  }
  const initThemeColor = () => {
    const primary = themeColor.value
    document.documentElement.style.setProperty('--el-color-primary', primary)
    for (let i = 1; i <= 9; i++) {
      document.documentElement.style.setProperty(`--el-color-primary-light-${i}`, colorUtil.lighten(primary, i / 10))
    }
    for (let i = 1; i <= 9; i++) {
      document.documentElement.style.setProperty(`--el-color-primary-dark-${i}`, colorUtil.darken(primary, i / 10))
    }
  }

  const setThemeStyle = (style: string) => {
    themeStyleName.value = style
    initThemeStyle()
  }
  const initThemeStyle = () => {
    const style = themeStyle.value
    document.documentElement.style.setProperty('--el-menu-bg-color', style.bgColor)
    document.documentElement.style.setProperty('--el-menu-text-color', style.textColor)
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    document.querySelector('html')!.className = style.name
  }

  // 导航栏模式
  const themeNav = useStorage('themeNav', config.themeNav)
  const setThemeNav = (name: string) => {
    themeNav.value = name
  }

  // 界面显示
  const showTabs = useStorage('showTabs', config.showTabs)
  const keepAliveTabs = useStorage('keepAliveTabs', config.keepAliveTabs)
  const logoInHeader = useStorage('logoInHeader', config.logoInHeader)

  const initTheme = () => {
    initThemeColor()
    initThemeStyle()
  }

  return {
    themeColor,
    setThemeColor,
    initThemeColor,
    themeStyle,
    setThemeStyle,
    initThemeStyle,
    themeNav,
    setThemeNav,
    initTheme,
    showTabs,
    keepAliveTabs,
    logoInHeader
  }
})
