//引入axios
import store from "@/store";
import axios from "axios";
import cherry from "@qg/cherry-ui";
import config from "../config";
// import qs from "qs";

const CancelToken = axios.CancelToken;
const { Notify } = cherry;

axios.defaults.baseURL = config.basicHost;
axios.defaults.timeout = 30000;

// let cancel;
let pending = {};
let reqNum = 0;

function beforeRequest() {
  reqNum++;
  store.dispatch("setIsLoading", true);
}

function afterRequest() {
  setTimeout(clearRequest, 300);
}

function clearRequest() {
  reqNum--;
  if (reqNum <= 0) {
    store.dispatch("setIsLoading", false);
  }
}

//请求拦截器
axios.interceptors.request.use(
  config => {
    beforeRequest();
    //发起请求时，取消掉当前正在进行的相同请求
    if (pending[config.url]) {
      pending[config.url]("取消重复请求");
    }
    config.cancelToken = new CancelToken(c => (pending[config.url] = c));

    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

//响应拦截器即异常处理
axios.interceptors.response.use(
  response => {
    afterRequest();
    delete pending[response.config.url];
    if (response.data.code === 0) {
      return response.data;
      // return response.data.data;
    }
    Notify({ type: "danger", message: response.data.msg || "后端服务异常" });
  },
  err => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = "错误请求";
          break;
        case 401:
          err.message = "未授权，请重新登录";
          break;
        case 403:
          err.message = "拒绝访问";
          break;
        case 404:
          err.message = "请求错误,未找到该资源";
          break;
        case 405:
          err.message = "请求方法未允许";
          break;
        case 408:
          err.message = "请求超时";
          break;
        case 500:
          err.message = "服务器端出错";
          break;
        case 501:
          err.message = "网络未实现";
          break;
        case 502:
          err.message = "网络错误";
          break;
        case 503:
          err.message = "服务不可用";
          break;
        case 504:
          err.message = "网络超时";
          break;
        case 505:
          err.message = "http版本不支持该请求";
          break;
        default:
          err.message = `连接错误${err.response.status}`;
      }
    } else {
      if (err.message == "操作取消") {
        err.response = {};
        err.response.status = 409;
        err.response.data = {};
        return Promise.resolve(err.response);
      } else {
        err.message = "连接到服务器失败";
      }
    }
    afterRequest();
    Notify({ type: "danger", message: err.message });
    return Promise.resolve(err.response);
  }
);

export default {
  axios,
  //get请求
  get(url, params = {}) {
    return new Promise((resolve, reject) => {
      axios({
        method: "get",
        // url: url + "?" + qs.stringify(params),
        url: url,
        params,
        headers: {
          "Content-Type": "application/json"
        }
      })
        .then(res => {
          resolve(res);
        })
        .catch(e => {
          reject(e);
        });
    });
  },
  //post请求
  post(url, params = {}) {
    return new Promise((resolve, reject) => {
      axios({
        method: "post",
        url,
        data: params,
        headers: {
          "Content-Type": "application/json"
        }
      })
        .then(res => {
          resolve(res);
        })
        .catch(e => {
          reject(e);
        });
    });
  }
};
