import axios from "axios";
// import Router from '@/router/index'
import store from "@/store";
import urlConfig from "@/apis/url-config";
import { getToken } from "@/utils/auth";
import { Message } from "element-ui";
const header = {
  // "X-Requested-With": "XMLHttpRequest",
  // "X-Frame-Options": "DENY", // 告诉浏览器不要（DENY）把这个网页放在iFrame内，通常的目的就是要帮助用户对抗点击劫持。
  // "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
};
window.ajaxTimeout = 20000;
export default async (
  url = "",
  data = {},
  type = "GET",
  params = {},
  headers = header,
  onUploadProgress
) => {
  type = type.toLowerCase();
  const obj = {
    method: type,
    baseURL: "",
    url: urlConfig.baseURL + url,
    data: data,
    params,
    processData: true, // 告诉axios不要去处理发送的数据(重要参数)
    timeout: window.ajaxTimeout,
    headers,
    onUploadProgress,
  };
  if (onUploadProgress && typeof onUploadProgress === "function") {
    obj.onUploadProgress = onUploadProgress;
  }

  return new Promise((resolve, reject) => {
    axios(obj)
      .then((response) => {
        resolve(response.data);
      })
      .catch((res) => {
        reject(res);
      });
  });
};

// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    if (!config.data.token) {
      config.data.token = getToken();
    }
    // const { noRelation, needRela, relaComNo } = config.data
    // const innerRelaComNo = store.state.user.currentCompany
    // // 决定传递关联公司:非超管用户且单独的请求中data中没有设置noRelation
    // // needRela: 超管需要传递关联公司(默认超管不传递)
    // // noRelation: 普通用户不传递关联公司(默认普通用户传递)
    // const isAllowRelaComNo = !store.state.user.isSupertube && !noRelation
    // config.data.relaComNo = isAllowRelaComNo ? innerRelaComNo : ''
    // if (needRela) config.data.relaComNo = relaComNo || innerRelaComNo
    // const deleteKeys = ['needRela', 'noRelation']
    // deleteKeys.forEach(key => key in config.data && delete config.data[key])
    return config;
  },
  function () {
    // 错误抛到业务代码
    return Promise.reject(new Error("服务器异常，请联系管理员！"));
  }
);

// 添加响应拦截器
axios.interceptors.response.use(
  async (response) => {
    // TODO:修改响应code判断
    const { data } = response;
    const { code, msg } = data;
    switch (Number(code)) {
      case 0:
        // 正常提示错误 ...
        Message.warning(msg);
        break;
      case 101:
        // token验证错误,登出 ...
        store.dispatch("user/logout");
        break;
      default:
        // TODO 正常响应 ...
        break;
    }
    return response;
  },
  (error) => {
    return Promise.reject(error.response.data);
  }
);
