import {
  getDictTree
} from '@/api/dict'
import {
  getCulturalRelicList
} from '@/api/culturalRelic'
const state = {
  dicts: {},
  crList: [] //文物列表，布展关联文物时使用
};

const mutations = {
  SET_DICTS(state, obj) {
    state.dicts[obj.label] = obj.value;
  },
  SET_CR_LIST(state, crList) {
    state.crList = crList
  }
};

const actions = {
  // user login
  getDictTree({
    commit
  }, data) {
    let dicts = []
    let requestDicts = []
    data.forEach(i => {
      // 如果state中不存在的就需要重新获取
      if (!state.dicts[i]) {
        requestDicts.push(i)
      } else {
        // 如果存在就直接存入dicts中
        let obj = {}
        obj[i] = state.dicts[i]
        dicts.push(obj)
      }
    });
    return new Promise((resolve, reject) => {
      getDictTree(requestDicts).then(res => {
        let dictsObj = {}
        requestDicts.forEach(reqDict => {
          dictsObj[reqDict] = []
          res.data.map(item => {
            if (item.dictType == reqDict) {
              dictsObj[reqDict].push(item)
            }
          })
          commit("SET_DICTS", {
            label: reqDict,
            value: Object.freeze(dictsObj[reqDict]),
          });
        })
        resolve(dictsObj)
      }).catch(error => {
        reject(error)
      })
    });

  },

  getCrList({
    commit
  }, {
    isReload,
    params
  }) {

    // 如果是空或者需要重新加载则重新调取接口获取，否则直接获取状态管理中的
    if (!state.crList || state.crList == 0 || isReload) {
      return new Promise((resolve, reject) => {
        getCulturalRelicList(params).then(response => {
          const {
            data
          } = response
          console.log('response',response);
          commit('SET_CR_LIST', data.records)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    } else {
      return new Promise((resolve, reject) => {
        resolve(state.crList)
      })
    }
  },


}

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