import {
  getDictCode
} from "@/api/dict";
import {
  getLiteratureList
} from '@/api/literature'
import store from "@/store";
import Vue from "vue";
class Dict {
  constructor(dict) {
    this.dict = dict;
  }

  async init(names) {
    // 先判断list中的name是否存在，如果不存在，把不存在的放置在一个list中，再对list进行获取
    var nonExistentNames = []
    // debugger
    names.forEach(name => {
      if (store.getters.dicts[name]) {
        Vue.set(this.dict, name, store.getters.dicts[name]);
      } else {
        nonExistentNames.push(name) //存入list中，单独进行处理调用
      }
    });

    var index = nonExistentNames.indexOf('literature')
    
    if (index != -1) {
      // debugger
      Vue.set(this.dict, 'literature', []);
      nonExistentNames.splice(index, 1)
      var params = {
        limit: 100,
        page: 1
      }
      var res = await getLiteratureList(params)
      if (res.code == 0) {
        var literatureList =  res.data.records
        Vue.set(this.dict, 'literature', literatureList);
        this.dict['literature'] = Object.freeze(literatureList)
        store.commit("dict/SET_DICTS", {
          label: 'literature',
          value: Object.freeze(literatureList),
        });
      }
    }
    if (nonExistentNames.length > 0) {
      // debugger
      var res = await getDictCode(nonExistentNames)
      nonExistentNames.forEach(n => {
        Vue.set(this.dict, n, []);
        // var arr = []
        var obj = {}
        if (res.code == 0) {
          res.data.map(item => {
            if (item.dictType === n) {
              obj[item.value]=item.label
            }
          })
          this.dict[n] = Object.freeze(obj)
     
          store.commit("dict/SET_DICTS", {
            label: n,
            value: Object.freeze(obj),
          });
        }
      })
    }

  }

}

const install = function (Vue) {
  Vue.mixin({
    data() {
      // 如果在调用组件处data中有定义dicts，再进行初始化dict
      if (
        this.$options.dicts instanceof Array &&
        this.$options.dicts.length > 0
      ) {
        return {
          dict: {}
        };
      } else {
        return {};
      }
    },
    created() {
      // 如果在调用组件处data中有定义dicts，再进行获取dicts中定义的字典
      if (
        this.$options.dicts instanceof Array &&
        this.$options.dicts.length > 0
      ) {
        new Dict(this.dict).init(this.$options.dicts);
      }
    },
  });
};

export default {
  install
};
