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

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

export default {
  name: "exam-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 },
    selectDefault: { type: Boolean, default: false },
    semesterId: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      optionList: [],
      selected: ""
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      }
    },
    semesterId(val, oldval) {
      console.log(val, oldval);
      if (val !== oldval) {
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      }
    }
  },
  methods: {
    async search() {
      if (!this.semesterId) {
        this.optionList = [];
        return;
      }
      const schoolId = this.$ls.get("schoolId");
      const res = await examQuery({
        schoolId,
        semesterId: this.semesterId
      });
      this.optionList = res;

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