广丰卷烟厂数采质量分析系统
zhuguifei
2026-03-02 80ff784bf60637cd348ae665fc907f7b1e527dd8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { fetchGetDictDataByType } from '@/service/api/system';
import { useDictStore } from '@/store/modules/dict';
import { isNull } from '@/utils/common';
import { $t } from '@/locales';
 
export function useDict(dictType: string, immediate: boolean = true) {
  const dictStore = useDictStore();
  const { dictData: dictList } = storeToRefs(dictStore);
 
  const data = ref<Api.System.DictData[]>([]);
  const record = ref<Record<string, string>>({});
  const options = ref<CommonType.Option[]>([]);
 
  async function getData() {
    const dicts = dictStore.getDict(dictType);
    if (dicts) {
      data.value = dicts;
      return;
    }
    const { data: dictData, error } = await fetchGetDictDataByType(dictType);
    if (error) return;
    dictData.forEach(dict => {
      if (dict.dictLabel?.startsWith(`dict.${dictType}.`)) {
        dict.dictLabel = $t(dict.dictLabel as App.I18n.I18nKey);
      }
    });
    dictStore.setDict(dictType, dictData);
    data.value = dictData;
  }
 
  async function getRecord() {
    if (!data.value.length) {
      await getData();
    }
    data.value.forEach(dict => {
      record.value[dict.dictValue!] = dict.dictLabel!;
    });
  }
 
  async function getOptions() {
    if (!data.value.length) {
      await getData();
    }
 
    options.value = data.value.map(dict => ({ label: dict.dictLabel!, value: dict.dictValue! }));
  }
 
  function transformDictData(dictValue: string[] | number[] | string | number) {
    if (!data.value.length || isNull(dictValue)) return undefined;
    if (Array.isArray(dictValue)) {
      return data.value.filter(dict => dictValue.some(value => dict.dictValue === value.toString()));
    }
    return data.value.filter(dict => dict.dictValue === dictValue.toString());
  }
 
  if (immediate) {
    getData().then(() => {
      getRecord();
      getOptions();
    });
  } else {
    watch(
      () => dictList.value[dictType],
      val => {
        if (val && val.length) {
          getRecord();
          getOptions();
        }
      },
      { immediate: true }
    );
  }
 
  return {
    data,
    record,
    options,
    getData,
    getRecord,
    getOptions,
    transformDictData
  };
}