<template>
  <el-tree-select
    v-model="innerValue"
    :data="normalizedOptions"
    :props="treeProps"
    :placeholder="placeholder"
    node-key="value"
    check-strictly
    clearable
    filterable
    default-expand-all
    :render-after-expand="false"
    :disabled="disabled"
  />
</template>

<script setup lang="ts">
interface LegacyTreeNode {
  [key: string]: any;
}

const props = withDefaults(
  defineProps<{
    modelValue?: string | number | null;
    options?: LegacyTreeNode[];
    normalizer?: (node: LegacyTreeNode) => LegacyTreeNode;
    placeholder?: string;
    disabled?: boolean;
  }>(),
  {
    options: () => [],
    normalizer: undefined,
    placeholder: '请选择',
    disabled: false
  }
);

const emit = defineEmits<{
  (event: 'update:modelValue', value: string | number | null | undefined): void;
}>();

const normalizeNodes = (nodes: LegacyTreeNode[]): LegacyTreeNode[] =>
  nodes.map((node) => {
    // 兼容旧版 treeselect 的 normalizer 约定，避免 EMS 页面为迁移额外重写树数据结构。
    const normalizedNode = props.normalizer ? props.normalizer({ ...node }) : { ...node };
    const children = Array.isArray(normalizedNode.children) ? normalizeNodes(normalizedNode.children) : undefined;

    return {
      ...normalizedNode,
      children
    };
  });

const normalizedOptions = computed(() => normalizeNodes(props.options ?? []));

const treeProps = {
  label: 'label',
  children: 'children'
};

const innerValue = computed({
  get: () => props.modelValue ?? undefined,
  set: (value) => {
    emit('update:modelValue', value);
  }
});
</script>
