<template>
  <el-select
    v-model="selected"
    class="size-select"
    placeholder="请选择"
    @change="select"
    :style="styles"
    filterable
    clearable
  >
    <el-option
      v-for="item in optionList"
      :key="item.courseCode"
      :label="item.courseName"
      :value="item.courseCode"
    >
      <span>{{ item.courseName }}</span>
    </el-option>
  </el-select>
</template>

<script>
import { searchCourses } from "@/api/examwork-course";

export default {
  name: "CourseSelect",
  props: {
    value: String,
    examId: String,
    styles: { type: String },
    examRequired: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      optionList: [],
      selected: "",
    };
  },
  async created() {
    this.search();
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
    examId(val, oldval) {
      if (val !== oldval) {
        this.search("");
        this.$emit("input", "");
        this.$emit("change", {});
      }
    },
  },
  methods: {
    async search(query) {
      this.optionList = [];
      if (this.examRequired && !this.examId) return;

      const res = await searchCourses({
        examId: this.examId,
        courseName: query,
        pageNumber: 1,
        pageSize: 1000,
      });
      this.optionList = res?.data.data.records;
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit("change", this.selected);
    },
  },
};
</script>

<style></style>
