import { ElMessage } from 'element-plus';

let msgBoxInstance: any = null;
/**
 * [showMessage 统一封装消息]
 *
 * @return  {[params]}  [return description]
 */
export const showMessage = (params: {
  type: string;
  message: string;
  icon?: string;
  duration?: number;
}) => {
  if (msgBoxInstance) {
    msgBoxInstance.close();
  }
  msgBoxInstance = ElMessage(params as any);
};

export const safeJsonParse = (val: string, defaultValue?: any) => {
  try {
    return JSON.parse(val);
  } catch {
    return defaultValue ?? {};
  }
};

/**
 * [倒计时]
 *
 * @return  {[params]}  [return description]
 */
export function startCountdown(
  duration: number,
  onTick?: (args: number) => void,
  onComplete?: () => void
) {
  let time = duration;
  const timer = setInterval(() => {
    time--;
    if (typeof onTick === "function") {
      onTick(time);
    }
    if (time <= 0) {
      clearInterval(timer);
      if (typeof onComplete === "function") {
        onComplete();
      }
    }
  }, 1000);
}
