import NProgress from 'nprogress'
import { defineStore } from 'pinia'
import { getConfigInfo } from '@/api/config'

export const useConfigStore = defineStore('config', () => {
  const config = ref<Record<string, any>>({})
  const routeRefreshTag = ref<boolean>(true)
  const sideCollapsed = ref<boolean>(false)
  const sideDrawerShow = ref<boolean>(false)
  const windowSizeLevel = ref<number>(0)

  // 获取应用配置
  const getConfig = async () => {
    return new Promise((resolve, reject) => {
      getConfigInfo()
        .then((data) => {
          config.value = data || {}
          resolve(data)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  // 刷新视图
  const refreshRouterView = () => {
    routeRefreshTag.value = false
    NProgress.start()
    nextTick(() => {
      routeRefreshTag.value = true
      NProgress.done()
    })
  }

  // 切换折叠状态
  const toggleCollapsed = (toggle?: boolean) => {
    sideCollapsed.value = toggle ?? !sideCollapsed.value
  }

  // 切换抽屉显示状态
  const toggleDrawerShow = (toggle?: boolean) => {
    sideDrawerShow.value = toggle ?? !sideDrawerShow.value
  }

  // 切换窗口尺寸级别
  const toggleWindowSizeLevel = (level: number) => {
    windowSizeLevel.value = level
  }

  return {
    config,
    routeRefreshTag,
    sideCollapsed,
    sideDrawerShow,
    windowSizeLevel,
    getConfig,
    refreshRouterView,
    toggleCollapsed,
    toggleDrawerShow,
    toggleWindowSizeLevel
  }
})
