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

<script setup name="SelectSubject" lang="ts">
import { ref, useAttrs, watch } from "vue";
import { getSubjectList } from "@/ap/system";

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

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

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

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

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