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";

/**
 * 定义请求元数据
 */
declare global {
  interface DageRequestMeta {
    /**
     * 显示全局 错误信息, 默认为 false
     */
    showError?: boolean;
  }
}

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();
      const { showError = true } = request.meta;

      if (
        [
          ResponseStatusCode.TOKEN_INVALID,
          ResponseStatusCode.TOKEN_INVALID2,
        ].includes(response.code)
      ) {
        showMessage("登录失效!");
        removeTokenInfo();
        globalThis.location.href = "#/login";
      } else if (response.code !== ResponseStatusCode.SUCCESS) {
        const message = response.__raw__.data.msg ?? "系统出差中";
        // 错误信息映射
        response.errorMessage = message;
        if (showError) {
          showMessage(message);
        }
      }

      return response;
    }
  ),
});
