import { defineStore } from 'pinia'
import { store } from '@/store'
import { getConfig } from '@/api/system/user'

import { getFilter } from '@/api/home/filter'
import type { AsideConfig } from '/#/api'

export interface ConfigState {
  systemConfig: AsideConfig | null
  customConfig: string[] | null
  asideValue: any
  searchValue: string
  isAllowDownload: boolean
  timeNum: number
}

export const useAsideConfigStore = defineStore({
  id: 'app-config',
  state: (): ConfigState => ({
    systemConfig: null,
    customConfig: null,
    asideValue: null,
    searchValue: "",
    isAllowDownload: true,
    timeNum: 0,
  }),
  getters: {
    getConfig(): AsideConfig | null {
      return this.systemConfig
    },
    getCustomConfig(): string[] | null {
      return this.customConfig
    },
    getAsideValue(): any {
      return this.asideValue
    },
    getSearchValue(): any {
      return this.searchValue
    },
    getIsAllowDownload(): any {
      return this.isAllowDownload
    },
    getTimeNum(): any {
      return this.timeNum
    },
  },
  actions: {
    setConfig(config: AsideConfig) {
      this.systemConfig = config
    },
    setAsideValue(value) {
      this.asideValue = value
    },
    setSearchValue(value) {
      this.searchValue = value
    },
    setIsAllowDownload(value) {
      this.isAllowDownload = value
    },
    setTimeNum(value) {
      this.timeNum = value
    },
    // 设置个性化配置
    setCustomConfig(value) {
      this.customConfig = value
    },
    // 获取系统配置信息
    async fetchConfig() {
      const response = await getConfig()
      this.setConfig(response.data)
      return response.data
    },
    // 获取个性化配置
    async fetchCustomConfig() {
      const res = await getFilter(0)
      const { data } = res
      const list = data && data.searchcount ? data.searchcount.split(',') : []
      this.customConfig = list
      return list
    },
  },
})

// Need to be used outside the setup
export function useConfig() {
  return useAsideConfigStore(store)
}
