<template>
  <app-dialog
    v-model="visible"
    :loading="loading"
    :title="title"
    append-to-body
    class="detail-dialog"
    hide-footer
    width="25%"
    @cancel="onCancel"
    @confirm="onMoveConfirm"
  >

    <!--  :actions="treeActions"   :context-menu="false"  关键修改：禁用右键菜单 -->
    <div class="tree-container">
      <el-input
        v-model="filterText"
        class="tree-filter-input"
        clearable
        placeholder="输入关键字进行过滤"
        prefix-icon="el-icon-search"
        @clear="handleFilterClear"
        @input="handleFilterInput"
      />
      <app-sync-tree
        ref="appAsyncTree"
        :actions="treeActions"
        :default-checked-keys="defaultCheckedKeys"
        :default-data="{ customConfigField: 'custom config field' }"
        :default-expanded-keys="filterText ? [] : defaultExpandedKeys"
        :expand-all="expandAll"
        :props="treeProps"
        :request-method="getTreeNodes"
        highlight-first
        title="共享资源目录"
        @select="onTreeNodeClick"
      />
    </div>
    <div ref="dialogFooter" slot="footer" class="gz-dialog-footer text-l">
      <el-button :disabled="!curNode.id" :loading="loading" class="confirm_btn" type="primary"
                 @click="onMoveConfirm"
      >确 定
      </el-button>
      <el-button class="cancel_btn" @click="onCancel">取 消</el-button>
    </div>
  </app-dialog>
</template>

<script>
import dialogMixin from '@/mixins/dialog.js'
import API from '@/api/business/shareDataCatalog'

