<!-- 上级配置选择下拉框 -->
<template>
  <el-tree-select
    clearable
    filterable
    :data="configData"
    check-strictly
    default-expand-all
    node-key="id"
    :props="{ label: 'title', disabled: 'disabled' }"
    :placeholder="placeholder"
    :model-value="modelValue || void 0"
    class="ele-fluid"
    :popper-options="{ strategy: 'fixed' }"
    @update:modelValue="updateValue"
  >
    <template #default="{ data }">
      <span>{{ data.title }}</span>
    </template>
  </el-tree-select>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { EleMessage, toTree } from 'ele-admin-plus';
  import { listConfigs } from '@/api/system/config';
  import type { Config } from '@/api/system/config/model';

  const props = withDefaults(
    defineProps<{
      /** 选中的配置 */
      modelValue?: number | string;
      /** 提示信息 */
      placeholder?: string;
      /** 配置所属组 */
      group?: string | null;
    }>(),
    {
      placeholder: '请选择上级配置'
    }
  );

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

  /** 配置数据 */
  const configData = ref<Config[]>([]);

  /** 更新选中数据 */
  const updateValue = (value: number | string) => {
    emit('update:modelValue', value || 0);
  };

  /** 获取配置数据 */
  listConfigs({ group: props.group, limit: 999 })
    .then((list) => {
      const data: any = list.map((d: Config) => {
        d.disabled = ['tabs', 'tabs_item'].indexOf(d.type) === -1;
        return d;
      });

      configData.value = toTree({
        data: data.filter(d => !d.disabled),
        idField: 'id',
        parentIdField: 'pid'
      });
    })
    .catch((e) => {
      EleMessage.error({ message: e.message, plain: true });
    });
</script>
