import { compose, initial } from "@dage/service";
import { getTokenInfo, removeTokenInfo } from "@dage/pc-components";
import { message } from "antd";
import { NoticeType } from "antd/es/message/interface";

const showMessage = (msg: string, type: NoticeType = "error") => {
  message.open({
    type,
    content: msg,
    duration: 4,
  });
};

initial({
  fetch: window.fetch.bind(window),
  baseURL: process.env.REACT_APP_API_URL as string,
  interceptor: compose(
    (request, next) => {
      const { token } = getTokenInfo();
      if (token) {
        request.headers["token"] = token;
      }
      return next();
    },
    // 登陆失效
    async (request, next) => {
      const response = await next();

      if ([5001, 5002].includes(response.code)) {
        const msg = "登录失效!";
        showMessage(msg);
        removeTokenInfo();
        globalThis.location.href = "#/login";
      }

      return response;
    }
  ),
});
