<script setup>
import { computed, inject } from "vue";
import { VueDraggable } from "vue-draggable-plus";
import LayerItem from "./LayerItem.vue";

defineOptions({
  name: "LayersList",
});

const props = defineProps({
  layers: Array,
  activeLayerId: String,
  sortableRootLayers: Array,
  selectedLayerIds: Array,
  isMultiSelectMode: Boolean,
  editingLayerId: String,
  editingLayerName: String,
  thumbnailManager: Object,
  groupName: String,
  expandedGroupIds: Set, // 新增：展开状态集合
  isChild: Boolean,
  parentLayerId: String, // 新增：父图层ID
});

const emit = defineEmits([
  "layer-click",
  "layer-double-click",
  "context-menu",
  "checkbox-change",
  "toggle-visibility",
  "toggle-lock",
  "delete",
  "edit-confirm",
  "edit-cancel",
  "edit-keydown",
  "touch-start",
  "touch-move",
  "touch-end",
  "update:editing-name",
  "root-layers-sort",
  "child-layers-sort",
  "cross-level-move", // 新增：跨层级移动事件
  "select-child-layer",
  "start-child-layer-edit",
  "child-context-menu",
  "finish-child-layer-edit",
  "cancel-child-layer-edit",
  "child-layer-edit-keydown",
  "toggle-group-expanded",
  // 新增子图层专用事件
  "toggle-child-visibility",
  "toggle-child-lock",
  "delete-child",
  "rename-child",
]);

// 检查图层是否被选中
const isLayerSelected = (layerId) => {
  return props.selectedLayerIds.includes(layerId);
};

// 获取图层缩略图URL
function getLayerThumbnail(layerId) {
  if (props.thumbnailManager) {
    return props.thumbnailManager.getLayerThumbnail(layerId);
  }
  return null;
}

// 事件转发方法
const forwardEvent = (eventName, ...args) => {
  emit(eventName, ...args);
};

// 处理根级图层拖拽排序
const handleRootLayersSort = (event) => {
  console.log("🔄 拖拽结束事件:", event);
  console.log("📍 当前组件信息:", {
    isChild: props.isChild,
    parentLayerId: props.parentLayerId,
    groupName: props.groupName,
  });

  // 清理拖拽样式
  const sortableContainers = document.querySelectorAll(".sortable-layers");
  sortableContainers.forEach((container) => {
    container.classList.remove("drag-mode", "drop-target", "drop-invalid");
  });

  // 检查是否为跨层级拖拽
  const { from, to, oldIndex, newIndex, item } = event;
  const isFromDifferentContainer = from !== to;

  if (isFromDifferentContainer) {
    console.log("🔀 检测到跨层级拖拽");

    // 获取被拖拽的图层ID
    const draggedLayerId =
      item.getAttribute("data-layer-id") || props.sortableRootLayers[oldIndex]?.id;

    if (!draggedLayerId) {
      console.error("❌ 无法获取被拖拽的图层ID");
      return;
    }

    // 获取容器类型信息
    const fromContainerType = from.getAttribute("data-container-type");
    const toContainerType = to.getAttribute("data-container-type");
    const fromParentId = from.getAttribute("data-parent-id");
    const toParentId = to.getAttribute("data-parent-id");

    console.log("📦 拖拽信息:", {
      fromContainerType,
      toContainerType,
      fromParentId,
      toParentId,
      draggedLayerId,
    });

    // 验证拖拽的有效性
    if (
      !validateCrossLevelMove(
        draggedLayerId,
        fromContainerType,
        toContainerType,
        fromParentId,
        toParentId
      )
    ) {
      console.warn("⚠️ 无效的跨层级移动，操作被取消");
      return;
    }

    // 发送跨层级移动事件
    emit("cross-level-move", {
      layerId: draggedLayerId,
      fromContainerType,
      toContainerType,
      fromParentId,
      toParentId,
      newIndex,
      oldIndex,
    });

    return;
  }

  // 普通的同层级拖拽排序
  if (props.isChild) {
    // 子图层事件处理
    // 确保排序只影响当前组图层的children，而不是全局layers
    emit("child-layers-sort", event, props.sortableRootLayers, props.parentLayerId);
  } else {
    emit("root-layers-sort", event);
  }
};

