/*
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2018-10-10 14:44:45
 * @LastEditors: 无尘
 * @LastEditTime: 2020-11-16 09:28:03
 */
import Vue from 'vue';
import VueAxios from 'vue-axios';
import axios from 'axios';
// import axios from 'axios';
import qs from 'qs';
import { Message } from 'element-ui';

Vue.use(VueAxios, axios);
Vue.axios.defaults.withCredentials = true; // cookie访问
Vue.axios.defaults.headers.common['platform'] = 'haoban';

Vue.axios.defaults.timeout = 500000;
let local = window.location.origin;
const userInfos = JSON.parse(sessionStorage.getItem('userInfos') || '{}');
let gicHost = typeof userInfos.gicHost == 'string' ? userInfos.gicHost.replace(/\/$/, '') : '';
console.log(gicHost);
if (local.indexOf('localhost') >= 0) {
  gicHost = local;
}
// gicHost = local;

// let local = process.env.NODE_ENV == 'development' ? 'https://www.gicdev.com' : '';

let axiosPromiseArr = []; //储存cancel toke
let pending = []; //声明一个数组用于存储每个ajax请求的取消函数和ajax标识
let CancelToken = Vue.axios.CancelToken;
let removePending = ever => {
  for (let p in pending) {
    if (pending[p].u === ever.url + '&' + ever.method) {
      //当当前请求在数组中存在时执行函数体
      pending[p].f(); //执行取消操作
      pending.splice(p, 1); //把这条记录从数组中移除
    }
  }
};
Vue.axios.interceptors.request.use(
  config => {
    removePending(config); //在一个ajax发送前执行一下取消操作
    config.cancelToken = new CancelToken(c => {
      // 这里的ajax标识我是用请求地址&请求方式拼接的字符串，当然你可以选择其他的一些方式
      pending.push({
        u: config.url + '&' + config.method,
        f: c
      });
    });
    // 在发送请求设置cancel token
    config.cancelToken = new Vue.axios.CancelToken(cancel => {
      axiosPromiseArr.push({
        cancel
      });
    });
    /**
     * 获取好办 企业 id
     */
    if (!!sessionStorage.getItem('userInfoBrandId')) {
      let haobanSign = sessionStorage.getItem('userInfoBrandId');
      haobanSign ? (config.headers.enterpriseId = haobanSign) : '';
    }

    console.log(config);
    return config;
  },
  err => {
    Message.error({ message: '请求超时!' });
    return Promise.resolve(err);
  }
);

Vue.axios.interceptors.response.use(
  data => {
    removePending(data.config); //在一个ajax响应后再执行一下取消操作，把已经完成的请求从pending中移除
    // if (data.status && data.status == 200 && data.data.errorCode != 1) {
    //   if (data.data.errorCode == 4) {
    //     if (window.location.href.indexOf('gic-error') != -1) {
    //       return false;
    //     }
    //     window.location.href = gicHost + '/gic-web/#/login?ishb=1';
    //   }
    //   if (data.data.errorCode == 10 || data.data.errorCode == 7) {
    //     window.location.href = gicHost + '/haoban-3/#/index';
    //   }
    //   return data;
    // }
    return data;
  },
  err => {
    // if (err.response.status == 502) {
    //   window.location.href = gicHost + '/gic-web/#/login?ishb=1';
    //   Message.error({ message: '服务异常⊙﹏⊙∥' });
    // }
    // if (err.response.status != 403) {
    //   window.location.href = gicHost + '/gic-web/#/login?ishb=1';
    //   Message.error({ message: '登录失效!' });
    // }
    return Promise.resolve(err);
  }
);

/*
 *
 * 统一 get 请求方法
 * @url: 请求的 url
 * @params: 请求带的参数
 * @header: 带 token
 *
 */
export const getRequest = (url, params) => {
  params.requestProject = 'haoban-manage-web';
  return Vue.axios({
    method: 'get',
    url: `${local}${url}`,
    data: {},
    params: params,
    headers: {
      'Content-type': 'application/x-www-form-urlencoded'
    } // "token": token
  });
};

/*
 *
 * 统一 delete 请求方法
 * @url: 请求的 url
 * @params: 请求带的参数
 * @header: 带 token
 *
 */
export const deleteRequest = (url, params) => {
  params.requestProject = 'haoban-manage-web';
  return Vue.axios({
    method: 'delete',
    url: `${local}${url}`,
    data: {},
    params: params,
    headers: {
      'Content-type': 'application/x-www-form-urlencoded'
    } // "token": token
  });
};
/**
 *
 * 统一 post 请求方法
 * url: 请求的 url
 * @params: 请求带的参数
 * @header:
 *
 */
export const postRequest = (url, params) => {
  params.requestProject = 'haoban-manage-web';
  return Vue.axios({
    method: 'post',
    url: `${local}${url}`,
    data: qs.stringify(params),
    headers: {
      'Content-type': 'application/x-www-form-urlencoded'
    } //multipart/form-data{"token": token}
  });
};

export const postJsonRequest = (url, params) => {
  params.requestProject = 'haoban-manage-web';
  return Vue.axios({
    method: 'post',
    url: `${local}${url}`,
    data: params,
    headers: { 'Content-Type': 'application/json;charset=UTF-8' } //multipart/form-data{"token": token}
  });
};

/**
 * method: 'post'
 * 'Content-Type': 'application/json;charset=UTF-8'
 * @data: params
 * @requestProject: 'haoban-manage-web'
 *
 */
export const postJson = (url, params) => {
  // params.requestProject = "haoban-manage-web";
  return Vue.axios({
    method: 'post',
    url: `${local}${url}`,
    data: params,
    params: { requestProject: 'haoban-manage-web' },
    // withCredentials: true,
    // credentials: 'same-origin',
    headers: { 'Content-Type': 'application/json;charset=UTF-8' } //multipart/form-data{"token": token}
  });
};

/**
 *  method: 'post'
 *  data: params
 *
 */
export const postForm = (url, params) => {
  params.requestProject = 'haoban-manage-web';
  return Vue.axios({
    method: 'post',
    url: `${local}${url}`,
    data: params,
    headers: {} //'content-type': 'application/x-www-form-urlencoded'multipart/form-data{"token": token}
  });
};

/**
 * post excel
 */

export const postExcel = (url, params) => {
  params.requestProject = 'haoban-manage-web';
  return Vue.axios({
    method: 'post',
    url: `${local}${url}`,
    data: qs.stringify(params),
    responseType: 'blob',
    headers: {
      'content-type': 'application/x-www-form-urlencoded'
    } //multipart/form-data{"token": token}
    /* httpAgent: new http.Agent({
          keepAlive: true
        }),
        httpsAgent: new https.Agent({
          keepAlive: true
        }) */
  });
};
