<template>
  <div class="workstation-tree">
    <div class="head-container">
      <el-input
        v-model="searchValue"
        placeholder="请在下方选择岗位名称"
        clearable
        class="mb-20px"
        @input="handleInputChange"
        @clear="handleClear"
      >
        <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="treeDataRef"
        node-key="id"
        default-expand-all
        @node-click="handleNodeClick"
        highlight-current
      />
    </div>
  </div>
</template>

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

defineOptions({ name: 'WorkstationTree' })

// 定义事件
const emit = defineEmits(['node-click'])

// 数据定义
const treeDataRef = ref() // 树形组件引用
const workstationOptions = ref([]) // 岗位树选项
const searchValue = ref('') // 搜索值

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: -1,
  workstationName: undefined,
  workstationId: undefined
})

/** 获取岗位树数据 */
const getWorkstationTree = async () => {
  try {
    const data = { pageNo: 1, pageSize: -1 }
    const response = await MarsDeptApi.listMarsDept(data)
    workstationOptions.value = handleTree(response.list, 'id', 'parentId')
  } catch (error) {
    console.error('获取岗位树数据失败:', error)
  }
}

/** 树节点点击事件 */
const handleNodeClick = (data: any) => {
  searchValue.value = data.workstationName // 将选中的节点名称赋值给搜索框
  emit('node-click', data)
}

/** 搜索框输入事件 */
const handleInputChange = (val: string) => {
  treeDataRef.value?.filter(val)
}

/** 搜索框清空事件 */
const handleClear = () => {
  searchValue.value = ''
  emit('node-click', null)
}

/** 树节点过滤方法 */
const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.workstationName.indexOf(value) !== -1
}

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

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

  .head-container {
    margin-bottom: 10px;
  }

  .mb-20px {
    margin-bottom: 20px;
  }
}
</style>
