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

  defineOptions({
    name: 'SelectPaperNumber',
  });
  type ValueType = string | Array<string>;

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

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

    optionList.value = (resData || []).map((item) => {
      return { value: item, label: item };
    });
  };
  search();

  const onChange = () => {
    const selectedData = props.multiple
      ? optionList.value.filter(
          (item) =>
            selected.value && (selected.value as string[]).includes(item.value)
        )
      : optionList.value.filter((item) => selected.value === item.value);
    emit('update:modelValue', selected.value || null);
    emit('change', props.multiple ? selectedData : selectedData[0]);
  };

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