<template>
  <div class="doc-tree-container">
    <a-input-group compact>
      <a-select v-model:value="srhValueTp" style="width: 25%">
        <a-select-option value="1">标签</a-select-option>
        <a-select-option value="2">文件夹</a-select-option>
      </a-select>
      <a-input-search
        v-model:value="srhValue"
        placeholder="请输入"
        style="width: 60%"
        enter-button
        allow-clear
        @search="onSearch"
      />
    </a-input-group>
    
    <div class="card-container" style="margin-top: 10px">
      <a-tabs v-model:activeKey="activeKey" type="card" @change="tabChange">
        <a-tab-pane v-for="(data, index) in treeData" :key="index" :tab="setTitle(data)">
          <a-directory-tree
            draggable
            @drop="onDrop"
            ref="treeRef"
            class="tree-content"
            v-model:expandedKeys="expandedKeys"
            :selectedKeys="selectedKeys"
            :tree-data="data.children || []"
            @select="onTreeSelect"
          >
            <template #title="{ key: treeKey, title, otherData, isFind }">
              <a-dropdown :trigger="['contextmenu']">
                <span :class="{'search-highlight': isFind}">
                  {{ title }}{{ otherData?.cnt ? `[${otherData.cnt}]` : '' }}
                </span>
                <template #overlay>
                  <a-menu @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey)">
                    <a-menu-item key="edit">修改</a-menu-item>
                    <a-menu-item key="add">添加下级</a-menu-item>
                    <a-menu-item key="delete">删除</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </template>
          </a-directory-tree>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
  
  <TreeModal :rootTreeData="treeData" @register="registerTreeModal" @success="handleSuccess" />
</template>

