<template>
  <el-select
    v-model="selectedValues"
    multiple
    collapse-tags
    collapse-tags-tooltip
    :placeholder="placeholder"
    @remove-tag="handleRemoveTag"
    @clear="handleClear"
  >
    <el-option :value="optionValue" style="height: auto; padding: 0">
      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="treeProps"
        :node-key="nodeKey"
        :default-expand-all="defaultExpandAll"
        :expand-on-click-node="false"
        :check-strictly="checkStrictly"
        show-checkbox
        @check="handleTreeCheck"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span v-if="showIcon && data.icon" :class="data.icon" style="margin-right: 6px"></span>
            <span>{{ node.label }}</span>
          </span>
        </template>
      </el-tree>
    </el-option>
  </el-select>
</template>

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

const props = defineProps({
  // 树形数据
  treeData: {
    type: Array,
    default: () => []
  },
  // 树形配置
  treeProps: {
    type: Object,
    default: () => ({
      children: 'children',
      label: 'label',
      disabled: 'disabled'
    })
  },
  // 节点唯一标识字段
  nodeKey: {
    type: String,
    default: 'id'
  },
  // 是否默认展开所有节点
  defaultExpandAll: {
    type: Boolean,
    default: false
  },
  // 是否严格遵守父子不互相关联
  checkStrictly: {
    type: Boolean,
    default: false
  },
  // 是否显示图标
  showIcon: {
    type: Boolean,
    default: false
  },
  // 选中的值
  modelValue: {
    type: Array,
    default: () => []
  },
  // 占位符
  placeholder: {
    type: String,
    default: '请选择'
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const treeRef = ref(null)
const selectedValues = ref([])
const optionValue = ref([]) // 虚拟option值，用于el-select

// 初始化选中值
onMounted(() => {
  selectedValues.value = [...props.modelValue]
  if (treeRef.value) {
    treeRef.value.setCheckedKeys(selectedValues.value)
  }
})

// 监听外部modelValue变化
watch(
  () => props.modelValue,
  newVal => {
    if (JSON.stringify(newVal) !== JSON.stringify(selectedValues.value)) {
      selectedValues.value = [...newVal]
      if (treeRef.value) {
        treeRef.value.setCheckedKeys(selectedValues.value)
      }
    }
  }
)

// 处理树节点选中事件
const handleTreeCheck = (node, treeCheckedStatus) => {
  const checkedKeys = treeCheckedStatus.checkedKeys
  selectedValues.value = checkedKeys
  emit('update:modelValue', checkedKeys)
  emit('change', checkedKeys)
}

// 处理移除标签事件
const handleRemoveTag = tag => {
  if (treeRef.value) {
    treeRef.value.setChecked(tag, false)
  }
}

// 处理清空事件
const handleClear = () => {
  if (treeRef.value) {
    treeRef.value.setCheckedKeys([])
  }
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
}

:deep(.el-select .el-select__tags) {
  flex-wrap: nowrap;
  overflow: hidden;
}

:deep(.el-tree) {
  padding: 8px 12px;
  max-height: 300px;
  overflow-y: auto;
}

:deep(.el-tree-node__content) {
  height: 34px;
}
</style>
