import type { ToastOptions as VantToastOptions, ToastWrapperInstance as VantToastWrapperInstance } from 'vant';
import { closeToast, showToast } from 'vant';
import 'vant/es/toast/style';


type ToastOptions = Omit<VantToastOptions, 'message'>;

export class Toast {
  static show(message: string, options?: ToastOptions) {
    const toastRef = showToast({ message, ...options });
    return { toastRef, close: () => toastRef.close() };
  }

  static close() { closeToast(true); }

  static success(message: string, options?: ToastOptions) {
    return this.show(message, { ...options, closeOnClick: true, closeOnClickOverlay: true, type: 'success' });
  }

  static warning(message: string, options?: ToastOptions) {
    return this.show(message, { ...options, icon: 'warning-o' });
  }

  static error(message: string, options?: ToastOptions) {
    return this.show(message, { ...options, type: 'fail' });
  }

  static loading(delay = 0, options?: ToastOptions & { message?: string }) {
    const fn = () => this.show(options?.message ?? '加载中...', {
      ...options,
      type: 'loading',
      closeOnClick: false,
      closeOnClickOverlay: false,
      forbidClick: true,
      duration: 0,
    });
    if (delay === 0) { return fn(); }
    const timer = setTimeout(() => {
      ({ toastRef: ref.toastRef, close: ref.close } = fn());
    }, delay);
    const ref = {
      toastRef: null as VantToastWrapperInstance | null,
      cancel: () => clearTimeout(timer),
      close: () => clearTimeout(timer),
    };
    return ref;
  }
}