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

<script>
import { courseQuery, courseTeachQuery } from "../modules/college/api";

export default {
  name: "course-select",
  props: {
    placeholder: { type: String, default: "选择课程(代码)" },
    disabled: { type: Boolean, default: false },
    value: { type: [Number, String], default: "" },
    styles: { type: String, default: "" },
    clearable: { type: Boolean, default: true },
    inspect: { type: Boolean, default: false },
    isTeach: { type: Boolean, default: false },
    selectDefault: { type: Boolean, default: false },
    examId: { type: String, default: "" }
  },
  data() {
    return {
      optionList: [],
      selected: ""
    };
  },
  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() {
      if (!this.examId) {
        this.optionList = [];
        return;
      }
      const schoolId = this.$ls.get("schoolId");
      let res = [];
      if (this.isTeach) {
        res = await courseTeachQuery({
          schoolId,
          examId: this.examId
        });
      } else {
        res = await courseQuery({
          schoolId,
          examId: this.examId,
          inspect: this.inspect
        });
      }

      this.optionList = res;

      if (this.selectDefault && this.optionList.length) {
        this.selected = this.optionList[0].courseCode;
        this.select();
      }
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find(item => item.courseCode === this.selected)
      );
    }
  }
};
</script>