// 验证跨层级移动的有效性
const validateCrossLevelMove = (layerId, fromType, toType, fromParentId, toParentId) => {
  // 查找图层
  const layer = findLayerInHierarchy(layerId, fromType, fromParentId);

  if (!layer) {
    console.error("找不到要移动的图层:", layerId);
    return false;
  }

  // 检查是否为不可移动的图层
  if (layer.isBackground || layer.isFixed) {
    console.warn("背景层和固定层不能移动");
    return false;
  }

  // 检查是否试图将组图层移动到自己的子层级中（防止循环引用）
  if (toType === "child" && toParentId && isDescendantOf(toParentId, layerId)) {
    console.warn("不能将图层移动到自己的子层级中");
    return false;
  }

  return true;
};

// 在层级结构中查找图层
const findLayerInHierarchy = (layerId, containerType, parentId) => {
  if (containerType === "root") {
    return props.layers.find((layer) => layer.id === layerId);
  } else if (containerType === "child" && parentId) {
    const parent = props.layers.find((layer) => layer.id === parentId);
    return parent?.children?.find((child) => child.id === layerId);
  }
  return null;
};

// 检查是否为子层级关系（防止循环引用）
const isDescendantOf = (ancestorId, layerId) => {
  const checkChildren = (children) => {
    if (!children) return false;
    for (const child of children) {
      if (child.id === layerId) return true;
      if (child.children && checkChildren(child.children)) return true;
    }
    return false;
  };

  const ancestor = props.layers.find((layer) => layer.id === ancestorId);
  return ancestor ? checkChildren(ancestor.children) : false;
};

// 拖拽开始事件
const handleDragStart = (event) => {
  console.log("🎯 开始拖拽:", event);
  const { item } = event;

  // 为拖拽元素添加数据属性
  if (item) {
    item.setAttribute("data-dragging", "true");

    // 添加拖拽相关的样式类
    const sortableContainers = document.querySelectorAll(".sortable-layers");
    sortableContainers.forEach((container) => {
      container.classList.add("drag-mode");
    });
  }
};

// 拖拽添加事件（当元素被拖拽到新容器时）
const handleDragAdd = (event) => {
  console.log("➕ 拖拽添加:", event);
  // 这个事件在跨容器拖拽时会触发
};

// 拖拽移除事件（当元素被从容器中移除时）
const handleDragRemove = (event) => {
  console.log("➖ 拖拽移除:", event);
  // 这个事件在跨容器拖拽时会触发
};

const canDeleteComputed = computed(() => {
  // 如果是子图层，检查父图层是否可以删除
  if (props.isChild) {
    const parentLayer = props.layers.find((layer) => layer.id === props.parentLayerId);
    return parentLayer?.children?.length > 1;
  }
  // 否则直接返回根图层的可删除状态
  return props.layers.length > 3;
});
</script>

