import axios from "axios";
import router from "../router/index.js";
import { Undertheshelf } from "../view/namespace.js";
import { undefinedCollect } from "./index.js";
import { getToken, refreshToken } from "./config";
import { addPendingRequest, removePendingRequest } from "./cancelRepeatRquest";
import { Toast } from "mint-ui";
// var instance = axios.create(
//   process.env.NODE_ENV === "development"
//     ? {
//         baseURL: "http://site1.aizhuishu.com/api",
//         withCredentials: true
//       }  
//     : {
//         baseURL: "/api"
//       }
// );
const whiteList = ["/login", "/hashuserToToken"];

var instance = axios.create({
  baseURL: "/api"
});

instance.interceptors.response.use(
  async res => {
    if (res.data.code === 0) { 
      //removePendingRequest(res);
      return res.data.data;
    }
    if (
      res.data.code === 10001 ||
      res.data.code === 10023 ||
      res.data.code === 10035
    ) {
      Toast("重新登录中");
      await refreshToken();
      return axios(res.config);
    }
    if (res.data.code === 10018) {
      router.replace(Undertheshelf.route);
    } else {
      return Promise.reject(res);
    }
  },
  error => {
    //removePendingRequest(error.config || {});
    return Promise.reject(error);
  }
);
instance.interceptors.request.use(async function(config) {
  let token = localStorage.getItem("token");

  if (!whiteList.includes(config.url) && !token) {
    console.log(config.url);
    token = await getToken(config);
  }else{
    config.cancelRequest = true;
    //addPendingRequest(config);

  }

  if (token) {
    config.headers.Authorization = `bearer ${token}`;
  }
  if (
    config.method === "get" &&
    config.url &&
    config.url.indexOf("undefined") !== -1
  ) {
    undefinedCollect({
      name: "undefined",
      content: JSON.stringify({
        current_page: location.href,
        next_page: window.nextPage,
        prev_page: window.prevPage,
        api: config.url,
        user_id: window.options && window.options.uid,
        channel_id: window.options && window.options.distribution_channel_id
      })
    });
  }
  
  return config;
});

export default instance;