<script lang="ts" setup>
  import { ref, onMounted, watch, nextTick } from 'vue';
  import { useModal } from '/@/components/Modal';
  import { Modal } from 'ant-design-vue';
  import TreeModal from './TreeModal.vue';
  import { loadTreeData, deleteOne, changeTreeNodeOrder } from '../DocFilesDir.api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import type { TreeActionType } from 'ant-design-vue/es/tree';

  // 常量定义
  const ROOT_NODE_ID = 1;
  
  // Refs
  const activeKey = ref<number>(0);
  const srhValue = ref<string>('');
  const srhValueTp = ref<string>('2');
  const treeRef = ref<Nullable<TreeActionType>>(null);
  const expandedKeys = ref<string[]>([]);
  const selectedKeys = ref<string[]>([]);
  const currentNode = ref<any>(null);
  const treeData = ref<any[]>([]);
  const rootPid = ref<string | number>();

  // Hooks
  const { createMessage } = useMessage();
  const [registerTreeModal, { openModal: openTreeModal }] = useModal();
  
  // Emits
  const emit = defineEmits(['select', 'rootTreeData', 'selectTreeNode']);

  // 初始化树数据
  onMounted(() => {
    iniTreeData();
  });

  // 监听搜索值变化，为空时重置高亮
  watch(srhValue, (newVal) => {
    if (!newVal) {
      resetSearchHighlight(treeData.value);
    }
  });

  // 重置搜索高亮
  function resetSearchHighlight(nodes: any[]) {
    nodes.forEach(node => {
      delete node.isFind;
      if (node.children) {
        resetSearchHighlight(node.children);
      }
    });
  }

  // 新增子节点
  function onAddChildNode(data = currentNode.value) {
    if (!data) {
      createMessage.warning('请先选择一个节点');
      return;
    }
    
    const record = { pid: data.key };
    openTreeModal(true, { isUpdate: false, record });
  }

  // 修改节点
  function onUpdateTreeNode(data = currentNode.value) {
    if (!data) {
      createMessage.warning('请先选择一个节点');
      return;
    }
    
    const record = { 
      id: data.key, 
      name: data.title, 
      pid: data.parentId, 
      labelNames: data.otherData?.label 
    };
    openTreeModal(true, { isUpdate: true, record });
  }

  // 删除节点
  async function onDeleteNode(data = currentNode.value) {
    if (!data) {
      createMessage.warning('请先选择一个节点');
      return;
    }
    
    if (data.key == ROOT_NODE_ID) {
      createMessage.warning('根节点不能删除');
      return;
    }

    if (data.children?.length > 0) {
      createMessage.warning('该节点有子节点不能删除');
      return;
    }

    Modal.confirm({
      title: '确认删除',
      content: '是否删除选中文件夹',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteOne({ id: data.key });
          await iniTreeData();
        } catch (error) {
          console.error('删除节点失败:', error);
          createMessage.error('删除失败');
        }
      },
    });
  }

  // 设置当前选中的行
  function setSelectedKey(key: string, data?: any) {
    selectedKeys.value = selectedKeys.value[0] === key ? [] : [key];
    currentNode.value = data;
  }

  // 树选择事件
  function onTreeSelect(selKeys: string[], event: any) {
    if (selectedKeys.value[0] !== selKeys[0]) {
      setSelectedKey(selKeys[0], event.selectedNodes[0]);
      emit('selectTreeNode', event.selectedNodes[0]);
    } else {
      // 点击已选中的节点时取消选择
      setSelectedKey('');
      emit('selectTreeNode', null);
    }
  }

  // 自动展开父节点
  function autoExpandParentNode(index: number) {
    const item = treeData.value[index];
    if (!item) {
      emit('select', null);
      return;
    }
    
    const expandKeys = new Set<string>();
    
    if (item.children?.length > 0) {
      expandKeys.add(item.key);
      
      // 只展开直接子节点，避免过度展开
      for (const child of item.children) {
        if (child.children?.length > 0) {
          expandKeys.add(child.key);
        }
      }
    }
    
    expandedKeys.value = Array.from(expandKeys);
    setSelectedKey(item.key, item);
    emit('selectTreeNode', item);
  }

  // 处理成功操作
  function handleSuccess(node: any, isUpdate: boolean) {
    if (isUpdate) {
      // 更新现有节点
      if (currentNode.value) {
        currentNode.value.title = node.name;
        currentNode.value.otherData = currentNode.value.otherData || {};
        currentNode.value.otherData.label = node.labelNames;
      }
    } else {
      // 添加新节点
      const newNode = { 
        key: node.id, 
        title: node.name, 
        parentId: node.pid,
        otherData: { cnt: 0, label: node.labelNames } 
      };
      
      if (rootPid.value == newNode.parentId) {
        treeData.value.push(newNode);
      } else if (currentNode.value) {
        if (!currentNode.value.children) {
          currentNode.value.children = [];
        }
        currentNode.value.children.push(newNode);
        
        // 确保父节点展开
        if (!expandedKeys.value.includes(currentNode.value.key)) {
          expandedKeys.value = [...expandedKeys.value, currentNode.value.key];
        }
      }
    }
    
    // 重新加载数据以确保一致性
    iniTreeData();
  }

  // 右键菜单点击处理
  function onContextMenuClick(treeKey: string, menuKey: string) {
    // 确保选中当前节点
    const node = findNodeInTreeData(treeData.value, treeKey);
    if (node) {
      setSelectedKey(treeKey, node);
    }
    
    switch (menuKey) {
      case 'delete':
        onDeleteNode();
        break;
      case 'add':
        onAddChildNode();
        break;
      case 'edit':
        onUpdateTreeNode();
        break;
    }
  }

  // 节点拖拽处理
  function onDrop(info: any) {
    const { node, dragNode, dropPosition, dropToGap } = info;
    const dropKey = node.eventKey;
    const dragKey = dragNode.eventKey;
    
    // 克隆数据以避免直接修改
    const data = JSON.parse(JSON.stringify(treeData.value));
    let dragObj: any = null;
    
    // 查找并移除拖拽节点
    const removeNode = (nodes: any[], key: string): boolean => {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].key === key) {
          dragObj = nodes[i];
          nodes.splice(i, 1);
          return true;
        }
        if (nodes[i].children && removeNode(nodes[i].children, key)) {
          return true;
        }
      }
      return false;
    };
    
    removeNode(data, dragKey);
    
    if (!dragObj) return;
    
    // 插入到目标位置
    const insertNode = (nodes: any[], key: string, obj: any, position: number, isGap: boolean): boolean => {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].key === key) {
          if (!isGap) {
            // 放入节点内
            nodes[i].children = nodes[i].children || [];
            nodes[i].children.push(obj);
          } else {
            // 放入间隙
            const insertIndex = position === -1 ? i : i + 1;
            nodes.splice(insertIndex, 0, obj);
          }
          return true;
        }
        if (nodes[i].children && insertNode(nodes[i].children, key, obj, position, isGap)) {
          return true;
        }
      }
      return false;
    };
    
    if (!dropToGap) {
      // 放入节点
      insertNode(data, dropKey, dragObj, 0, false);
    } else {
      // 放入间隙
      insertNode(data, dropKey, dragObj, dropPosition, true);
    }
    
    treeData.value = data;
    
    // 更新后端
    const isFolder = node.children?.length > 0;
    changeTreeNodeOrder({ tid: dropKey, cid: dragKey, isfolder: isFolder });
  }

  // 处理文件夹节点
  function handleFolderNode(item: any) {
    const node = findNodeInTreeData(treeData.value, item.key);
    if (node) {
      emit('selectTreeNode', node);
      setSelectedKey(node.key, node);
    }
  }

  // 递归查找节点
  function findNodeInTreeData(treeDataTmp: any[], targetKey: string): any | null {
    for (const node of treeDataTmp) {
      if (node.key == targetKey) {
        return node;
      }
      if (node.children) {
        const foundNode = findNodeInTreeData(node.children, targetKey);
        if (foundNode) {
          return foundNode;
        }
      }
    }
    return null;
  }

  // 搜索处理
  async function onSearch() {
    const val = srhValue.value.trim();
    if (!val) {
      resetSearchHighlight(treeData.value);
      return;
    }
    
    const findNodes: any[] = [];
    await searchTree(treeData.value, findNodes, val, srhValueTp.value);
    
    if (findNodes.length > 0) {
      // 高亮匹配的节点
      findNodes.forEach(node => {
        node.isFind = true;
      });
      
      // 展开所有包含匹配节点的路径
      const expandKeys = new Set<string>();
      findNodes.forEach(node => {
        let current = node;
        while (current && current.parentId) {
          expandKeys.add(current.parentId);
          current = findNodeInTreeData(treeData.value, current.parentId);
        }
      });
      
      expandedKeys.value = Array.from(expandKeys);
      
      // 选中第一个匹配的节点
      setSelectedKey(findNodes[0].key, findNodes[0]);
      emit('selectTreeNode', findNodes[0]);
    } else {
      createMessage.info('未找到匹配的节点');
    }
  }

  // 搜索树
  async function searchTree(nodes: any[], results: any[], value: string, type: string) {
    for (const node of nodes) {
      const compareText = type === '1' ? node.otherData?.label : node.title;
      
      if (compareText && (compareText === value || compareText.includes(value))) {
        results.push(node);
      }
      
      if (node.children) {
        await searchTree(node.children, results, value, type);
      }
    }
  }

  // 设置标题
  function setTitle(data: any) {
    const cnt = data.otherData?.cnt;
    return data.title + (cnt ? `[${cnt}]` : '');
  }

  // 初始化树数据
  async function iniTreeData() {
    try {
      treeData.value = await loadTreeData({});
      if (treeData.value.length > 0) {
        rootPid.value = treeData.value[0].key;
        autoExpandParentNode(0);
      }
    } catch (error) {
      console.error('加载树数据失败:', error);
      createMessage.error('加载数据失败');
    }
  }

  // 标签切换
  function tabChange(index: number) {
    activeKey.value = index;
    autoExpandParentNode(index);
  }

  // 暴露方法
  defineExpose({
    handleFolderNode,
    setTitle,
    iniTreeData
  });
</script>

<style scoped>
  .doc-tree-container {
    background: #fff;
    padding: 10px;
  }
  
  .tree-content {
    padding: 10px 0px;
  }
  
  .search-highlight {
    color: #ff4d4f;
    font-weight: bold;
  }
  
  .editInput {
    width: 80px;
    margin: 0 10px;
  }
  
  .icon-wrap {
    color: #808080;
    margin: 0 10px;
  }
</style>