import axios from "axios";
import {
  useStore
} from "../store";

const service = axios.create({
  //根据环境变量 统一设置 域名 前缀,实际请求的路径是 baseURL + requestUrl
  baseURL: '',
  withCredentials: true, //跨域请求时发送Cookie
  timeout: 10000, // 设置超时时间
});
// 请求拦截
service.interceptors.request.use(
  (config) => {
    const store = useStore();
    // 请求前加一些需要的逻辑，如再请求头中加参数
    if (store.token) {
      config.headers['Authorization'] = store.token
    }
    //最终要返回这个配置
    return config;
  },
  (error) => {
    //请求失败时的逻辑
    return Promise.reject(error);
  }
);
// 响应拦截
service.interceptors.response.use(
  (response) => {
    //response中包含响应的所有数据包括响应头，状态等
    // 前后端约定的接口回来的数据格式，接口成功或接口失败，做一些逻辑处理再返回结果
    if (response.status !== 200) {
      alert(response.statusText);
      //最终都要返回结果
      return Promise.reject(new Error(response.statusText || "Error"));
    } else {
      //最终都要返回结果
      if (response.data.code == '9000' || response.data.constructor !== Object) {
        return response.data;
      } else {
        return Promise.reject(response.data.message);
      }
    }
  },
  (error) => {
    let status = "";
    if (error.request) {
      status = error.request;
    } else if (error.response) {
      status = error.response;
    }
    if (status) {
      switch (status.status) {
        case 400:
          error.message = "请求错误(400)";
          break;
        case 401:
          error.message = "未授权，请重新登录(401)";
          router.push("/401");
          break;
        case 403:
          error.message = "拒绝访问(403)";
          break;
        case 404:
          error.message = "请求出错(404)";
          router.push("/404");
          break;
        case 408:
          error.message = "请求超时(408)";
          break;
        case 500:
          error.message = "服务器错误(500)";
          router.push("/a500");
          break;
        case 501:
          error.message = "服务未实现(501)";
          break;
        case 502:
          error.message = "网络错误(502)";
          break;
        case 503:
          error.message = "服务不可用(503)";
          break;
        case 504:
          error.message = "网络超时(504)";
          break;
        case 505:
          error.message = "HTTP版本不受支持(505)";
          break;
        default:
          error.message = `连接出错(${error.response.status})!`;
      }
    } else {
      error.message = "连接服务器失败!";
    }
    // console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);

export default service;