<template>
  <div class="workstation-tree">
    <div class="head-container">
      <el-input
        v-model="searchValue"
        placeholder="请输入区域名称"
        clearable
        style="margin-bottom: 20px"
        @clear="handleClear"
        @input="handleSearch"
      >
        <template #prefix>
          <Icon icon="ep:search" />
        </template>
      </el-input>
    </div>
    <div class="head-container">
      <el-tree
        :data="workstationOptions"
        :props="{ label: 'workstationName', value: 'id', children: 'children' }"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        ref="treeData"
        node-key="id"
        default-expand-all
        @node-click="handleNodeClick"
        highlight-current
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { handleTree } from '@/utils/tree'
import * as MarsDeptApi from '@/api/system/marsdept'

// 定义接口类型
interface TreeNode {
  id: string
  workstationName: string
  children?: TreeNode[]
  [key: string]: any
}

// 定义事件
const emit = defineEmits<{
  nodeClick: [data: TreeNode]
}>()

// 响应式数据
const searchValue = ref<string>('')
const workstationOptions = ref<TreeNode[]>([])
const treeData = ref()

// 获取岗位树数据
const getWorkstationTree = async (): Promise<void> => {
  try {
    const data = {
      pageNo: 1,
      pageSize: -1
    }
    const response = await MarsDeptApi.listMarsDept(data)

    console.log('原始数据:', response.list)

    // 找到所有根节点的数据（parentId 为 0 的节点）
    const rootData = response.list.filter((item: any) => {
      return item.parentId === 0 || item.parentId === '0'
    })

    console.log('根节点数据:', rootData)

    // 构建树形结构
    workstationOptions.value = handleTree(rootData, 'id', 'parentId', 'children')

  } catch (error) {
    console.error('获取岗位树数据失败:', error)
  }
}

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

// 岗位树点击事件
const handleNodeClick = (data: TreeNode): void => {

  // searchValue.value = data.workstationName // 点击节点时赋值 暂不需要
  emit('nodeClick', data)
}

// 清除搜索
const handleClear = (): void => {
  searchValue.value = ''
  emit('nodeClick', { id: '', workstationName: '' })
}

// 搜索处理
const handleSearch = (value: string): void => {
  // 这里不需要额外处理，watch 会自动调用 filter
}

/** 监听searchValue */
watch(searchValue, (val) => {
  if (treeData.value) {
    treeData.value.filter(val)
  }
})

// 初始化
onMounted(async () => {
  await getWorkstationTree()
})
</script>

<style lang="scss" scoped>
.workstation-tree {
  height: 100%;

  .head-container {
    padding: 0 10px;
  }
}
</style>