export default {
  name: 'ManualDialog',
  mixins: [dialogMixin],
  props: {
    // 接收父组件传递的selectedRows数据
    selectedRows: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const TREE_CONFIG = {
      treeProps: {
        value: 'id',
        label: 'name',
        children: 'children'
      },
      expandAll: false,
      defaultExpandedKeys: ['1'],
      defaultCheckedKeys: ['1'],
      curNode: {}, // 当前选择节点
      selectedTableData: [], // 存储要移动的表格数据
      //过滤功能
      filterText: '', // 过滤文本
      filterTimeout: null, // 防抖定时器
      originalTreeData: [], // 保存原始树数据
      isFiltering: false, // 是否正在过滤
      hasFilterResults: true // 新增标志位，表示是否有过滤结果
    }
    return {
      ...TREE_CONFIG,
      parentDetail: {},
      loading: false
    }
  },
  created() {

  },
  mounted() {
    this.$nextTick(() => {
      if (this.$refs.appAsyncTree && this.$refs.appAsyncTree.$el) {
        const treeEl = this.$refs.appAsyncTree.$el
        treeEl.addEventListener('contextmenu', e => {
          e.preventDefault()
          return false
        })
      }
    })
  },
  watch: {
    filterText(val) {
      // 使用防抖优化性能
      clearTimeout(this.filterTimeout)
      this.filterTimeout = setTimeout(() => {
        this.applyFilter(val)
      }, 300)
    },
    // 监听 visible 变化，当弹层显示时清空过滤条件
    visible(val) {
      if (val) {
        this.resetFilter()
      }
    }
  },
  methods: {
    // 新增重置过滤条件的方法
    resetFilter() {
      this.filterText = ''
      this.expandAll = false
      this.hasFilterResults = true
      this.curNode = {}

      // 如果有原始数据，直接使用原始数据
      if (this.originalTreeData.length) {
        this.$refs.appAsyncTree?.handleTreeData(this.originalTreeData)
      }
    },
    treeActions(data) {
      //右键无内容操作
    },
    /**
     * @description: dialog每次显示时触发的init方法
     * @param {*} data 传入data
     * @return {*}
     */
    async getTreeNodes() {
      try {
        const {value} = await API.getShareTree()
        this.originalTreeData = value || []
        this.defaultExpandedKeys = [value?.[0].id || '']

        // 如果有过滤条件，应用过滤
        if (this.filterText) {
          const filteredData = this.filterTreeData(this.originalTreeData, this.filterText)
          this.hasFilterResults = filteredData.length > 0 // 更新是否有结果的标志
          return {data: filteredData}
        }

        this.hasFilterResults = true // 重置标志
        return {data: this.originalTreeData}
      } catch (error) {
        console.error('获取树数据失败:', error)
        return {data: []}
      }
    },
    /**
     * 应用过滤条件
     */
    applyFilter(filterValue) {
      if (!this.originalTreeData.length) return

      this.isFiltering = true

      if (!filterValue) {
        // 清空过滤时，直接使用原始数据
        this.$refs.appAsyncTree.handleTreeData(this.originalTreeData)
        this.expandAll = false
        this.isFiltering = false
        this.hasFilterResults = true

        // 重置展开状态
        this.$nextTick(() => {
          if (this.$refs.appAsyncTree && this.$refs.appAsyncTree.setCurrentKey) {
            this.$refs.appAsyncTree.setCurrentKey(this.defaultExpandedKeys[0])
          }
        })
        return
      }

      // 获取过滤后的数据
      const filteredData = this.filterTreeData(this.originalTreeData, filterValue)
      this.hasFilterResults = filteredData.length > 0

      if (!this.hasFilterResults) {
        this.$message.warning('没有找到匹配的节点')
        this.handleFilterClear()
      } else {
        this.$refs.appAsyncTree.handleTreeData(filteredData)
        this.expandAll = true
      }

      this.isFiltering = false
    },


    /**
     * 递归过滤树数据
     */
    filterTreeData(nodes, filterValue) {
      const lowerFilter = filterValue.toLowerCase()

      return nodes.reduce((result, node) => {
        const newNode = {...node}
        const label = newNode[this.treeProps.label] || ''
        const isMatch = label.toLowerCase().includes(lowerFilter)

        // 过滤子节点
        if (newNode.children && newNode.children.length) {
          newNode.children = this.filterTreeData(newNode.children, filterValue)
        }

        // 如果当前节点匹配，或者有匹配的子节点，则保留该节点
        if (isMatch || (newNode.children && newNode.children.length > 0)) {
          // 如果当前节点匹配，但子节点不匹配，则清空子节点
          if (isMatch && newNode.children && newNode.children.length === 0) {
            delete newNode.children
          }
          result.push(newNode)
        }

        return result
      }, [])
    },
    /**
     * 处理过滤输入
     */
    handleFilterInput() {
      // 可以在这里添加输入时的额外逻辑
    },

    /**
     * 清除过滤条件
     */
    handleFilterClear() {
      this.filterText = ''
      this.expandAll = false
      this.hasFilterResults = true

      // 直接使用缓存的原始数据，避免重新请求
      this.$refs.appAsyncTree.handleTreeData(this.originalTreeData)

      // 重置到默认展开状态
      this.$nextTick(() => {
        if (this.$refs.appAsyncTree && this.$refs.appAsyncTree.setCurrentKey) {
          this.$refs.appAsyncTree.setCurrentKey(this.defaultExpandedKeys[0])
        }
      })
    },
    initData(data) {
      // 组件创建时打印接收到的selectedRows数据
      this.selectedTableData = [...this.selectedRows]
    },

    onTreeNodeClick(node) {
      if (node.id === this.curNode?.id) return
      // 打印当前点击的树节点
      console.log('当前点击的树节点:', node)
      // 打印要移动的表格数据
      console.log('要移动的表格数据:', this.selectedTableData) //数组包含对象
      this.curNode = {...node}
    },
    onCancel() {
      this.isTableNameEnValidated = true
      this.visible = false
      this.resetFilter() // 关闭时清空过滤条件
    },
    onMoveConfirm() {
      this.loading = true
      // 检查是否已选择树节点
      if (!this.curNode.id) {
        this.$message.warning('请先选择目标目录')
        this.loading = false
        return
      }

      // 检查是否有选中的数据
      if (this.selectedTableData.length === 0) {
        this.$message.warning('请选择要移动的数据')
        this.loading = false
        return
      }
      // 提取ids数组
      const ids = this.selectedTableData.map(item => item.id)
      // 准备formData参数
      const formData = new URLSearchParams()
      formData.append('catalogId', this.curNode.id)
      // 准备查询参数
      const queryParams = ids.map(id => `ids=${id}`).join('&')
      // 调用API
      API.MoveData(queryParams, formData)
        .then(() => {
          this.$message.success('数据移动成功')
          this.$emit('move-success') // 通知父组件刷新数据
          this.visible = false // 关闭对话框
        })
        .catch(error => {
          console.error('移动数据失败:', error)
          this.$message.error('数据移动失败')
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .gz-dialog .el-form-item__error {
    left: 0;
  }

  .el-form-item {
    margin-bottom: 18px !important;

  }

  .el-input__suffix {
    right: 0;
  }
}

.gz-dialog-footer {
  padding: 11px 11px 0 11px;
  text-align: right;
}

/* 新增树节点样式 */
::v-deep {
  /* 树节点点击/选中状态 */
  .el-tree-node {
    &.is-current, &.is-checked {
      > .el-tree-node__content {
        background-color: #b3d8ff; /* 浅蓝色背景 */
        color: #1890ff; /* 蓝色文字 */
        font-weight: 500;

        &:hover {
          background-color: #d0e8ff; /* 悬停时更深一点的蓝色 */
        }
      }
    }

    /* 普通节点的悬停状态 */
    > .el-tree-node__content:hover {
      background-color: #f5f5f5;
    }
  }

  /* 树节点内容区域 */
  .el-tree-node__content {
    height: 36px; /* 增加行高 */
    line-height: 36px;
    transition: all 0.3s; /* 添加过渡效果 */
    border-radius: 4px; /* 添加圆角 */
    margin: 2px 0; /* 添加间距 */
  }

  /* 树节点展开图标 */
  .el-tree-node__expand-icon {
    color: #666;
    font-size: 16px;

    &.expanded {
      transform: rotate(0deg); /* 保持默认旋转 */
    }
  }
}

.tree-container {
  width: 100%; /* 确保容器宽度与dialog一致 */
  height: 100%; /* 如果需要也可以设置高度 */

  ::v-deep .app-tree {
    width: 100% !important; /* 强制树组件宽度为100% */

    /* 如果需要，可以添加以下样式确保树内容也填满 */
    .el-tree {
      width: 100%;
    }
  }
}
</style>
