import {
  getDictCode,
  getDictTree
} from '@/api/dict'
import {
  getCulturalRelicList
} from '@/api/culturalRelic'
import {
  getLiteratureList,
  getLtListPer
} from '@/api/literature'


const state = {
  dicts: {}, //字典
  crList: [], //文物列表
  ltList: [] //文献列表
};

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

const actions = {
  /**
   * 获取普通list结构(非树结构)的字典
   * @param {Array} data 字典的key集合
   * @returns {Promise}
   */
  getDictList(context, data) {
    let dicts = {}
    let requestDicts = []
    // debugger
    data.forEach(i => {
      if (!context.state.dicts[i]) {
        requestDicts.push(i)
      } else {
        dicts[i] = context.state.dicts[i]
      }
    });

    if (requestDicts.length > 0) {
      return new Promise((resolve, reject) => {
        getDictCode(requestDicts).then(res => {
          requestDicts.forEach(reqDict => {
            var obj = {}
            if (res.code == 0) {
              res.data.map(item => {
                if (item.dictType == reqDict) {
                  obj[item.value] = item.label
                }
              })
              dicts[reqDict] = obj
              // console.log('dicts',dicts);
              context.commit('SET_DICTS', {
                label: reqDict,
                value: obj
              })
            }
          })
          resolve(dicts)
        }).catch(error => {
          reject(error)
        })
      });
    } else {
      return new Promise((resolve, reject) => {
        resolve(dicts)
      })
    }
  },

  // /**
  //  * 获取普通list结构(非树结构)的字典
  //  * @param {type} data 字典的key集合或者字符串
  //  * @returns {Promise}
  //  */
  // async getDictsByTypes(context, type) {
  //   let dicts = context.state.dicts;
  //   let types = [];
  //   if (typeof type === "string") {
  //     types.push(type);
  //   } else if (Array.isArray(type)) {
  //     types = type;
  //   }

  //   let dataArr = [];
  //   let serverTypes = [];
  //   types.forEach((n, i) => {
  //     let curData = dicts[n];
  //     if (curData) {
  //       dataArr[i] = curData;
  //     } else {
  //       dataArr[i] = n;
  //       serverTypes.push(n);
  //     }
  //   });

  //   if (serverTypes.length > 0) {
  //     const res = await getDictCode(serverTypes);

  //     let obj = {};
  //     serverTypes.forEach((n, i) => {
  //       let j = dataArr.indexOf(n);
  //       dataArr[j] = res[i];
  //       obj[n] = res[i];
  //     });
  //     context.commit("SET_DICTS_2", obj);
  //   }

  //   return dataArr;
  // },

  /**
   * 获取树形结构的字典树，如文物年代、文物质地
   * @param {Array} data 字典的key集合
   * @returns {Promise}
   */
  getDictTree({
    commit
  }, data) {
    let dicts = {}
    let requestDicts = []
    data.forEach(i => {
      if (!state.dicts[i]) {
        requestDicts.push(i)
      } else {
        dicts[i] = state.dicts[i]
      }
    });
    if (requestDicts.length > 0) {
      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)
        })
      });
    } else {
      return new Promise((resolve, reject) => {
        resolve(dicts)
      })
    }
  },

  /**
   * 获取文物列表
   * @param {Boolean} isReload 是否要重新加载
   * @param {params}  params 分页或一些查询参数
   * @returns {Promise}
   */
  getCrList({
    commit
  }, {
    isReload,
    params
  }) {
    if (!state.crList || state.crList.length == 0 || isReload) {
      return new Promise((resolve, reject) => {
        getCulturalRelicList(params).then(response => {
          const {
            data
          } = response
          commit('SET_CR_LIST', data.records)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    } else {
      return new Promise((resolve, reject) => {
        resolve(state.crList)
      })
    }
  },

  /**
   * 获取文献列表
   * @param {Boolean} hasPer 是否含有权限
   * @param {params}  params 分页或一些查询参数
   * @returns {Promise}
   */
  getLtList({
    commit
  }, {
    hasPer,
    params
  }) {
    if (hasPer) {
      return new Promise((resolve, reject) => {
        getLtListPer(params).then(response => {
          const {
            data
          } = response
          commit('SET_CR_LIST', data.records)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    } else {
      return new Promise((resolve, reject) => {
        getLiteratureList(params).then(response => {
          const {
            data
          } = response
          commit('SET_CR_LIST', data.records)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    }

  },

}

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