import React from "react";
import classNames from "classnames";
import { message as antdMessage } from "antd";
import { TYIcon } from "../../TYIcon";
import { isFunction, isObject } from "lodash";
import { tyMessageCls } from "./styled";
import { ArgsProps } from "antd/es/message";
import { MessageInstance } from "antd/es/message/interface";
// import { myRoot } from '../../../util/constant';

let internalMessage: MessageInstance | undefined;

export function setInternalMessage(value: MessageInstance | undefined) {
  internalMessage = value;
}

type Message = typeof antdMessage;
type TypeOpen = (typeof antdMessage)["success"];
type Params = Parameters<TypeOpen>;
type ParamContent = Params[0];
type ParamDuration = Params[1];
type ParamOnClose = Params[2];

function isArgsProps(content: ParamContent): content is ArgsProps {
  return (
    Object.prototype.toString.call(content) === "[object Object]" &&
    !!(content as ArgsProps).content
  );
}

const wrapperTypeOpen =
  (type: "success" | "info" | "error" | "warning" | "loading", params: Partial<ParamContent>) =>
  (content: ParamContent, duration?: ParamDuration, onClose?: ParamOnClose) => {
    if (isFunction(duration)) {
      // eslint-disable-next-line no-param-reassign
      onClose = duration;
      // eslint-disable-next-line no-param-reassign
      duration = undefined;
    }
    const userParams = (isObject(params) ? params : {}) as Record<string, any>;
    const config = (isArgsProps(content) ? content : {}) as Record<string, any>;
    const renderContent = !isArgsProps(content) ? content : undefined;
    const { className, ...restConfig } = config;

    if (restConfig.key) {
      if (internalMessage) {
        internalMessage.destroy();
      } else {
        antdMessage.destroy(restConfig.key);
      }
    }
    const passParams = {
      ...userParams,
      content: renderContent,
      duration,
      onClose,
      className: classNames(tyMessageCls, className),
      ...restConfig,
    };

    if (internalMessage) {
      return internalMessage[type](passParams);
    } else {
      return antdMessage[type](passParams);
    }
  };

function destroy(key?: React.Key) {
  if (internalMessage) {
    return internalMessage.destroy(key);
  }
  return antdMessage.destroy(key);
}

export const message: Message = {
  ...antdMessage,
  success: wrapperTypeOpen("success", {
    icon: <TYIcon type="tongyi-checkCircle-line" />,
  }),
  error: wrapperTypeOpen("error", {
    icon: <TYIcon type="tongyi-errorCircle-line" />,
  }),
  info: wrapperTypeOpen("info", {
    icon: <TYIcon type="tongyi-info-line" />,
  }),
  warning: wrapperTypeOpen("warning", {
    icon: <TYIcon type="tongyi-warningCircle-line" />,
  }),
  loading: wrapperTypeOpen("loading", {
    icon: <TYIcon type="extend-loading-line" className="ty-spin-icon" spin />,
  }),
  destroy,
};
