import axios from "axios";
import { Message, Loading } from "element-ui";
const ins = axios.create();

// 洋葱模型全局loading
let loading = null; //定义loading变量

// 开始 加载loading
let startLoading = () => {
  loading = Loading.service({
    lock: true,
    text: "数据加载中...",
  })
};

// 结束 取消loading加载
let endLoading = () => {
  loading.close();
};

let needLoadingRequestCount = 0; //声明一个变量

let showFullScreenLoading = () => {
  if (needLoadingRequestCount === 0) {
    // 当等于0时证明第一次请求 这时开启loading
    startLoading();
  }
  needLoadingRequestCount++; //全局变量值++
};

let tryHideFullScreenLoading = () => {
  if (needLoadingRequestCount <= 0) return; //小于等于0 证明没有开启loading 此时return
  needLoadingRequestCount--; //正常响应后 全局变量 --
  if (needLoadingRequestCount === 0) {
    //等于0 时证明全部加载完毕 此时结束loading 加载
    endLoading();
  }
};

ins.interceptors.request.use(
  (config) => {
    // showFullScreenLoading()
    return config;
  },
  (err) => {
    // showFullScreenLoading()
  }
);

// 响应拦截器
ins.interceptors.response.use(
  (res) => {
    // tryHideFullScreenLoading()
    // 返回信息拦截
    if (res.data.code !== 200) {
      Message.error(res.data.message);
      return Promise.reject(res.data.message);
    }
    return res;
  },
  (err) => {
    let redirectOrigin
    if(process.env.NODE_ENV === 'development'){
      redirectOrigin = 'http://localhost:9000'
    }else{
      redirectOrigin = window.location.origin
    }
    if (err.response.data.code === 401) {
      window.location.href = `${redirectOrigin}/#/login?redirectURL=${encodeURIComponent(window.location.href)}`;
    } else {
      Message.error("接口异常，请联系管理员");
      return Promise.reject(err);
    }
  }
);

export default ins;
