import axios from "axios";
import { Toast } from "vant";

let loading = null;

const service = axios.create({
  baseURL: "/shop-mall",
  timeout: 5000
});

service.interceptors.request.use(
  config => {
    const token = localStorage.getItem("token");
    config.headers["token"] = token;
    if (!config.loading) {
      loading = Toast.loading({
        forbidClick: true,
        message: "加载中..."
      });
    }
    return config;
  },
  error => {
    if (loading) Toast.clear();
    this.$toast.fail(error.response.data.error);
  }
);

service.interceptors.response.use(
  response => {
    if (loading) Toast.clear();
    const res = response.data;
    return res;
  },
  error => {
    if (loading) Toast.clear();
    return Promise.reject(error);
  }
);

export default service;
