<template>
  <a-select
    v-model="selected"
    :placeholder="placeholder"
    :allow-clear="clearable"
    :disabled="disabled"
    :options="optionList"
    allow-search
    popup-container="body"
    v-bind="attrs"
    @change="onChange"
  >
    <template v-if="prefix" #prefix>考试</template>
  </a-select>
</template>

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

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

  const props = defineProps<{
    modelValue: string;
    clearable?: boolean;
    disabled?: boolean;
    placeholder?: string;
    prefix?: boolean;
    selectDefault?: boolean;
    semesterId: string;
  }>();
  const emit = defineEmits(['update:modelValue', 'change', 'defaultSelected']);
  const attrs = useAttrs();

  const selected = ref<string | undefined>();
  const optionList = ref<OptionListItem[]>([]);
  const search = async () => {
    optionList.value = [];
    if (!props.semesterId) return;
    const resData = await examQuery(props.semesterId);

    optionList.value = (resData || []).map((item) => {
      return { ...item, value: item.id, label: item.name };
    });
    if (props.selectDefault) emitDefaultOption();
  };

  function emitDefaultOption() {
    const defaultData = optionList.value[0];
    if (!defaultData) return;

    selected.value = defaultData.value;
    emit('update:modelValue', selected.value || '');
    emit('change', defaultData);
    emit('defaultSelected', defaultData);
  }

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

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

  watch(
    () => props.semesterId,
    (val, oldval) => {
      if (val !== oldval) {
        emit('update:modelValue', '');
        emit('change', null);
        search();
      }
    },
    {
      immediate: true,
    }
  );
</script>
