import Vue from 'vue'
import VueI18n from 'vue-i18n'
import store from '@/store'
import DataDict from '@/utils/dict'
import { getDicts as getDicts } from '@/api/system/dict/data'

function searchDictByKey(dict, key) {
  if (key == null && key == "") {
    return null
  }
  try {
    for (let i = 0; i < dict.length; i++) {
      if (dict[i].key == key) {
        return dict[i].value
      }
    }
  } catch (e) {
    return null
  }
}

function searchDictByKeys(dict, key) {
  if (key == null && key == "") {
    return null
  }
  try {
    return dict[key]
  } catch (e) {
    return null
  }
}

function install() {
  Vue.use(DataDict, {
    metas: {
      '*': {
        labelField: 'dictLabel',
        valueField: 'dictValue',
        request(dictMeta) {
          const currentLocale = window.VueI18n.locale;
          // console.log("获取字典查询时候local："+currentLocale)
          // console.log("获取字典查询时候local："+localStorage.getItem("local"))
          if(currentLocale === 'chinese'){
            dictMeta.labelField = "dictLabel";
          }
          if(currentLocale === 'english'){
            dictMeta.labelField = "dictLabelUS";
          }
          if(currentLocale === 'russia'){
            dictMeta.labelField = "dictLabelRU";
          }
          if(currentLocale === 'spanish'){
            dictMeta.labelField = "dictLabelES";
          }
          const storeDict = searchDictByKeys(store.getters.dict, dictMeta.type)
          // console.log("从Store中获取"+JSON.stringify(storeDict))
          if (storeDict) {
            return new Promise(resolve => { resolve(storeDict) })
          } else {
            return new Promise((resolve, reject) => {
              getDicts(dictMeta.type).then(res => {
                store.dispatch('dict/setDict', { key: dictMeta.type, value: res.data })
                resolve(res.data)
              }).catch(error => {
                reject(error)
              })
            })
          }
        },
      },
    },
  })
}

export default {
  install,
}
