<template>
  <div>
    <TreeSelect
      v-model:value="selectData"
      v-bind="$attrs"
      style="width: 100%"
      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
      :placeholder="placeholder"
      allow-clear
      show-search
      tree-default-expand-all
      :multiple="multiple"
      :tree-data="treeData"
      :field-names="{ children: 'children', label: 'title', value: 'id' }"
      tree-node-filter-prop="title"
      @change="handleChange"
      :key="key"
    >
      <template #title="{ systemName, parentId, title }">
        {{ title }}&nbsp;&nbsp;<b v-if="!(parentId > 0)">[{{ systemName }}]</b>
      </template>
    </TreeSelect>
  </div>
</template>
<script lang="ts" setup>
  import { TreeSelect } from 'ant-design-vue';
  import { onMounted, ref, watch } from 'vue';
  import { getMenuTree, getMenuSimpleTree } from '/@/api/system/menu';
  const treeData = ref<Recordable[]>([]);
  const selectData = ref<string | undefined>('');

  // const value = ref<string>();

  const props = defineProps({
    value: String,
    placeholder: String,
    allmenu: String, //所有项目可选
    multiple: { type: Boolean, default: () => false }, //允许多选
  });

  const emit = defineEmits(['options-change', 'change', 'update:value']);
  const key = ref(0);
  onMounted(() => {
    fetch();
  });

  watch(
    () => props.value,
    () => {
      fetch();
    },
  );

  async function fetch() {
    if (props.allmenu === 'true') {
      treeData.value = ((await getMenuSimpleTree()) as unknown as Recordable[]) || [];
    } else {
      treeData.value = ((await getMenuTree()) as unknown as Recordable[]) || [];
    }

    treeData.value = treeData.value.filter((data) => {
      return import.meta.env.VITE_GLOB_PRODUCTION === 'true' ? data.systemId !== '1' : data;
    });
    selectData.value = props.value;
    emit('options-change', treeData.value);
  }

  //多选
  // function handleChange(...args) {
  //   emit('change', ...args);
  // }

  //单选
  function handleChange(val, node) {
    selectData.value = val;
    emit('change', val, node);
    key.value++;
  }
</script>
