import axios from "axios";
import history from "./history";
import { getTokenInfo, removeTokenInfo } from "./storage";
import store from "@/store";
import { MessageFu } from "./message";
// 请求基地址
export const baseURL =
  // 线下的图片地址需要加上/api/
  process.env.NODE_ENV === "development"
    ? "http://192.168.20.55:8041/api/"
    : "";
// process.env.NODE_ENV === "development" ? "https://xuzhouwall.4dage.com" : "";

// 处理  类型“AxiosResponse<any, any>”上不存在属性“code”
declare module "axios" {
  interface AxiosResponse {
    code: number;
    // 这里追加你的参数
  }
}

// 创建 axios 实例
const http = axios.create({
  // --------线下的地址不用加/api/
  baseURL: baseURL,

  // --------打包或线上环境接口需要加上api/
  // baseURL: baseURL + "/api/",
  timeout: 5000,
});

let axajInd = 0;

// 请求拦截器
http.interceptors.request.use(
  function (config: any) {
    // 发请求前打开加载提示
    if (!store.getState().loginStore.asyncLoding)
      store.dispatch({ type: "login/asyncLoding", payload: true });

    axajInd++;

    const { token } = getTokenInfo();
    if (token) config.headers.token = token;
    return config;
  },
  function (err) {
    return Promise.reject(err);
  }
);

let timeId = -1;

// 响应拦截器
http.interceptors.response.use(
  function (response) {
    // 请求回来的关闭加载提示
    axajInd--;
    if (axajInd === 0) {
      if (store.getState().loginStore.asyncLoding)
        store.dispatch({ type: "login/asyncLoding", payload: false });
    }
    if (response.data.code === 5001 || response.data.code === 5002) {
      clearTimeout(timeId);
      timeId = window.setTimeout(() => {
        removeTokenInfo();
        MessageFu.warning("登录失效!");
        history.push("/login");
      }, 200);
    } else if (response.data.code === 0) {
      // MessageFu.success(response.data.msg);
    } else if (response.data.code === 3014)
      MessageFu.warning("用户名不存在或密码错误，请联系管理员!");
    else MessageFu.warning(response.data.msg);
    return response.data;
  },
  async function (err) {
    axajInd = 0;
    if (store.getState().loginStore.asyncLoding)
      store.dispatch({ type: "login/asyncLoding", payload: false });

    // 上传附件的进度条
    const UpAsyncLodingDom: any = document.querySelector("#UpAsyncLoding");
    const progressDom: any = document.querySelector("#progress");

    // 如果因为网络原因，response没有，给提示消息
    if (!err.response) {
      if (store.getState().loginStore.closeUpFile.state)
        MessageFu.success("取消上传!");
      else MessageFu.warning("网络繁忙，请稍后重试!");
    } else {
      MessageFu.warning("错误!");
    }

    // 响应错误也要取消 上传文件的进度条
    UpAsyncLodingDom.style.opacity = 0;
    UpAsyncLodingDom.style.pointerEvents = "none";
    progressDom.style.width = "0%";

    return Promise.reject(err);
  }
);

// 导出 axios 实例
export default http;
