import { defineStore } from "pinia"
import { store } from "../index"
import { getDictionary } from "@/api/user.api"
import { httpAjax } from "@/plugin/httpAjax"

const useStore = defineStore("dictionaryCache", {
   state: (): { cache: Map<string, any[]> } => {
      return {
         //字典缓存区
         cache: new Map()
      }
   },
   actions: {
      async getDictionary(key: string) {
         //有缓存取缓存 没缓存ajax 取值
         const cache = this.cache
         if (cache.has(key)) {
            return cache.get(key)
         } else {
            const dictionaryRes = await httpAjax(getDictionary, key)
            if (dictionaryRes.code === 200) {
               this.cache.set(key, dictionaryRes.data)
               return dictionaryRes.data
            }
            return []
         }
      }
   }
})

export default () => {
   return useStore(store)
}
