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
}

export const useAsideConfigStore = defineStore({
  id: 'app-config',
  state: (): ConfigState => ({
    systemConfig: null,
    customConfig: null,
    asideValue: null,
  }),
  getters: {
    getConfig(): AsideConfig | null {
      return this.systemConfig
    },
    getCustomConfig(): string[] | null {
      return this.customConfig
    },
    getAsideValue(): any {
      return this.asideValue
    },
  },
  actions: {
    setConfig(config: AsideConfig) {
      this.systemConfig = config
    },
    setAsideValue(value) {
      this.asideValue = 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)
}
