import { getSysDictApi } from '#/api/modules/sys-dict'
import obj from '#/utils/obj'

export type MapAndOptions = {
  map: Record<any, any>
  options: {
    label: any
    value: any
  }[]
}

export const useSysDictStore = defineStore('sys-dict', () => {
  const sysDictMap = {} as Record<string, MapAndOptions>

  const getSysDict = async (code: any) => {
    let data = sysDictMap[code]
    if (!data) {
      const res = (await getSysDictApi(code)) as any[]
      const map = res?.reduce((prev: any, cur: any) => {
        prev[cur.code] = cur.value
        return prev
      }, {})
      const options = obj.map2options(map)
      data = {
        map,
        options,
      }
      sysDictMap[code] = data
    }
    return data
  }

  const $reset = () => {}

  return {
    getSysDict,
    $reset,
  }
})
