<template>
  <el-select
    v-model="selected"
    class="course-select"
    :placeholder="placeholder"
    filterable
    :clearable="clearable"
    :disabled="disabled"
    @change="select"
  >
    <el-option
      v-for="item in optionList"
      :key="item.code"
      :value="item.code"
      :label="`${item.name}（${item.code}）`"
    >
      <span>{{ `${item.name}（${item.code}）` }}</span>
    </el-option>
  </el-select>
</template>

<script>
import { courseQuery } from "../../modules/base/api";

export default {
  name: "course-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择科目" },
    value: { type: [Number, String], default: "" },
    clearable: { type: Boolean, default: true },
    semesterId: { type: String, default: "" },
    examTypeId: { type: String, default: "" },
    collegeId: { type: String, default: "" },
  },
  data() {
    return {
      optionList: [],
      selected: "",
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
    semesterId(val, oldval) {
      if (val !== oldval) {
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      }
    },
    examTypeId(val, oldval) {
      if (val !== oldval) {
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      }
    },
    collegeId(val, oldval) {
      if (val !== oldval) {
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      }
    },
  },
  async created() {
    this.search();
  },
  methods: {
    async search() {
      if (!this.semesterId || !this.examTypeId) return;

      let data = {
        semesterId: this.semesterId,
        examTypeId: this.examTypeId,
        collegeId: this.collegeId,
      };

      const res = await courseQuery(data);
      this.optionList = res.map((item) => {
        return {
          code: item.courseCode,
          name: item.courseName,
        };
      });
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find((item) => item.code === this.selected)
      );
    },
  },
};
</script>
