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

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

export default {
  name: "semester-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 }
  },
  data() {
    return {
      optionList: [],
      selected: ""
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      }
    }
  },
  created() {
    this.search();
  },
  methods: {
    async search() {
      const schoolId = this.$ls.get("schoolId");
      const res = await semesterQuery(schoolId);
      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.id === this.selected)
      );
    }
  }
};
</script>
