import apis from "../api" const DICT_KEY = "DICK_CACHE" export const useDictStore = defineStore("dict", () => { const dictArr = ref(localCache.getJSON(DICT_KEY) || []) // 获取字典 function getDict(key: string) { return new Promise((resolve, reject) => { if (key == null && key == "") { reject(new Error("Key 不能为空")) return } let item = dictArr.value?.find((v) => v.key == key) if (item == null) { apis.system.dictApi.getDicts(key).then((res: any) => { if (res.code == 200) { item = formatterDict(key, res.data) resolve(item) } else { reject(res.message) } }) } else { resolve(item.value) } }) } function setDict(key: string, value: string) { if (key !== null && key !== "") { dictArr.value = dictArr.value || [] dictArr.value.push({ key, value }) localCache.setJSON(DICT_KEY, dictArr.value) } } function removeDict(key: string) { const index = dictArr.value.findIndex((v) => { return v.key == key }) if (index > 0) { dictArr.value.splice(index, 1) } } function formatterDict(key: string, data: any, custFormat?: (v: any) => any) { // console.log("DATA", data) let dict: any = {} if (data?.length) { dict = data.map((p: any) => ({ label: p.dictLabel, value: p.dictValue, elTagType: p.listClass, elTagClass: p.cssClass })) setDict(key, dict) if (custFormat) { dict = custFormat(data) } } return dict } // 清空字典 function cleanDict() { return new Promise((resolve, reject) => { apis.system.dictApi .refreshCache() .then(() => { dictArr.value = [] localCache.setJSON(DICT_KEY, []) resolve("") }) .catch((e) => { reject(e) }) }) } function initDict() { dictArr.value = localCache.getJSON(DICT_KEY) if (dictArr.value && dictArr.value.length > 0) { return } apis.system.dictApi.listAllType().then((res: any) => { if (res.code == 200) { res.data.forEach((v: any) => { getDict(v.dictType) }) } }) } return { getDict, setDict, removeDict, cleanDict, formatterDict, initDict } })