<template>
  <el-select
    v-model="selected"
    class="exam-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"
    >
    </el-option>
  </el-select>
</template>

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

export default {
  name: "teacher-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择任课老师" },
    value: { type: [Number, String], default: "" },
    clearable: { type: Boolean, default: true },
    filterData: {
      type: Object,
      default() {
        return {
          semesterId: "",
          examTypeId: "",
          courseCode: "",
          openCollege: "",
          kcCollege: "",
        };
      },
    },
  },
  data() {
    return {
      optionList: [],
      selected: "",
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
    filterData: {
      deep: true,
      handler(val, oldval) {
        if (JSON.stringify(val) === JSON.stringify(oldval)) return;
        console.log(val);
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      },
    },
  },
  created() {
    this.search();
  },
  methods: {
    async search() {
      this.optionList = [];
      if (Object.values(this.filterData).some((item) => !item)) return;

      const res = await examTeacherQuery(this.filterData);
      this.optionList = res;
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find((item) => item.code === this.selected)
      );
    },
  },
};
</script>
