import Vue from 'vue'
import api from '@/api'

const state = {
  dict: {},
  queue: []
}
const mutations = {
  SET_DICT: (state, { type, list }) => {
    // 设置值:注意得用Vue.set方法
    Vue.set(state.dict, type, list)
  },
  SET_QUEUE: (state, type) => {
    state.queue.push(type)
  },
  DEL_QUEUE: (state, type) => {
    // 找到并删除
    for (let i = 0; i < state.queue.length; i++) {
      const item = state.queue[i]
      if (item === type) {
        state.queue.splice(i, 1)
        break
      }
    }
  }
}
const actions = {
  async getDictByType ({ dispatch, state }, type) {
    /**
     * 闭包特性。返回一个函数,该函数接收一个type参数。
     * 同时由于闭包还持有state对象,故可以返回需要的值。
     */
    await dispatch('dict', type)
    var obj = JSON.parse(JSON.stringify(state.dict[type]))
    return obj
  },
  // 缓存字典内容
  dict ({ commit, state }, type) {
    // 判断是否已经缓存过,缓存过后将不再获取数据
    const isExistence = state.queue.some((item) => {
      return item === 'dict/' + type
    })
    // 没有缓存则请求数据
    if (!isExistence) {
      // 在异步请求之前将该任务标记为已缓存(存入队列)
      this.commit('cache/SET_QUEUE', 'dict/' + type)
      return new Promise(async (resolve, reject) => {
        await api.parameter.getArrayListByType({ typeId: type })
          .then(({ data = {} }) => {
            if (data) {
              try {
                this.commit('cache/SET_DICT', { type: type, list: data })
                resolve(data)
              } catch (error) {
                reject(error)
              }
            } else {
              reject('error')
            }
          }).catch(err => {
            // 获取失败移除缓存队列
            this.commit('cache/DEL_QUEUE', 'dict/' + type)
            reject(err.response)
          })
      })
    } else {
      return state.dict[type]
    }
  }
}

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