import { message } from 'ant-design-vue';
import Axios from 'axios';
const $axios = Axios;

export const loadProfile = function (name) {
  const lang = 'zh';
  const list = [];
  const baseURL = location.protocol + '//' + location.host + '/';
  const modelName = location.pathname.substr(1);

  if (typeof name == 'string') {
    list.push('/' + name + '-' + lang + '.json');
  } else {
    for (const i in name) {
      list.push('/' + name[i] + '-' + lang + '.json');
    }
  }
  if (process.env.NODE_ENV === 'production') {
    const files = [];
    for (let j = 0; j < list.length; j++) {
      const path = list[j].substr(0, list[j].lastIndexOf('/'));
      const _name = list[j].substr(list[j].lastIndexOf('/') + 1);
      files.push({
        model: modelName + path,
        fileName: _name,
      });
    }
    return $axios
      .post(`${baseURL}cfg?` + new Date().getTime(), files)
      .then((response) => {
        const res = response.data;
        const resCfg = [];
        for (let locvar = 0; locvar < list.length; locvar++) {
          let resvar = 0;
          for (; resvar < res.length; resvar++) {
            if (res[resvar].model + '/' + res[resvar].fileName == modelName + list[locvar]) {
              try {
                resCfg.push(JSON.parse(res[resvar].context));
              } catch {
                this.$message('无法解析配置文件：' + list[locvar]);
              }
              break;
            }
          }
          if (resvar == res.length) {
            message.warning(this.$t('文件' + [list[locvar]] + '解析失败'));
            resCfg.push({});
          }
        }
        if (typeof name == 'string') {
          return resCfg[0];
        } else {
          return resCfg;
        }
      })
      .catch((e) => {
        //this.$message("无法获取配置文件："+name);
        this.$message(e);
      });
  } else {
    const ps = [];
    for (let j = 0; j < list.length; j++) {
      ((fname) => {
        ps.push(
          $axios
            .get(baseURL + modelName + '/script/' + fname + '?' + new Date().getTime())
            .then((response) => {
              return response.data;
            })
            .catch(() => {
              message.warning(this.$t('文件' + fname + '解析失败'));
            }),
        );
      })(list[j]);
    }
    return $axios.all(ps).then((res) => {
      if (typeof name == 'string') {
        return res[0];
      } else {
        return res;
      }
    });
  }
};


