import request from './request'

// 获取字典
export async function getDict(key) {
  const params = {
    dictType: key,
    pageSize: 999,
    pageNum: 1
  }
  try {
    const { data } = await request.get('/admin-api/system/dict-data/page', { params })
    return data
  } catch (error) {
    throw error;
  }
}

// 返回字典值
export async function getDictLabel(dict, value, locale, key = 'value') {
  const dictKeys = locale === 'zh' ? 'label' : 'labelEn';

  const findLabel = (list) => {
    const item = list.find(item => item[key] === value);
    return item ? item[dictKeys] : '';
  };

  if (Array.isArray(dict)) {
    return findLabel(dict);
  } else if (typeof dict === 'string') {
    try {
      const { list } = await getDict(dict);
      return findLabel(list);
    } catch (error) {
      throw error;
    }
  }
  return '';
}
