import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message } from 'element-ui';
let router: any = null;
let key: string | undefined = process.env.VUE_APP_CURRENTMODE
if (key) {
  if (key.indexOf('sy') === 0) {
    // 溯源环境
    router = require('@/entry/sy/router');
  } else if (key.indexOf('cs') === 0) {
    // 慈善环境
    router = require('@/entry/cs/router');
  } else if (key.indexOf('best') === 0) {
    // best
    router = require('@/entry/best/router');
  } else if (key.indexOf('hd') === 0) {
    // hd
    router = require('@/entry/hd/router');
  } else if (key.indexOf('dl') === 0) {
    // hd
    router = require('@/entry/dl/router');
  }
}

import { getLoginCode } from './storage';
export interface ResBase {
  code: number;
  data: any;
  msg: string;
}
// get请求
export interface GetParam {
  type: 'get' | 'delete';
  url: string;
  params?: { [key: string]: any };
  header?: Object;
  config?: Object;
}
// post请求
export interface PostParam {
  type: 'post' | 'put' | 'patch' | 'delete';
  url: string;
  params?: Object;
  header?: Object;
  config?: Object;
}
//获取对象的长度
function length(o: object) {
  var count = 0;
  for (var i in o) {
    count++;
  }
  return count;
};
// ajax
async function ajax(param: PostParam | GetParam) {
  try {
    const type = param.type.toLowerCase();
    const result: AxiosRequestConfig = {
      method: type,
      url: param.url,
      params: {},
      headers: {
        Authorization: 'Bearer ' + getLoginCode(),
        ...(param.header || {}),
      },
      ...(param.config || {}),
    };
    if (param.params) {
      if (['get'].includes(type)) {
        let restfulUrl = param.url + `?`;
        const params = (param as GetParam).params || [];
        let num = length(params)
        Object.keys(params).forEach(function (key) {
          if (num === 1) {
            restfulUrl += `${key}=${params[key]}`;
          } else {
            restfulUrl += `${key}=${params[key]}&`;
            num--
          }
        });
        result.url = restfulUrl;
      }
      else {
        result.data = param.params;
      }
    }
    // 返回res
    const res: AxiosResponse<ResBase> = await axios(result);
    if (res.data.code === 200) { // mock 为 0
      return res.data || {};
    }
    else if (res.data.code == 403) {
      Message.warning('登录过期,请刷新页面');
      sessionStorage.removeItem("user");
      router.push({ path: "/" });
      return null;
    }
    else {
      Message(res.data.msg);
      return null;
    }
  } catch (e) {
    if (axios.isCancel(e)) {
      return null;
    }
    Message.error('网络异常');
  }
}
export {
  ajax,
};
export default {
  install(Vue: any, funcName: string = '$ajax') {
    Object.defineProperty(Vue.prototype, funcName, { value: ajax });
  },
};
