<template>
  <div class="head-container" style="display: flex; flex-direction: row">
    <el-input
      size="default"
      v-model="deptName"
      class="mb-18px"
      clearable
      placeholder="请输入部门名称"
    >
      <template #prefix>
        <Icon icon="ep:search" />
      </template>
    </el-input>
  </div>
  <div ref="treeContainer" class="tree-container">
    <el-tree
      ref="treeRef"
      :data="deptList"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :props="defaultProps"
      :default-expanded-keys="firstLevelKeys"
      highlight-current
      node-key="id"
      @node-click="handleNodeClick"
      @node-contextmenu="handleRightClick"
      style="height: 52em"
    />
  </div>
  <div v-show="menuVisible" class="custom-menu" :style="{ left: menuX + 'px', top: menuY + 'px' }">
    <ul>
      <li @click="handleMenuClick('add')">新增子节点</li>
      <li @click="handleMenuClick('edit')">重命名</li>
      <li @click="handleMenuClick('delete')">删除</li>
    </ul>
  </div>
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
import * as DeptApi from '@/api/system/dept'
import { defaultProps, handleTree } from '@/utils/tree'
import { useTreeStore } from '@/store/modules/usersTreeStore'
defineOptions({ name: 'DeptTree2' })

const deptName = ref('')
const deptList = ref<Tree[]>([]) // 树形结构
const treeRef = ref<InstanceType<typeof ElTree>>()
const menuVisible = ref(false)
const menuX = ref(0)
const menuY = ref(0)
const firstLevelKeys = ref([])
let selectedNode = null
const treeStore = useTreeStore()

// props 定义，接收 deptId 参数
interface Props {
  deptId?: number
}

const props = withDefaults(defineProps<Props>(), {
  deptId: 157 // 可以设置默认值，但建议父组件必须传递
})

const handleRightClick = (event, { node, data }) => {
  event.preventDefault()
  menuX.value = event.clientX
  menuY.value = event.clientY
  selectedNode = data // 存储当前操作的节点数据 ‌:ml-citation{ref="7" data="citationList"}
  //menuVisible.value = true;
}
const treeContainer = ref(null)
const setHeight = () => {
  if (!treeContainer.value) return
  const windowHeight = window.innerHeight
  const containerTop = treeContainer.value.offsetTop
  treeContainer.value.style.height = `${windowHeight * 0.78}px` // 60px 底部预留
}
const handleMenuClick = (action) => {
  switch (action) {
    case 'add':
      // 调用新增节点逻辑 ‌:ml-citation{ref="4" data="citationList"}
      break
    case 'edit':
      // 调用编辑节点逻辑 ‌:ml-citation{ref="7" data="citationList"}
      break
    case 'delete':
      // 调用删除节点逻辑 ‌:ml-citation{ref="4" data="citationList"}
      break
  }
  menuVisible.value = false
}
/** 获得部门树 */
const getTree = async () => {
  const res = await DeptApi.specifiedSimpleDepts(props.deptId)
  deptList.value = []
  const treeData = handleTree(res)

  // 对树进行排序
  const sortedTree = sortTreeBySort(treeData)

  deptList.value.push(...sortedTree)
  firstLevelKeys.value = deptList.value.map((node) => node.id)
}

/** 递归对树节点按sort排序 */
const sortTreeBySort = (treeNodes: Tree[]) => {
  if (!treeNodes || !Array.isArray(treeNodes)) return treeNodes

  // 对当前层级节点按sort升序排序
  const sortedNodes = [...treeNodes].sort((a, b) => {
    const sortA = a.sort != null ? a.sort : 999999
    const sortB = b.sort != null ? b.sort : 999999
    return sortA - sortB
  })

  // 递归处理子节点
  sortedNodes.forEach(node => {
    if (node.children && Array.isArray(node.children)) {
      node.children = sortTreeBySort(node.children)
    }
  })

  return sortedNodes
}

// 添加获取顶级部门的方法
const getTopDeptId = async (): Promise<number> => {
  try {
    // 如果已经加载了部门树，直接获取第一级节点的第一个节点
    if (deptList.value && deptList.value.length > 0) {
      // 假设第一级节点就是顶级节点
      return deptList.value[0].id
    }

    // 如果没有加载部门树，则根据传入的deptId重新获取
    const res = await DeptApi.specifiedSimpleDepts(props.deptId)
    const treeData = handleTree(res)

    // 对树进行排序
    const sortedTree = sortTreeBySort(treeData)

    if (sortedTree && sortedTree.length > 0) {
      return sortedTree[0].id
    }

    // 如果没有找到顶级部门，返回默认值
    return 158
  } catch (error) {
    console.error('获取顶级部门ID失败:', error)
    return 158 // 默认值
  }
}

// 修改3: 将方法暴露给父组件
defineExpose({
  getTopDeptId,
})

/** 基于名字过滤 */
const filterNode = (name: string, data: Tree) => {
  if (!name) return true
  return data.name.includes(name)
}

/** 处理部门被点击 */
const handleNodeClick = async (row: { [key: string]: any }) => {
  emits('node-click', row)
  treeStore.setSelectedId(row.id)
}
const emits = defineEmits(['node-click'])

/** 监听deptName */
watch(deptName, (val) => {
  treeRef.value!.filter(val)
})

// 监听 deptId 变化，当父组件改变 deptId 时重新加载树
watch(
  () => props.deptId,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      getTree()
    }
  },
  { immediate: true } // 添加立即执行，确保组件初始化时加载树
)

/** 初始化 */
onMounted(async () => {
  await getTree()
  setHeight()
  window.addEventListener('resize', setHeight)
})
onUnmounted(() => {
  window.removeEventListener('resize', setHeight)
})
</script>
<style lang="scss" scoped>
.custom-menu {
  position: fixed;
  z-index: 1000;
  background: white;
  border: 1px solid #ccc;
  box-shadow: 2px 2px 5px rgb(0 0 0 / 10%);
}

.custom-menu ul {
  padding: 0;
  margin: 0;
  list-style: none;
}

.custom-menu li {
  padding: 8px 20px;
  cursor: pointer;
}

.custom-menu li:hover {
  background: #f5f5f5;
}

.tree-container {
  min-width: 100%;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}
</style>
