import axios from "axios";
import NProgress from "nprogress";
import { Message } from "element-ui";
import router from "@/router/index";
import store from "@/store";
import conf from "../config/index"; // 路径配置
import { getURLParams } from "@/utils";

let code = getURLParams("code") || getURLParams("dockkey") || localStorage.getItem("csCode") || "";


// axios默认配置
const service = axios.create({
  baseURL: conf.baseURL, // api的base_url
  timeout: 600000000000000, // 请求超时时间
  withCredentials: true,
});
// http request 拦截器
service.interceptors.request.use(
  (config) => {
    NProgress.start();
    // config.headers["Content-Type"] = "application/json;charset=UTF-8";

    const source = axios.CancelToken.source();
    store.commit("setTokenSources", [source.token, source.cancel]);
    config.cancelToken = source.token;
    return config;
  },
  (error) => {
    return Promise.reject(error.response);
  }
);

// http response 拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    NProgress.done();
    if (response.config.cancelToken) {
      store.commit("delTokenSources", response.config.cancelToken);
    }
    if (response.status == 200) {
      if (res.status == 999) {
        // if (!location.href.includes("localhost")) {
        if (res.data) {
          window.location.href = res.data;
        } else {
          router.push({ path: "/login" });
          if (res.info.includes("不存在")) {
            Message({
              info: res.info,
              type: "error",
              duration: 3 * 1000,
            });
          }
        }
        // }
      }
    }
    return Promise.resolve(res);
  },
  (error) => {
    const { data, status } = error.response;
    if (error.response == undefined) {
      return Promise.reject(error);
    }

    if (status === 403 || status === 401) {
      if (data.status === 999) {
        if (data.data) {
          window.location.href = data.data;
        } else {
          Message({
            message: data.info,
            type: "error",
            duration: 3 * 1000,
          });
          router.push({ path: "/login" });
        }
        if (code) {
          return
        } else {
          return Promise.resolve(data);
        }
      }
      Message.closeAll();
      Message({
        message: data.info || "未登录或登录超时，即将跳转到登录页面",
        type: "error",
        duration: 3 * 1000,
      });

      if (!window.location.href.includes("login")) {
        router.push({
          path: "/login",
          query: {
            url: window.location.href,
          },
        });

      }
      return;
    }
    Message({
      message: data.info || error,
      type: "error",
      duration: 3 * 1000,
    });
    return Promise.reject(error.response); // 返回接口返回的错误信息
  }
);
export default service;
