import { ref, onBeforeUnmount } from "vue";
import { useVueFlow } from "@vue-flow/core";
import { ElMessage } from "element-plus";
import { uploadMedia } from "@/api/flow";
import meinv from '@/static/image/meinv.png'
import huaban from '@/static/image/huaban.png'
import aaa from '../../../../public/aaa.mp4'
import longimg from '@/static/image/long.png'

const acceptByType: Record<string, string> = {
  image: "image/*",
  video: "video/*",
  audio: "audio/*",
};

/**
 * 节点内上传 composable：每个媒体节点（image/video/audio）共用。
 * 内部自建 file input，点击 triggerUpload() 弹文件选择 → uploadMedia → 写入 node.data.url
 */
export function useNodeUpload(nodeId: string, nodeType: string, options?: { onSuccess?: () => void }) {
  const { findNode } = useVueFlow();
  const uploading = ref(false);
  let input: HTMLInputElement | null = null;

  const ensureInput = () => {
    if (input) return input;
    input = document.createElement("input");
    input.type = "file";
    input.accept = acceptByType[nodeType] ?? "*/*";
    input.style.display = "none";
    input.addEventListener("change", onChange);
    document.body.appendChild(input);
    return input;
  };

  const onChange = async (e: Event) => {
    const target = e.target as HTMLInputElement;
    const file = target.files?.[0];
    target.value = "";
    if (!file) return;

    if (!file.type.startsWith(nodeType)) {
      ElMessage.warning("文件类型与节点类型不匹配");
      return;
    }
    const node = findNode(nodeId);
    if (!node) return;
    node.data = { ...(node.data ?? {}), url: nodeType ==='image' ? huaban : aaa };
    options?.onSuccess?.();
    // uploading.value = true;
    // try {
    //   const res = await uploadMedia(file);
    //   const url = res?.url;
    //   if (!url) throw new Error("上传接口未返回 url");
    //   const node = findNode(nodeId);
    //   if (!node) return;
    //   node.data = { ...(node.data ?? {}), url };
    //   options?.onSuccess?.();
    // } catch (err: any) {
    //   console.error("上传失败", err);
    //   ElMessage.error("上传失败：" + (err?.message || "未知错误"));
    // } finally {
    //   uploading.value = false;
    // }
  };

  const triggerUpload = () => {
    ensureInput().click();
  };

  onBeforeUnmount(() => {
    if (input) {
      input.removeEventListener("change", onChange);
      input.remove();
      input = null;
    }
  });

  return { uploading, triggerUpload };
}
