<script lang="ts" setup>
import { getCategoryList } from '../api'
import type { ElTree } from 'element-plus'

defineProps({
  isTreeVisible: {
    type: Boolean,
    required: true
  }
})
const emit = defineEmits<{
  (e: 'update:isTreeVisible', isTreeVisible: false): void
  (e: 'getCheckedLabel', checkedCategory: any): void
}>()

const handleCancel = () => {
  emit('update:isTreeVisible', false)
}
interface ICategory {
  category_name: string
  depth: string
  id: string
  lft: string
  need_pass: string
  rgt: string
  status: string
  children?: ICategory[]
}

let data = ref<ICategory[]>([])

const filterText = ref('') // 搜索字段
const treeRef = ref<InstanceType<typeof ElTree>>()

const defaultProps = {
  children: 'children',
  label: 'category_name'
}
const checkedCategory = {
  checkedId: '',
  checkedLabel: '', // 默认选中项名称
  checkedLevel: 0 // 默认选中项层级
}
// 监听搜索
watch(filterText, val => {
  treeRef.value?.filter(val)
})
//搜索
const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.category_name.indexOf(value) != -1
}
// 获取选中节点
const handleNodeClick = (TreeNode: any) => {
  checkedCategory.checkedLabel = TreeNode.category_name // 类名
  checkedCategory.checkedId = TreeNode.id // id
  checkedCategory.checkedLevel = parseInt(TreeNode.depth) //层级
}

// 确认
const handleConfirm = () => {
  checkedCategory.checkedLabel && emit('getCheckedLabel', { checkedCategory })
  emit('update:isTreeVisible', false)
}

// 获取分类列表
const handleCategoryList = () => {
  const params = { type: 'tree' }
  getCategoryList(params).then((res: any) => {
    data.value = res.data
  })
}
onMounted(() => {
  handleCategoryList()
})
</script>
<template>
  <el-dialog :model-value="isTreeVisible" draggable :before-close="handleCancel" title="类别选择" width="20%">
    <el-input v-model="filterText" placeholder="请选择类别" />
    <el-tree
      ref="treeRef"
      class="filter-tree"
      :data="data"
      :props="defaultProps"
      default-expand-all
      :expand-on-click-node="false"
      :highlight-current="true"
      @node-click="handleNodeClick"
      :filter-node-method="filterNode"
    />
    <template #footer>
      <span>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.filter-tree {
  height: 40vh;
  overflow: auto;
}
</style>
