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")) {
    config.headers.sessionId = localStorage.getItem("token");
  }
  return config;
});
service.interceptors.response.use(
  // (response) => {
  //   if (response.status === 200) {
  //     return response.data;
  //   } else {
  //     Promise.reject();
  //   }
  // },
  // (error) => {
  //   console.log(error);
  //   return Promise.reject();
  // }

  (response) => {
    const res = response.data;
    if (res.code !== 200) {
      Message({
        message: res.msg || "Error",
        type: "error",
        duration: 5 * 1000,
      });
      if (res.code === 401) {
        // Message({ message: '重新登录', type: 'error', duration: 5 * 1000 })
        router.push("/login");
      }
      return Promise.reject(new Error(res.msg || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    Message({ message: error.message, type: "error", duration: 5 * 1000 });
    return Promise.reject(error);
  }
);

export default service;
