<template>
  <el-select
    v-model="selected"
    :placeholder="props.placeholder"
    :clearable="props.clearable"
    :disabled="props.disabled"
    filterable
    default-first-option
    v-bind="attrs"
    @change="onChange"
  >
    <el-option
      v-for="item in optionList"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</template>

<script setup lang="ts">
  import { ref, useAttrs, watch } from 'vue';
  import { examQuery } from '@/api/base';

  defineOptions({
    name: 'SelectExam',
  });

  type ValueType = number | Array<number> | null;

  const props = withDefaults(
    defineProps<{
      modelValue: ValueType;
      clearable?: boolean;
      disabled?: boolean;
      placeholder?: string;
      defaultFirst?: boolean;
    }>(),
    {
      clearable: true,
      disabled: false,
      placeholder: '请选择考试',
      defaultFirst: false,
    }
  );
  const emit = defineEmits(['update:modelValue', 'change', 'defaultSelected']);
  const attrs = useAttrs();

  interface OptionListItem {
    value: number;
    label: string;
  }

  const selected = ref<number | Array<number> | undefined>();
  const optionList = ref<OptionListItem[]>([]);
  const search = async () => {
    const res = await examQuery();
    optionList.value = res.map((item) => {
      return { ...item, value: item.id, label: `${item.id}-${item.name}` };
    });

    if (props.defaultFirst && optionList.value[0]) {
      selected.value = optionList.value[0].value;
      emit('update:modelValue', selected.value || undefined);
      emit('change', optionList.value[0]);
      emit('defaultSelected', optionList.value[0]);
    }
  };
  search(); // Initial load

  const onChange = () => {
    const selectedData = optionList.value.filter(
      (item) => selected.value === item.value
    );
    emit('update:modelValue', selected.value || undefined);
    emit('change', selectedData[0]);
  };

  watch(
    () => props.modelValue,
    (val) => {
      selected.value = val || undefined;
    },
    {
      immediate: true,
    }
  );
</script>
