<template>
  <div class="w-full">
    <a-collapse v-model:activeKey="activeKey" :accordion="true">
      <a-collapse-panel key="1">
        <template #header>
          <span class="ks-model-builder-title-icon icon-model"></span>控制节点
        </template>
        <div class="w-full h-full">
          <a-row>
            <a-col v-for="nm in controlTemplates" :span="12">
              <div
                :key="nm.id"
                :data-type="nm.type"
                class="ks-model-drag-item"
                @dragend="handleDragEnd"
                @dragstart="handleDragStart($event, nm)"
              >
                <img :alt="nm.name ?? ''" class="icon" src="@/assets/icons/model-4.svg" />
                <span class="desc">{{ nm.name }}</span>
              </div>
            </a-col>
          </a-row>
        </div>
      </a-collapse-panel>
      <a-collapse-panel key="2">
        <template #header>
          <span class="ks-model-builder-title-icon icon-model"></span>条件节点
        </template>
        <div class="w-full h-full">
          <a-row>
            <a-col v-for="nm in conditionTemplates" :span="12">
              <div
                :key="nm.id"
                :data-type="nm.type"
                class="ks-model-drag-item"
                @dragend="handleDragEnd"
                @dragstart="handleDragStart($event, nm)"
              >
                <img :alt="nm.name ?? ''" class="icon" src="@/assets/icons/model-4.svg" />
                <span class="desc">{{ nm.name }}</span>
              </div>
            </a-col>
          </a-row>
        </div>
      </a-collapse-panel>
      <a-collapse-panel key="3">
        <template #header>
          <span class="ks-model-builder-title-icon icon-model"></span>行为节点
        </template>
        <div class="w-full h-full">
          <a-row>
            <a-col v-for="nm in actionsTemplates" :span="12">
              <div
                :key="nm.id"
                :data-type="nm.type"
                class="ks-model-drag-item"
                @dragend="handleDragEnd"
                @dragstart="handleDragStart($event, nm)"
              >
                <img :alt="nm.name ?? ''" class="icon" src="@/assets/icons/model-4.svg" />
                <span class="desc">{{ nm.name }}</span>
              </div>
            </a-col>
          </a-row>
        </div>
      </a-collapse-panel>
    </a-collapse>


    <!--    <a-card class="ks-model-builder-card">-->
    <!--      <template #title>-->
    <!--        <span class="ks-model-builder-title-icon icon-model"></span>控制节点-->
    <!--      </template>-->
    <!--      <div-->
    <!--        v-for="nm in controlTemplates"-->
    <!--        :key="nm.id"-->
    <!--        :data-type="nm.type"-->
    <!--        class="ks-model-drag-item"-->
    <!--      >-->
    <!--        <img class="icon" src="@/assets/icons/model-4.svg" :alt="nm.name ?? ''"/>-->
    <!--        <span class="desc">{{ nm.name }}</span>-->
    <!--      </div>-->
    <!--    </a-card>-->

    <!--    <a-card class="ks-model-builder-card">-->
    <!--      <template #title>-->
    <!--        <span class="ks-model-builder-title-icon icon-model"></span>条件节点-->
    <!--      </template>-->
    <!--      <div-->
    <!--        v-for="nm in conditionTemplates"-->
    <!--        :key="nm.id"-->
    <!--        :data-type="nm.type"-->
    <!--        class="ks-model-drag-item"-->
    <!--      >-->
    <!--        <img class="icon" src="@/assets/icons/model-4.svg" :alt="nm.name ?? ''"/>-->
    <!--        <span class="desc">{{ nm.name }}</span>-->
    <!--      </div>-->
    <!--    </a-card>-->

    <!--    <a-card class="ks-model-builder-card">-->
    <!--      <template #title>-->
    <!--        <span class="ks-model-builder-title-icon icon-model"></span>行为节点-->
    <!--      </template>-->
    <!--      <div-->
    <!--        v-for="nm in actionsTemplates"-->
    <!--        :key="nm.id"-->
    <!--        :data-type="nm.type"-->
    <!--        class="ks-model-drag-item"-->
    <!--      >-->
    <!--        <img class="icon" src="@/assets/icons/model-4.svg" :alt="nm.name ?? ''"/>-->
    <!--        <span class="desc">{{ nm.name }}</span>-->
    <!--      </div>-->
    <!--    </a-card>-->

  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import { defaultNodeTemplateData, defaultNodeTemplateQuery } from './constants';
import type { NodeTemplate, NodeTemplateData, NodeTemplateQuery } from './types';
import { findTemplatesByQuery } from './api';
import { safePreventDefault, safeStopPropagation } from '@/utils/event';

export default defineComponent({
  emits: ['drag-item-start', 'drag-item-end'],
  setup(_props, { emit }) {

    const activeKey = ref<number>(1);
    const templateData = ref<NodeTemplateData>({ ...defaultNodeTemplateData });
    const templateQuery = ref<NodeTemplateQuery>({ ...defaultNodeTemplateQuery });
    const isDraggingOver = ref(false);
    const draggedNodeData = ref<NodeTemplate | null>(null);

    // 控制节点
    const controlTemplates = ref<NodeTemplate[]>([]);
    // 条件节点
    const conditionTemplates = ref<NodeTemplate[]>([]);
    // 行为节点
    const actionsTemplates = ref<NodeTemplate[]>([]);

    const loadTress = () => {
      controlTemplates.value = [];
      conditionTemplates.value = [];
      actionsTemplates.value = [];

      findTemplatesByQuery(templateQuery.value).then(r => {
        templateData.value = r.data;
        if (r.data.templates) {
          r.data.templates.forEach(tpl => {
            if (tpl.type === 'action') {
              if (tpl.parameter_defs && tpl.parameter_defs.length > 0) {
                actionsTemplates.value.push(tpl);
              }
            } else if (tpl.type === 'parallel' || tpl.type === 'sequence' || tpl.type === 'precondition') {
              conditionTemplates.value.push(tpl);
            } else {
              controlTemplates.value.push(tpl);
            }
          });
        }
      });
    };

    const handleDragStart = (e: DragEvent, nm: NodeTemplate) => {
      draggedNodeData.value = nm;

      if (e.dataTransfer) {
        e.dataTransfer.setData('text/plain', JSON.stringify(draggedNodeData.value));
        e.dataTransfer.effectAllowed = 'copyMove';

        const dragPreview = document.createElement('div');
        dragPreview.textContent = draggedNodeData.value.name || '';
        dragPreview.style.cssText = `
          position: absolute;
          top: -1000px;
          padding: 6px 12px;
          background: #3b82f6;
          color: white;
          border-radius: 6px;
          font-size: 12px;
          font-weight: 500;
        `;
        document.body.appendChild(dragPreview);
        e.dataTransfer.setDragImage(dragPreview, dragPreview.offsetWidth / 2, dragPreview.offsetHeight / 2);
        emit('drag-item-start', nm, isDraggingOver.value, e);
        console.log('开始拖动:', nm);
        setTimeout(() => document.body.removeChild(dragPreview), 0);
      }
    };

    const handleDragEnd = (e: DragEvent) => {
      safePreventDefault(e);
      safeStopPropagation(e);
      isDraggingOver.value = false;
      console.log('拖动结束');
      emit('drag-item-end', isDraggingOver.value, e);
    };

    onMounted(() => {
      loadTress();
    });

    return {
      activeKey,

      controlTemplates,
      conditionTemplates,
      actionsTemplates,

      handleDragStart,
      handleDragEnd,
    };
  },
});

</script>