import axios from "axios";
import Vue from "vue";
import { Loading } from "element-ui";

// create an axios instance
const service = axios.create({
  baseURL: "http://localhost:3000", // url = base url + request url
  timeout: 12600000 // request timeout
});
let loading;

function startLoading() {
  loading = Loading.service({
    lock: true,
    text: "拼命加载中...",
    spinner: "el-icon-loading",
    background: "rgba(0,0,0,.7)"
  });
}

function endLoading() {
  loading.close();
}

// Add a request interceptor
service.interceptors.request.use(
  config => {
    const user = Vue.prototype.$dataStore.get("user");

    if (user) {
      config.headers["jwt-token"] = user.token;
    }
    if (!config.skipLoading) startLoading();
    return config;
  },
  error => {
    if (!error.config?.skipLoading) endLoading();
    // do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
service.interceptors.response.use(
  async response => {
    // do something with response data
    const res = response.data;
    if (!response.config.skipLoading) endLoading();
    if (res.code) {
      if (res.code !== 200) {
        if (res.code === 411 || res.code === 205 || res.code === 301) {
          return Promise.resolve(res);
        }

        if (res.code === 403) {
          Vue.prototype.$dataStore.delete("user");
          Vue.prototype.$message.error({
            showClose: true,
            message: res.msg || res.message || "Error"
          });
          setTimeout(() => {
            location.reload();
          }, 500);

          return Promise.reject(new Error(res.msg || res.message || "Error"));
        }

        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
          // TODO: to re-login
        }
        Vue.prototype.$message.error({
          showClose: true,
          message: res.msg || res.message || "Error"
        });
        // reject
        return Promise.reject(new Error(res.msg || res.message || "Error"));
      } else {
        return Promise.resolve(res);
      }
    }
    return Promise.resolve(res);
  },
  error => {
    if (!error.config?.skipLoading) endLoading();
    let errMsg = "请求失败，请稍后重试";

    // 1. 有服务端响应：提取后端返回的 msg
    if (error.response && error.response.data) {
      const data = error.response.data;
      // 优先取后端返回的 msg（适配你后端 {code:500, msg:'xxx'} 的格式）
      errMsg =
        data.msg || data.message || `请求错误（${error.response.status}）`;
    }
    // 2. 无响应：网络层面错误
    else if (error.message) {
      if (error.message.includes("timeout")) {
        errMsg = "请求超时，请检查网络";
      } else if (error.message.includes("Network Error")) {
        errMsg = "网络连接异常，请检查网络";
      } else {
        errMsg = error.message;
      }
    }
    return Promise.reject(new Error(errMsg));
  }
);

export default service;
export { startLoading, endLoading };
