import type { Ref } from "vue";
import { useVueFlow } from "@vue-flow/core";

// ============ 跨域图片加载工具 ============
// 跨域图片转 base64 后加载，避免 canvas tainted
const loadImageSafe = (url: string): Promise<HTMLImageElement> => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "anonymous";
    img.onload = () => resolve(img);
    img.onerror = () => {
      fetch(url, { mode: "cors" })
        .then((r) => r.blob())
        .then((blob) => {
          const reader = new FileReader();
          reader.onload = () => {
            const img2 = new Image();
            img2.onload = () => resolve(img2);
            img2.onerror = reject;
            img2.src = reader.result as string;
          };
          reader.onerror = reject;
          reader.readAsDataURL(blob);
        })
        .catch(reject);
    };
    img.src = url;
  });
};

// canvas 镜像翻转 → base64
const mirrorImage = (img: HTMLImageElement, type: string): string => {
  const canvas = document.createElement("canvas");
  canvas.width = img.naturalWidth;
  canvas.height = img.naturalHeight;
  const ctx = canvas.getContext("2d")!;

  if (type === "horizontal") {
    ctx.translate(canvas.width, 0);
    ctx.scale(-1, 1);
  } else {
    ctx.translate(0, canvas.height);
    ctx.scale(1, -1);
  }
  ctx.drawImage(img, 0, 0);
  return canvas.toDataURL("image/png");
};

/**
 * 节点操作：镜像、裁剪确认、断开父子连接
 * 需要 vueFlow 传入 selectedNode 和 selectedNodeId
 */
export function useNodeOperations(
  selectedNode: Ref<any>,
  selectedNodeId: Ref<string | null>,
  panelForm: Ref<any>,
) {
  const { addNodes, addEdges, getNodes, setNodes, getEdges, removeEdges, findNode } = useVueFlow();

  // 共用：创建图片子节点 + 连线 + 选中
  const createChildNode = (
    parentNode: any,
    url: string,
    label: string,
    title: string,
  ) => {
    const clearedNodes = getNodes.value.map((n) => ({ ...n, selected: false }));
    setNodes(clearedNodes);

    const newNodeId = `node_${Date.now()}`;
    const offsetX = 200;
    addNodes({
      id: newNodeId,
      type: "image",
      position: { x: parentNode.position.x + offsetX, y: parentNode.position.y },
      selected: true,
      data: { label, title, url, isChildOf: parentNode.id },
    } as any);
    addEdges({
      id: `e${parentNode.id}-${newNodeId}`,
      source: parentNode.id,
      target: newNodeId,
    });
    selectedNodeId.value = newNodeId;
  };

  // 镜像：将选中节点的图片翻转后生成新图片，添加为子节点
  const mirror = async (type: string) => {
    const node = selectedNode.value;
    if (!node || !node.data?.url) return;

    try {
      const img = await loadImageSafe(node.data.url);
      const mirroredUrl = mirrorImage(img, type);
      createChildNode(
        node,
        mirroredUrl,
        "镜像图片",
        type === "horizontal" ? "水平镜像" : "垂直镜像",
      );
    } catch (err) {
      console.error("镜像失败", err);
    }
  };

  // 裁剪确认：创建子节点
  const onCropConfirm = (img: string) => {
    const node = selectedNode.value;
    if (!node || !img) return;
    createChildNode(node, img, "裁剪图片", "裁剪结果");
  };

  // 涂鸦确认：创建子节点
  const onDoodleConfirm = (img: string) => {
    const node = selectedNode.value;
    if (!node || !img) return;
    createChildNode(node, img, "涂鸦图片", "涂鸦结果");
  };

  // 删除下方面板继承的图片/视频，并断开当前节点与父节点的连接
  const delNodeBottomFile = () => {
    const node = selectedNode.value;
    if (!node) return;

    // 1. 清空下方面板的图片/视频
    panelForm.value = { ...panelForm.value, imgUrl: "", videoUrl: "" };

    // 2. 断开与父节点的连接
    const incomingEdges = getEdges.value.filter((e) => e.target === node.id);
    if (incomingEdges.length > 0) {
      removeEdges(incomingEdges.map((e) => e.id));

      incomingEdges.forEach((e) => {
        const parent = findNode(e.source);
        if (parent && parent.data?.isParentOf === node.id) {
          parent.data = { ...parent.data, isParentOf: undefined };
        }
      });
    }

    // 3. 清除当前节点的 isChildOf 标记
    if (node.data?.isChildOf) {
      node.data = { ...node.data, isChildOf: undefined };
    }
  };

  return { mirror, onCropConfirm, onDoodleConfirm, delNodeBottomFile };
}
