import axios from "axios";
import store from "@/store";
import router from "@/router";
import { getToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_URL, // api的base_url
  timeout: 15000, // request timeout
  // responseType: "json",
  // crossDomain: true,
  // xhrFields: { withCredentials: true },
  // headers: { 'X-Requested-With': 'XMLHttpRequest' },
  // headers: {
  //     "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
  // }
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // Do something before request is sent
    if (window.sessionStorage.getItem("Authorization")) {
      // 让每个请求携带token-- ['Authorization']为自定义key 请根据实际情况自行修改
      config.headers["Authorization"] = "Bearer " + getToken();
    }
    return config;
  },
  (error) => {
    // Do something with request error
    // console.log('error', error) // for debug
    Promise.reject(error);
  }
);

// respone interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data;
  
    // if (res.code === 200) return Promise.resolve(res);
    // } else return Promise.reject(res);
    if (res.code === 401) {
      window.sessionStorage.removeItem("Authorization")
      store.commit("frontend/login/removeToken")
      router.push({ path: "/user/login" })
    }

    return res;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default service;