<template>
  <div class="layers-list">
    <!-- 可排序的根级图层 -->
    <VueDraggable
      :model-value="sortableRootLayers"
      @end="handleRootLayersSort"
      @add="handleDragAdd"
      @remove="handleDragRemove"
      @start="handleDragStart"
      class="sortable-layers"
      :data-container-type="isChild ? 'child' : 'root'"
      :data-parent-id="isChild ? parentLayerId : null"
      :animation="250"
      :disabled="false"
      handle=".layer-drag-handle"
      ghost-class="ghost"
      chosen-class="chosen"
      drag-class="drag"
      :group="{
        name: groupName,
        pull: true,
        put: true,
      }"
      :swap-threshold="0.5"
      :empty-insert-threshold="5"
      :force-fallback="false"
      :fallback-tolerance="3"
      :scroll-sensitivity="100"
      :scroll-speed="10"
    >
      <!-- 遍历可排序的根级图层 -->
      <template v-for="(layer, index) in sortableRootLayers" :key="layer.id">
        <div class="layer-group" :data-layer-id="layer.id">
          <!-- 使用 LayerItem 子组件 -->
          <!-- :thumbnail-url="getLayerThumbnail(layer.id)" -->

          <LayerItem
            :layer="layer"
            :is-child="isChild"
            :is-active="layer.id === activeLayerId"
            :is-selected="isLayerSelected(layer.id)"
            :is-multi-select-mode="isMultiSelectMode && !layer.specialType"
            :is-editing="editingLayerId === layer.id"
            :editing-name="editingLayerName"
            :can-delete="
              canDeleteComputed && !layer.isBackground && !layer.isFixed && !layer.locked
            "
            :expanded-group-ids="expandedGroupIds"
            @click="(...args) => forwardEvent('layer-click', ...args)"
            @double-click="(...args) => forwardEvent('layer-double-click', ...args)"
            @context-menu="(...args) => !layer.specialType && forwardEvent('context-menu', ...args)"
            @checkbox-change="(...args) => forwardEvent('checkbox-change', ...args)"
            @toggle-visibility="(...args) => forwardEvent('toggle-visibility', ...args)"
            @toggle-lock="(...args) => forwardEvent('toggle-lock', ...args)"
            @delete="(...args) => forwardEvent('delete', ...args)"
            @edit-confirm="(...args) => forwardEvent('edit-confirm', ...args)"
            @edit-cancel="(...args) => forwardEvent('edit-cancel', ...args)"
            @edit-keydown="(...args) => forwardEvent('edit-keydown', ...args)"
            @touch-start="(...args) => forwardEvent('touch-start', ...args)"
            @touch-move="(...args) => forwardEvent('touch-move', ...args)"
            @touch-end="(...args) => forwardEvent('touch-end', ...args)"
            @update:editing-name="(...args) => forwardEvent('update:editing-name', ...args)"
            @toggle-group-expanded="(...args) => forwardEvent('toggle-group-expanded', ...args)"
            @toggle-child-visibility="(...args) => forwardEvent('toggle-child-visibility', ...args)"
            @toggle-child-lock="(...args) => forwardEvent('toggle-child-lock', ...args)"
            @delete-child="(...args) => forwardEvent('delete-child', ...args)"
            @rename-child="(...args) => forwardEvent('rename-child', ...args)"
          />

          <!-- 子图层列表 (递归渲染) -->
          <div
            v-if="
              layer?.children?.length > 0 &&
              !layer.isBackground &&
              !layer.isFixed &&
              expandedGroupIds?.has(layer.id)
            "
            class="child-layers"
          >
            <LayersList
              :layers="layers"
              :sortableRootLayers="layer.children"
              :active-layer-id="activeLayerId"
              :selected-layer-ids="selectedLayerIds"
              :is-multi-select-mode="isMultiSelectMode"
              :editing-layer-id="editingLayerId"
              :editing-layer-name="editingLayerName"
              :thumbnail-manager="thumbnailManager"
              :expanded-group-ids="expandedGroupIds"
              :isChild="true"
              :parentLayerId="layer.id"
              :group-name="layer.specialType || groupName"
              @layer-click="(...args) => forwardEvent('layer-click', ...args)"
              @layer-double-click="(...args) => forwardEvent('layer-double-click', ...args)"
              @context-menu="(...args) => forwardEvent('context-menu', ...args)"
              @checkbox-change="(...args) => forwardEvent('checkbox-change', ...args)"
              @toggle-visibility="(...args) => forwardEvent('toggle-visibility', ...args)"
              @toggle-lock="(...args) => forwardEvent('toggle-lock', ...args)"
              @delete="(...args) => forwardEvent('delete', ...args)"
              @edit-confirm="(...args) => forwardEvent('edit-confirm', ...args)"
              @edit-cancel="(...args) => forwardEvent('edit-cancel', ...args)"
              @edit-keydown="(...args) => forwardEvent('edit-keydown', ...args)"
              @touch-start="(...args) => forwardEvent('touch-start', ...args)"
              @touch-move="(...args) => forwardEvent('touch-move', ...args)"
              @touch-end="(...args) => forwardEvent('touch-end', ...args)"
              @update:editing-name="(...args) => forwardEvent('update:editing-name', ...args)"
              @root-layers-sort="(...args) => forwardEvent('root-layers-sort', ...args)"
              @child-layers-sort="(...args) => forwardEvent('child-layers-sort', ...args)"
              @cross-level-move="(...args) => forwardEvent('cross-level-move', ...args)"
              @select-child-layer="(...args) => forwardEvent('select-child-layer', ...args)"
              @start-child-layer-edit="(...args) => forwardEvent('start-child-layer-edit', ...args)"
              @child-context-menu="(...args) => forwardEvent('child-context-menu', ...args)"
              @toggle-child-visibility="
                (...args) => forwardEvent('toggle-child-visibility', ...args)
              "
              @toggle-child-lock="(...args) => forwardEvent('toggle-child-lock', ...args)"
              @finish-child-layer-edit="
                (...args) => forwardEvent('finish-child-layer-edit', ...args)
              "
              @cancel-child-layer-edit="
                (...args) => forwardEvent('cancel-child-layer-edit', ...args)
              "
              @child-layer-edit-keydown="
                (...args) => forwardEvent('child-layer-edit-keydown', ...args)
              "
              @toggle-group-expanded="(...args) => forwardEvent('toggle-group-expanded', ...args)"
              @delete-child="(...args) => forwardEvent('delete-child', ...args)"
              @rename-child="(...args) => forwardEvent('rename-child', ...args)"
            />
          </div>
        </div>
      </template>
    </VueDraggable>
  </div>
