<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 { courseQuery } from '@/api/task';
  import { OptionListItem } from '@/types/global';

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

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

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

    optionList.value = (resData || []).map((item) => {
      return { ...item, value: item.id, label: `${item.name}(${item.code})` };
    });
  };

  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.examId,
    (val, oldval) => {
      if (val !== oldval) {
        emit('update:modelValue', '');
        emit('change', null);
        search();
      }
    },
    {
      immediate: true,
    }
  );
</script>
