import axios from "axios";
import { getToken } from "@/util/auth";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { Message } from "element-ui";
import router from "@/router";
var instance = axios.create({
  timeout: 10000,
});

instance.interceptors.request.use(
  (config) => {
    // config.headers['content-type'] = 'application/json'

    // config.headers['Shop-Id'] = localStorage.getItem('shopId') || 1

    // 在发送请求之前做些什么
    // config.headers['content-type'] = 'application/json'
    config.headers.Authorization = "Bearer " + getToken(); // 请求头
    NProgress.start();
    // console.log(config, '1111') // for debug

    return config;
  },
  (error) => {
    // 对请求错误做些什么
    console.log(error, "222222"); // for debug
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    NProgress.done();
    const res = response.status;
    // 对响应数据做点什么
    // console.log(response, '33333') // for debug
    if (res === 200 || res === 201) {
      return response;
    }
  },
  (error) => {
    // 对响应错误做点什么
    if (error.response.status === 400) {
      Message({
        message: error.response.data.errorMessage,
        type: "error",
      });
    }

    if (error.response.status === 500) {
      Message({
        message: error.response.data.message,
        type: "error",
      });
    }
    // console.log(error, "44444"); // for debug
    // if (error.response.status === 401) {
    //   Message({
    //     message: '账户登录过期,请重新登录',
    //     type: 'error'

    //   })
    //   router.push('/login')
    // } else {
    //   Message({
    //     message: error.response || 'Error',
    //     type: 'error'
    //   })
    // }

    return Promise.reject(error);
  }
);

export default instance;
