<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 },
    printPlanId: { type: [String, Array], default: "" },
    teachingRoomId: { type: [String, Array], default: "" }
  },
  data() {
    return {
      optionList: [],
      selected: ""
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      }
    },
    printPlanId(val, oldval) {
      if (val !== oldval) {
        this.search("");
        this.$emit("input", "");
        this.$emit("change", {});
      }
    },
    teachingRoomId(val, oldval) {
      if (val !== oldval) {
        this.search("");
        this.$emit("input", "");
        this.$emit("change", {});
      }
    }
  },
  async created() {
    this.search();
  },
  methods: {
    async search(query) {
      const res = await courseQuery({
        param: query,
        printPlanId: this.printPlanId,
        teachingRoomId: this.teachingRoomId
      });
      this.optionList = res;
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find(item => item.code === this.selected)
      );
    }
  }
};
</script>
