<template>
  <a-select
    placeholder="请选择科目"
    allowClear
    showSearch
    :value="valueStr"
    style="width: 200px"
    :filterOption="false"
    @search="handleSearch"
    @change="handleChange"
  >
    <a-select-option
      v-for="(item, index) in optionList"
      :key="index"
      :value="item.id"
    >
      {{ item.name }}({{ item.code }})
    </a-select-option>
  </a-select>
</template>

<script setup lang="ts">
import { getCourseList } from "@/api/courseManagementPage";
import { onMounted, computed, watch } from "vue";

const props =
  defineProps<{ value?: null | number; rootOrgId?: null | number }>();
const emit = defineEmits(["update:value"]);

let optionList = $ref<{ id: number; name: string; code: string }[]>([]);

watch(
  () => props.rootOrgId,
  () => fetchData()
);
onMounted(fetchData);
async function fetchData(searchStr = "") {
  if (typeof props.rootOrgId === "number") {
    const res = await getCourseList({
      rootOrgId: props.rootOrgId,
      enable: true,
      name: searchStr,
      pageNo: 1,
      pageSize: 100,
    });
    optionList = res.data.content;
  }
}
async function handleSearch(searchStr: string) {
  await fetchData(searchStr);
}
let valueStr = computed(() => {
  let res: undefined | number | string = props.value ?? undefined;
  // if (typeof res === "number") res = props.value + "";
  return res as undefined | string;
});

function handleChange(v: string) {
  emit("update:value", v);
}
</script>
