<!-- 树形下拉选择框，只适合单选 -->
<template>
  <el-select
    ref="select"
    v-model="pid"
    placeholder="请选择"
    clearable
    style="width: 100%"
    :disabled="disabled"
    popper-class="selectDrop"
  >
    <el-option ref="option" class="option" :value="optionData.id" :label="optionData.name">
      <el-tree
        ref="tree"
        class="tree"
        :node-key="nodeKey"
        :data="data"
        :props="treeProps"
        :default-expanded-keys="id ? [id] : []"
        highlight-current
        :expand-on-click-node="false"
      />
    </el-option>
  </el-select>
</template>

<script setup>
import { nextTick, watch, ref } from 'vue'

const props = defineProps({
  // v-model绑定
  id: {
    type: [String, Number],
    default: ''
  },
  // 树形的数据
  data: {
    type: Array,
    default: function () {
      return []
    }
  },
  // 每个树节点用来作为唯一标识的属性
  nodeKey: {
    type: [String, Number],
    default: 'id'
  },
  // tree的props配置
  treeProps: {
    type: Object,
    default: function () {
      return {
        label: 'label',
        children: 'children'
      }
    }
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

watch(
  () => props.id,
  (val) => {
    if (props.data.length > 0 && isNotEmpty(val)) {
      init(val)
    } else {
      pid.value = ''
    }
  }
)
// 判断该值是否为空，不包括0
const isNotEmpty = (val) => {
  if (val === 0 || val === '0' || val) return true
  return false
}

const tree = ref()
// 模拟下拉数据
const optionData = ref({
  id: '',
  name: ''
})
// 上级分类id
const pid = ref(null)
// 初始化下拉内容
const init = (val) => {
  nextTick(() => {
    tree.value.setCurrentKey(val)
    const node = tree.value.getNode(val)
    optionData.value.id = val
    optionData.value.name = node.label
    pid.value = props.id
  })
}
</script>

<style lang="less" scoped>
.option {
  height: auto;
  line-height: 1;
  padding: 0;
  background-color: #fff;
}
</style>
