<template>
  <div v-loading="loading" style="height: 100%">
    <div class="head-container">
      <el-input v-model="deptName" class="mb-20px" clearable placeholder="请输入部门名称">
        <template #prefix>
          <Icon icon="ep:search" />
        </template>
      </el-input>
    </div>
    <div class="head-container tree-container">
      <el-tree
        class="custom_tree"
        ref="treeRef"
        :data="deptList"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        :props="defaultProps"
        default-expand-all
        highlight-current
        node-key="id"
        @node-click="handleNodeClick"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
import * as DeptApi from '@/api/system/dept'
import { defaultProps, handleTree } from '@/utils/tree'

defineOptions({ name: 'SystemUserDeptTree' })

const deptName = ref('')
const deptList = ref<Tree[]>([]) // 树形结构
const treeRef = ref<InstanceType<typeof ElTree>>()
const loading = ref(true)
/** 获得部门树 */
const getTree = async () => {
  const res = await DeptApi.getSimpleDeptList()
  deptList.value = []
  deptList.value.push(...handleTree(res))
  loading.value = false
}

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

/** 处理部门被点击 */
let currentNode: any = {}
const handleNodeClick = async (row: { [key: string]: any }, treeNode: any) => {
  // 判断选中状态
  if (currentNode && currentNode.name === row.name) {
    treeNode.checked = !treeNode.checked
  } else {
    treeNode.checked = true
  }
  if (treeNode.checked) {
    // 选中
    currentNode = row
    emits('node-click', row)
  } else {
    // 取消选中
    treeRef.value!.setCurrentKey(undefined)
    emits('node-click', undefined)
    currentNode = null
  }
}
const emits = defineEmits(['node-click'])

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

/** 初始化 */
onMounted(async () => {
  await getTree()
})
</script>
<style scoped lang="less">
.custom_tree {
  ::v-deep .el-tree-node__label {
    max-width: 150px; /* 可根据需求调整宽度 */
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.tree-container {
  height: calc(100% - 55px);
  overflow: auto;
}
.tree-container::-webkit-scrollbar {
  width: 0; /* 垂直滚动条宽度 */
  height: 0; /* 水平滚动条高度 */
  background: transparent; /* 透明背景（可选） */
}
</style>
