import { XEUtils } from '@eciol/ant-ui'; import { DictionaryService } from '@eciol/api'; import { useLocale } from '@eciol/locale'; import { LOCALE } from '@eciol/shared'; import { useUserStore } from '@/store'; /** * 从缓存中获取字典配置 * @param code */ const getDictItemsByCode = (code: DictionaryService.DatadictsFields, numberToString = true) => { const userStore = useUserStore(); const dictItems = userStore.getAllDictItems; if (typeof dictItems === 'object' && dictItems[code]) { return dictItems[code].map((item) => ({ label: item.name, value: numberToString ? item.code.toString() : XEUtils.toNumber(item.code), })); } return []; }; /** * 获取字典数组 * @param dictCode 字典Code * @return List */ const initDictOptions = ( code: DictionaryService.DatadictsFields, numberToString = true, joinAllOptions = false, ) => { // 优先从缓存中读取字典配置 if (getDictItemsByCode(code)) { const dict = getDictItemsByCode(code, numberToString); const { getLocale } = useLocale(); if (joinAllOptions) { dict.unshift({ label: (getLocale.value === LOCALE.ZH_CN ? '全部' : 'All') as string, value: '', }); } return dict; } return []; }; /** * 通过字典翻译字段值对应的文本 * @param dictCode 字典code * @param key 字段 * @returns string */ function filterDictTextByCache(dictCode: DictionaryService.DatadictsFields, key) { if (key == null || key.length === 0) { return; } if (!dictCode) { return '字典Code不能为空!'; } //优先从缓存中读取字典配置 if (getDictItemsByCode(dictCode)) { const item = getDictItemsByCode(dictCode).filter((t) => t['value'] == key); if (item && item.length > 0) { return item[0]['label']; } } } /** * 字典值替换文本通用方法 * @param dictOptions 字典数组 * @param text 字典值 * @return String */ function filterDictText( dictOptions: any[], text: string | number | (string | number)[], labelField = 'label', ) { // 字典翻译 text 允许逗号分隔 if (text != null && Array.isArray(dictOptions)) { const result: string[] = []; // 允许多个逗号分隔,允许传数组对象 let splitText; if (Array.isArray(text)) { splitText = text; } else { splitText = text.toString().trim().split(','); } for (const txt of splitText) { let dictText = txt; for (const dictItem of dictOptions) { if (txt.toString() === dictItem.value.toString()) { dictText = dictItem[labelField] || dictItem.text || dictItem.title || dictItem.label; break; } } result.push(dictText); } return result.join(','); } return text; } export { filterDictText, filterDictTextByCache, getDictItemsByCode, initDictOptions };