import { message } from "antd";
import { MessageInstance } from "antd/es/message/interface";
import { AxiosError } from "axios";
import React, { createContext, useContext, useState } from "react";

interface IGlobalContext {
  children: React.ReactNode;
  messageApi: MessageInstance;
  contextHolder: React.ReactNode;
  ErrorHandle: (error: any) => void;
}

export const GlobalContext = createContext<IGlobalContext | null>(null);

// ErrorHandle 仅处理 400 错误，此错误为业务逻辑相关错误
type Error = {
  reason: string;
  msg: string;
  details?: any;
};

export const GlobalContextProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const [messageApi, contextHolder] = message.useMessage();

  function ErrorHandle(error: any) {
    const err = error as AxiosError;

    if (!err.response || !err.response.data) {
      return;
    }
    const data = err.response.data as Error;

    const key = Date.now().toString();
    messageApi.error({
      content: `${data.msg} ${data.details?.length > 0 ? "😦" : ""}`,
      duration: 4,
      key: key,
      onClick(e) {
        messageApi.destroy(key);
        data.details?.map((v: string) => {
          if (v) {
            message.error({
              content: v,
              duration: 4,
            });
          }
        });
      },
    });
  }

  return (
    <GlobalContext.Provider
      value={{ children, messageApi, contextHolder, ErrorHandle }}
    >
      {contextHolder}
      {children}
    </GlobalContext.Provider>
  );
};

export const useGlobal = () => {
  const context = useContext(GlobalContext);
  if (!context) {
    throw new Error("useGlobal must be used within an GlobalContextProvider");
  }
  return context;
};
