<template>
  <a-select
    v-model:value="selected"
    :placeholder="placeholder"
    :options="optionList"
    filter-option
    :multiple="false"
    :field-names="fieldNames"
    style="width: 200px"
    v-bind="attrs"
    @change="onChange"
  >
  </a-select>
</template>

<script setup lang="ts">
import { ref, useAttrs, watch } from "vue";
import { getSubjectList } from "@/ap/base";
import { SubjectItem } from "@/ap/types/base";

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

const props = withDefaults(
  defineProps<{
    examId: number;
    value: string;
    placeholder?: string;
  }>(),
  {
    placeholder: "请选择",
  }
);
const emit = defineEmits(["update:value", "change"]);
const attrs = useAttrs();

const fieldNames = { label: "name", value: "code" };

const selected = ref("");
const optionList = ref<SubjectItem[]>([]);
const search = async () => {
  optionList.value = [];
  const resData = await getSubjectList({ examId: props.examId });
  optionList.value = resData || [];
};
search();

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

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