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

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 (
        [
          ResponseStatusCode.TOKEN_INVALID,
          ResponseStatusCode.TOKEN_INVALID2,
        ].includes(response.code)
      ) {
        showMessage("登录失效!");
        removeTokenInfo();
        globalThis.location.href = "#/login";
      }

      return response;
    }
  ),
});
