import {listDictDataAll} from "../../api/system/dict/data";

const state = {
  dict: new Array(),
  dictMap:{}
}
const mutations = {
  SET_DICT: (state, { key, value }) => {
    if (key !== null && key !== "") {
      state.dict.push({
        key: key,
        value: value
      })
    }
  },
  SET_DICT_MAP: (state, { key, value }) => {
    if (key !== null && key !== "") {
      state.dictMap[key] = value
    }
  },
  REMOVE_DICT: (state, key) => {
    try {
      for (let i = 0; i < state.dict.length; i++) {
        if (state.dict[i].key == key) {
          state.dict.splice(i, 1)
          return true
        }
      }
    } catch (e) {
    }
  },
  CLEAN_DICT: (state) => {
    state.dict = new Array()
  }
}

const actions = {
  // 设置字典
  setDict({ commit }, data) {
    commit('SET_DICT', data)
    commit('SET_DICT_MAP', data)
  },
  // 删除字典
  removeDict({ commit }, key) {
    commit('REMOVE_DICT', key)
  },
  // 清空字典
  cleanDict({ commit }) {
    commit('CLEAN_DICT')
  },
  // 加载字典数据
  GetDicts({commit}) {
    return new Promise((resolve, reject) => {
      listDictDataAll().then(res => {
        commit('SET_DICT', res.data)
        commit('SET_DICT_MAP', res.data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

}

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

