<template>
  <a-select
    placeholder="请选择科目"
    allowClear
    showSearch
    :value="valueStr"
    style="width: 200px"
    :disabled="props.disabled"
    :filterOption="filterAction"
    @change="handleChange"
  >
    <a-select-option
      v-for="item in optionList"
      :key="`${item.courseName}${item.courseCode}`"
      :value="item.courseId"
    >
      {{ item.courseName }}({{ item.courseCode }})
    </a-select-option>
  </a-select>
</template>

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

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

interface CoureOption {
  courseId: number;
  courseName: string;
  courseCode: string;
}

let optionList = $ref<CoureOption[]>([]);

onMounted(fetchData);
async function fetchData(searchStr = "") {
  const res = await getProjectCourseList({
    projectId: props.projectId,
    courseName: searchStr,
    pageNo: 1,
    pageSize: 200,
  });
  optionList = res.data.content;
}
// async function handleSearch(searchStr: string) {
//   await fetchData(searchStr);
// }
function filterAction(inputValue: string, option: { key: string }): boolean {
  const escapeRegexpString = (value = "") =>
    String(value).replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
  const reg = new RegExp(escapeRegexpString(inputValue), "i");
  return reg.test(option.key);
}

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>
