import { defineStore } from "pinia";
import { ref } from "vue";
import { ElMessage } from "element-plus";

let progressTimer: ReturnType<typeof setInterval> | null = null;
let activeController: AbortController | null = null;

function clearProgressTimer() {
  if (progressTimer) {
    clearInterval(progressTimer);
    progressTimer = null;
  }
}

export const useSimpleUploadOverlayStore = defineStore("simple-upload-overlay", () => {
  const show = ref(false);
  const percent = ref(0);
  const title = ref("上传中");
  const cancelText = ref("取消上传");

  function beginUpload(opts?: { title?: string }) {
    activeController?.abort(new DOMException("已开始新的上传", "AbortError"));
    clearProgressTimer();
    activeController = new AbortController();
    title.value = opts?.title ?? "上传中";
    percent.value = 3;
    show.value = true;
    progressTimer = setInterval(() => {
      if (percent.value < 88) {
        percent.value = Math.min(88, percent.value + 2 + Math.random() * 6);
      }
    }, 260);
    return activeController.signal;
  }

  function bumpToComplete() {
    clearProgressTimer();
    percent.value = 100;
  }

  function dismiss() {
    clearProgressTimer();
    show.value = false;
    percent.value = 0;
    activeController = null;
  }

  function userCancel() {
    activeController?.abort(new DOMException("用户已取消上传", "AbortError"));
    dismiss();
    ElMessage.info("取消上传");
  }

  /** 供 skipSimpleUploadOverlay 的上传与 beginUpload 配套，把 fetch 绑到同一 AbortSignal */
  function getActiveAbortSignal(): AbortSignal | undefined {
    return activeController?.signal;
  }

  return {
    show,
    percent,
    title,
    cancelText,
    beginUpload,
    bumpToComplete,
    dismiss,
    userCancel,
    getActiveAbortSignal
  };
});
