import { ElMessage } from "element-plus";
import { useSimpleUploadOverlayStore } from "@/stores/modules/simpleUploadOverlay";

function sleep(ms: number) {
  return new Promise<void>(resolve => setTimeout(resolve, ms));
}

/**
 * 使用全局 PopupLoading 包裹「/upload/simple」类上传；成功后提示「上传成功」。
 * 取消（AbortError）不弹成功提示；失败时关闭弹层，由调用方决定是否 ElMessage.error。
 * `successMessage === null` 时不弹成功提示（用于上传后还要继续审核等场景）。
 */
export async function withSimpleUploadOverlay<T>(
  task: (signal: AbortSignal) => Promise<T>,
  options?: { title?: string; successMessage?: string | null }
): Promise<T> {
  const overlay = useSimpleUploadOverlayStore();
  const signal = overlay.beginUpload({ title: options?.title });
  try {
    const result = await task(signal);
    overlay.bumpToComplete();
    await sleep(280);
    overlay.dismiss();
    if (options?.successMessage !== null) {
      ElMessage.success(options?.successMessage ?? "上传成功");
    }
    return result;
  } catch (e) {
    overlay.dismiss();
    throw e;
  }
}
