<template>
  <el-select
    v-model="selected"
    class="teach-college-select"
    :placeholder="placeholder"
    :style="styles"
    filterable
    :clearable="clearable"
    :disabled="disabled"
    @change="select"
  >
    <el-option
      v-for="item in optionList"
      :key="item.teachCollegeId"
      :value="item.teachCollegeId"
      :label="item.teachCollegeName"
    >
    </el-option>
  </el-select>
</template>

<script>
import { teachCollegeQuery } from "../modules/college/api";

export default {
  name: "teach-college-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 },
    examId: { type: String, default: "" },
    courseCode: { 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", {});
      }
    },
    courseCode(val, oldval) {
      if (val !== oldval) {
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      }
    }
  },
  methods: {
    async search() {
      if (!this.examId || !this.courseCode) {
        this.optionList = [];
        return;
      }
      const schoolId = this.$ls.get("schoolId");
      const res = await teachCollegeQuery({
        schoolId,
        examId: this.examId,
        courseCode: this.courseCode
      });
      this.optionList = res;
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find(item => item.teachCollegeId === this.selected)
      );
    }
  }
};
</script>
