import Vue from "vue";
import { ElMessageOptions, ElMessageComponent } from "element-ui/types/message";
import { Message as elMage } from "element-ui";

let instance: ElMessageComponent | null = null;
const showMessage = (options: ElMessageOptions) => {
  if (instance) instance.close();
  instance = elMage(options);
};

const $message = Object.assign(
  (message: string | ElMessageOptions, options?: ElMessageOptions) => {
    if (typeof message === "string")
      return showMessage({ type: "info", ...options, message });
    showMessage(message);
  },
  {
    success(message: string, options?: ElMessageOptions) {
      showMessage({ ...options, type: "success", message });
    },
    warning(message: string, options?: ElMessageOptions) {
      showMessage({ ...options, type: "warning", message });
    },
    info(message: string, options?: ElMessageOptions) {
      showMessage({ ...options, type: "info", message });
    },
    error(message: string, options?: ElMessageOptions) {
      showMessage({ ...options, type: "error", message });
    }
  }
);
export const Message = $message;
export default {
  install(vue: typeof Vue) {
    Object.assign(vue.prototype, {
      $message
    });
  }
};
