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
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000000, // 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;
    }
    startLoading();
    return config;
  },
  (error) => {
    endLoading();
    // do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  async (response) => {
    // do something with response data
    const res = response.data;
    endLoading();
    if (res.code) {
      if (res.code !== 200) {
        if (res.code === 411) {
          return Promise.resolve(res);
        }
        if (res.code === 205) {
          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) => {
    endLoading();
    // do something with response error
    return Promise.reject(error);
  }
);

export default service;
export { startLoading, endLoading };
