<template>
  <div>
    <ElTooltip v-model:visible="visible" :show-arrow="false" placement="right" :hide-after="0" trigger="click">
      <template #content>
        <div class="mb-10 color-999">添加节点</div>
        <div class="flex flex-col gap-10 ul-box">
          <NodeTypeItem v-for="(item, index) in filteredList" class="pointer" :key="index" :item="item" @click="onAddNode(item.type)" />
        </div>
      </template>
      <Handle :type="type" :position="type === 'target' ? Position.Left : Position.Right" class="icon-handle">
        <div class="w-10 h-10 round-10 flex-center" style="background: rebeccapurple;box-shadow: 0px 0px 0px 1px #fff;">+</div>
      </Handle>
    </ElTooltip>
  </div>
</template>

<script setup lang="ts">
import { Position, Handle, HandleType, useVueFlow } from "@vue-flow/core";
import type { PropType } from "vue";
import { computed, ref } from "vue";
import NodeTypeItem from "./NodeType.vue";

const visible = ref(false);
const emit = defineEmits<{
  'node-added': [nodeId: string]
}>()
const props = defineProps({
  handleType: {
    type: String,
    default: "text", // special/default/image
  },
  type: {
    type: String as PropType<HandleType>,
    default: "source", // source/target
  },
  position: {
    type: Object as PropType<{ x: number; y: number }>,
    default: () => ({}),
  },
  data: {
    type: Object,
    default: () => ({}),
  },
  id: {
    type: String,
    default: "",
  },
});

const nodeTypeConfig: any = {
  special: {
    target: ["text"],
    source: ["text", "image", "video"],
  },
  image: {
    target: ["text", "image"],
    source: ["image", "video"],
  },
  video: {
    target: ["text", "image", "video", "audio"],
    source: ["video"],
  },
  audio: {
    target: [],
    source: ["video"],
  },
  default: {
    target: ["text", "image", "video", "audio"],
    source: ["text", "image", "video", "audio"],
  },
};
const { addNodes, addEdges, getNodes, setNodes } = useVueFlow();

const allNodeTypes: any = [
  { title: "文本", type: "text" },
  { title: "图片", type: "image" },
  { title: "视频", type: "video" },
  { title: "音频", type: "audio" },
];
// 获取允许的类型
const getAvailableTypes = (handleType: string, type: string): string[] => {
  return (
    nodeTypeConfig[handleType]?.[type] || nodeTypeConfig.default[type] || []
  );
};

// ✅ 计算属性使用
const filteredList = computed(() => {
  const availableTypes = getAvailableTypes(props.handleType, props.type);
  return allNodeTypes.filter((item: any) => availableTypes.includes(item.type));
});

function onAddNode(type: string) {
  visible.value = false;

  // 先清除所有已有节点的选中状态，避免多选
  const clearedNodes = getNodes.value.map((n) => ({ ...n, selected: false }));
  setNodes(clearedNodes);

  const isAddingParent = props.type === "target";
  const offsetX = isAddingParent ? -200 : 200;

  const newNodePosition = {
    x: props.position.x + offsetX,
    y: props.position.y,
  };

  const newNodeId = `node_${Date.now()}`;

  const typeLabelMap: Record<string, string> = {
    text: "文本",
    image: "图片",
    video: "视频",
    audio: "音频",
  };
  const newNodeTitle = typeLabelMap[type] ?? "节点";

  // 添加子节点时：把父节点上传的图片/视频地址继承到子节点的 panel 中
  // 仅 source（添加子节点）时继承；target（添加父节点）不继承
  const parentUrl = !isAddingParent ? ((props.data?.url as string) ?? "") : "";
  const parentType = props.handleType; // image / video / audio / text
  const childPanel: Record<string, any> = {
    content: "",
    selectValue: "",
    imgUrl: parentType === "image" && parentUrl ? parentUrl : "",
    videoUrl: parentType === "video" && parentUrl ? parentUrl : "",
  };

  addNodes({
    id: newNodeId,
    type,
    position: newNodePosition,
    selected: true,
    data: {
      label: `New ${type} Node`,
      title: newNodeTitle,
      panel: childPanel,
      ...(isAddingParent ? { isParentOf: props.id } : { isChildOf: props.id }),
    },
  } as any);
  addEdges({
    id: `e${props.id}-${newNodeId}`,
    source: isAddingParent ? newNodeId : props.id,
    target: isAddingParent ? props.id : newNodeId,
  });
  emit('node-added', newNodeId);
}
</script>
<style scoped lang="scss"></style>
