import axios from "axios";
import { MessageBox, Message } from "element-ui";
import router from "../router/index";

const service = axios.create({
  // process.env.NODE_ENV === 'development' 来判断是否开发环境
  // easy-mock服务挂了，暂时不使用了
  // baseURL: '',
  // timeout: 5000
  baseURL: "api", //把原来的项目地址，改成api，解决跨域问题
  timeout: 30000,
});

service.interceptors.request.use((config) => {
  if (localStorage.getItem("token")) {
    // console.log("aaaaaaaaaaaaaa", localStorage.getItem("token"));
    config.headers.Authorization = localStorage.getItem("token");
  }
  return config;
});
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 200) {
      if (res.code === 401) {
        Message({
          showClose: true,
          message: res.msg,
          type: "error",
          duration: 1500,
        });
        localStorage.removeItem("token");
        router.push("/login");
      }

      if (res.code === 400) {
        Message({
          showClose: true,
          message: res.msg,
          type: "error",
          duration: 1500,
        });
      }
      if (res.code === 500) {
        //alert(res.msg || "Error");

        Message({
          showClose: true,
          message: res.msg,
          type: "error",
          duration: 1500,
        });
      }
     if (!res.code) { // 如果没有返回code，可能是下载excel
        // return resolve(response.data, res);
        return res
      }
      return Promise.reject(new Error(res.msg || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    Message({
      message: error.message,
      showClose: true,
      type: "error",
      duration: 1500,
    });
    return Promise.reject(error);
  }
);

export default service;
