import useDictStore from '@/store/modules/dict'
import { getDicts } from '@/api/system/dict/data'
import request from "@/utils/request.js";

export const DICT_TYPE = {
  TRADE_INVOICE_STATUS: 'trade_invoice_status'
}

/**
 * 获取 dictType 对应的数据字典数组
 */
export const getDictOptions = (dictType) => {
  const dicts = useDictStore().getDict(dictType);
  return dicts || [];
}

export const getIntDictOptions = (dictType) => {
  const dictOptions = getDictOptions(dictType);
  return dictOptions.map(dict => ({
    ...dict,
    value: parseInt(dict.value)
  }));
}

export const getStrDictOptions = (dictType) => {
  const dictOptions = getDictOptions(dictType);
  return dictOptions.map(dict => ({
    ...dict,
    value: dict.value + ''
  }));
}

/**
 * 获取字典数据
 */
export function useDict(...args) {
  const res = ref({});
  return (() => {
    args.forEach((dictType, index) => {
      res.value[dictType] = [];
      const dicts = useDictStore().getDict(dictType);
      if (dicts) {
        res.value[dictType] = dicts;
      } else {
        getDicts(dictType).then(resp => {
          res.value[dictType] = resp.data.map(p => ({ label: p.label, value: p.value, elTagType: p.elTagType, elTagClass: p.elTagClass }))
          useDictStore().setDict(dictType, res.value[dictType]);
        })
      }
    })
    return toRefs(res.value);
  })()
}

export function getDictDatas(dictType) {
    return request({
        url: '/biz/dict/getByType',
        method: 'get',
        params: {dictType}
    });
}