</template>

<style scoped lang="less">
// 从父组件的样式文件中继承相关样式
.layers-list {
  .sortable-layers {
    min-height: 20px;
  }

  .child-layers {
    position: relative;
    padding-left: 20px;
    &::after {
      content: "";
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      width: 20px;
      background-color: #e0e0e0;
      z-index: 9;
    }

    .layer-item {
      margin-left: 8px;
    }
  }

  .fixed-layers {
    border-top: 1px solid #e0e0e0;
  }

  // 拖拽模式样式
  .drag-mode {
    .layer-item {
      transition: all 0.2s ease;

      &:not(.chosen):not(.ghost) {
        opacity: 0.7;
        transform: scale(0.98);
      }
    }
  }

  // 拖拽状态样式
  .ghost {
    opacity: 0.4;
    background: linear-gradient(90deg, #e6f7ff 0%, #bae7ff 100%);
    border: 2px dashed #1890ff;
    transform: rotate(2deg);
    box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
    transition: all 0.3s ease;
  }

  .chosen {
    opacity: 0.8;
    transform: scale(1);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    z-index: 999;
    background: linear-gradient(90deg, #fff2e8 0%, #ffd8bf 100%);
    border: 1px solid #fa8c16;
    // border-left: none;
    // border-right: none;
  }

  .drag {
    opacity: 0.6;
    transform: rotate(-1deg);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
    z-index: 1000;
  }

  // 跨层级拖拽目标区域高亮
  .sortable-layers {
    position: relative;
    transition:
      background-color 0.2s ease,
      border-color 0.2s ease;
    border-radius: 4px;
    min-height: 40px; // 确保空组也有足够的拖拽区域

    &.drop-target {
      background-color: rgba(82, 196, 26, 0.1);
      border: 2px dashed #52c41a;

      &::before {
        content: "拖拽到此处";
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #52c41a;
        font-size: 12px;
        font-weight: 500;
        background: rgba(255, 255, 255, 0.9);
        padding: 4px 8px;
        border-radius: 4px;
        z-index: 10;
        pointer-events: none;
      }
    }

    &.drop-invalid {
      background-color: rgba(255, 77, 79, 0.1);
      border: 2px dashed #ff4d4f;

      &::before {
        content: "无法拖拽到此处";
        color: #ff4d4f;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .layers-list {
    .child-layers {
      padding-left: 25px;
      &::after {
        width: 25px;
      }

      .layer-item {
        margin-left: 8px;
      }
    }
  }
}
</style>
