import dictEnum from '@/enum/dict';
import Vue from 'vue';
import { getByCode } from '@/api/system/dictionary-data';
//非枚举定义
const otherDictConfig = {
  //   [dictEnum.类型用途]: {
  //     request: getSubListByParentId,
  //     dictCode: 'type',
  //     dictValue: 'name',
  //     resKey: '' //为空选 data
  //   }
};

const state = {};

const mutations = {
  //根据字典code 添加字典
  ADD_DICT: (state, { code, dict }) => {
    Vue.set(state, code, dict);
  }
};

const actions = {
  // 根据字典enumName请求字典 已获取的不做重复请求
  async requestDict({ commit, state }, enumName) {
    const code = dictEnum[enumName];

    if (state[code]?.length) return state[code];
    let res;
    if (otherDictConfig[dictEnum[enumName]]) {
      const config = otherDictConfig[dictEnum[enumName]];
      console.log(config);
      //非枚举定义
      res = await config.request();
      if (res?.code == 0) {
        let list = config.resKey ? res.data[config.resKey] : res.data;
        commit('ADD_DICT', {
          code,
          dict: list.map((item) => ({
            ...item,
            dictCode: item[config.dictCode],
            dictValue: item[config.dictValue]
          }))
        });
        return res.list;
      }
    } else {
      res = await getByCode(code);
      if (res?.code == 0) {
        commit('ADD_DICT', {
          code,
          dict: res.data.map((item) => {
            const arr = Object.entries(item)[0] || [];

            return {
              dictCode: arr[0],
              dictValue: arr[1]
            };
          })
        });
        return res.data;
      }
    }

    return [];
  },
  // 更新字典
  async reloadRequestDict({ commit }, enumName) {
    const code = dictEnum[enumName];
    const res = await getByCode(code);
    if (res?.code == 0) {
      commit('ADD_DICT', {
        code,
        dict: res.data.map((item) => {
          const arr = Object.entries(item);

          return {
            dictCode: arr[0],
            dictValue: arr[1]
          };
        })
      });
      return res.data;
    }

    return [];
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
