import store from '@/store';
import router from '@/router';
import { Message } from 'element-ui';
import { getToken, getSeed, setToken } from '@/utils/auth';
import user from '@/api/user';

var ApiUtil = {
  // apiPath : 'http://192.168.0.231:8001/index.php',
  apiPath: process.env.VUE_APP_BASE_API,
  jsPath: '/start/api/',
  loginList: ['B00103', 'B00109', '401'],
  showLoading() {},
  hideLoading() {},
  asyncCall(url, params, type, paramType, header) {
    //异步
    if (paramType == 'json') {
      params = JSON.stringify(params);
    }
    var settings = {
      type: type == null ? 'post' : type,
      params: params ? params : {},
      header:
        header == null
          ? {
              'zoomwin-token': getToken(),
              'zoomwin-sid': getSeed()
            }
          : '',
      dataType: 'json',
      processData: true,
      contentType:
        paramType == 'json'
          ? 'application/json;charset=UTF-8'
          : 'application/x-www-form-urlencoded',
      url: url
    };
    return this.promiseAjax(settings);
  },
  syncCall(url, params, type, paramType, header) {
    //同步
    if (paramType == 'json') {
      params = JSON.stringify(params);
    }
    var settings = {
      type: type == null ? 'post' : type,
      params: params ? params : {},
      header:
        header == null
          ? {
              'zoomwin-token': getToken(),
              'zoomwin-sid': getSeed()
            }
          : '',
      dataType: 'json',
      processData: true,
      contentType:
        paramType == 'json'
          ? 'application/json;charset=UTF-8'
          : 'application/x-www-form-urlencoded',
      url: url
    };
    return this.call(settings);
  },
  syncUploadCall(url, params) {
    //上传图片
    var settings = {
      type: 'post',
      params: params,
      header: {
        'zoomwin-token': getToken(),
        'zoomwin-sid': getSeed()
      },
      dataType: 'json',
      contentType: false,
      processData: false,
      url: url
    };
    return this.call(settings);
  },
  //同步ajax
  call(settings) {
    if (settings.url == null) {
      Message.warning('访问地址不能为空！');
      return;
    }
    this.showLoading();
    var data = null;
    let _this = this;
    $.ajax({
      type: settings.type,
      data: settings.params,
      headers: settings.header,
      dataType: settings.dataType,
      contentType: settings.contentType,
      processData: settings.processData,
      url: ApiUtil.apiPath + settings.url,
      cache: false,
      async: false,
      success: function (result) {
        if (result.success) {
          ApiUtil.hideLoading();
          data = result;
        } else {
          if (result.code == 'B00101') {
            let info = JSON.parse(localStorage.getItem('orgInfo'));
            let form = {
              token: getToken(),
              seed: info.metaSeed,
              sid: info.sessionId
            };
            let token = user.refreshToken(form);
            setToken(token);
            settings.header['zoomwin-token'] = token;
            data = _this.call(settings);
          } else if (ApiUtil.loginList.includes(result.code)) {
            Message({
              message: result.message,
              type: 'error',
              duration: 1000
            });
            store.dispatch('user/physicalExit');
            router.push('/login');
          } else {
            Message({
              message: result.message,
              type: 'error',
              duration: 1000
            });
          }
          data = false;
        }
      },
      error: function (err) {
        ApiUtil.hideLoading();
        Message.error(err.statusText);
      }
    });
    return data;
  },
  //异步ajax
  promiseAjax(settings) {
    if (settings.url == null) {
      Message.warning('访问地址不能为空！');
      return;
    }
    this.showLoading();
    let _this = this;

    return new Promise(function (resolve, reject) {
      var result = null;
      $.ajax({
        type: settings.type,
        data: settings.params,
        headers: settings.header,
        dataType: settings.dataType,
        contentType: settings.contentType,
        processData: settings.processData,
        url: ApiUtil.apiPath + settings.url,
        timeout: settings.timeout || 20000,
        cache: false,
        async: true,
        success: function (res) {
          if (res.success) {
            resolve(res);
          } else {
            if (res.code == 'B00101') {
              let info = JSON.parse(localStorage.getItem('orgInfo'));
              let form = {
                token: getToken(),
                seed: info.metaSeed,
                sid: info.sessionId
              };
              let token = user.refreshToken(form);
              setToken(token);
              settings.header['zoomwin-token'] = token;
              _this.promiseAjax(settings).then((res) => {
                resolve(res);
              });
            } else if (ApiUtil.loginList.includes(res.code)) {
              Message.error(res.message);
              store.dispatch('user/physicalExit');
              router.push('/login');
              reject(res);
            } else {
              Message.error(res.message);
              reject(res);
            }
          }
        },
        error: function (err) {
          Message.error(err.statusText);
          reject(err.statusText);
        }
      });
    });
  },
  import: function (modules, callback) {
    var returnApi = {};
    var importApi = [];
    for (var i = 0; i < modules.length; i++) {
      // import('./'+modules[i]+'.js').then(result=>{
      // 	for(var apis in result){
      // 		for(var func in result[apis]){
      // 			window.Api[func] = result[apis][func];
      // 		}
      // 	}
      // 	this.readyFunc();
      // },error=>{
      // 	alert('没有此API脚本')
      // });
      importApi.push(import(this.jsPath + modules[i] + '.js'));
    }
    Promise.all(importApi).then(
      (result) => {
        for (var i = 0; i < result.length; i++) {
          for (var apis in result[i]) {
            for (var func in result[i][apis]) {
              returnApi[func] = result[i][apis][func];
            }
          }
        }
        callback(returnApi);
      },
      (error) => {
        alert('没有此API脚本');
      }
    );
  },
  resetToken(url, params) {
    var settings = {
      type: 'post',
      params: params,
      header: {},
      dataType: 'json',
      contentType: 'application/x-www-form-urlencoded',
      processData: true,
      url: url
    };
    var token = null;
    $.ajax({
      type: settings.type,
      data: settings.params,
      headers: settings.header,
      dataType: settings.dataType,
      contentType: settings.contentType,
      processData: settings.processData,
      url: ApiUtil.apiPath + settings.url,
      cache: false,
      async: false,
      success: function (result) {
        if (result.success) {
          token = result.data;
        } else {
          Message({
            message: result.message,
            type: 'error',
            duration: 1000
          });
          token = false;
        }
      },
      error: function (err) {
        ApiUtil.hideLoading();
        Message.error(err.statusText);
      }
    });

    return token;
  }
};

export default ApiUtil;
