import { ref, reactive, watchPostEffect, computed } from 'vue'
import { defineStore } from 'pinia'
import { isUndefined } from 'lodash';
import Queue from 'yocto-queue';

export const useDialogStore = defineStore('dialog', () => {
  type Title = "Error" | "Info" | "Warn";
  const enableDialog = ref(false);
  const isDialogOpen = ref(false);
  const dialogTitle = ref<Title>("Error");
  const dialogContent = ref("这是一个错误");
  const contentQueue = new Queue<{ type: Title; content: string }>()

  function openDialog(title?: Title, content?: string) {
    if (isUndefined(title)) {
      if (contentQueue.size != 0) {
        const dialog = contentQueue.dequeue();
        if (isUndefined(dialog)) return;
        openDialog(dialog.type, dialog.content);
      }
    } else {
      if (!isUndefined(content) && content.length != 0)
        dialogContent.value = content;
      dialogTitle.value = title;
      isDialogOpen.value = true;
    }
  }

  function closeDialog() {
    isDialogOpen.value = false;

    openDialog();
  }

  function info(content: string) {
    contentQueue.enqueue({ type: "Info", content: content });
    openDialog();
    // openDialog("Info", content);
  }

  function error(content: string) {
    contentQueue.enqueue({ type: "Error", content: content });
    openDialog();
    // openDialog("Error", content);
  }

  function warn(content: string) {
    contentQueue.enqueue({ type: "Warn", content: content });
    openDialog();
    // openDialog("Warn", content);
  }

  return {
    enableDialog,
    isDialogOpen,
    dialogTitle,
    dialogContent,
    dialogQueue: contentQueue,
    openDialog,
    closeDialog,
    info,
    error,
    warn
  }
})

