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

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

export default {
  name: "semester-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择学期" },
    value: { type: [Number, String], default: "" },
    clearable: { type: Boolean, default: true },
    manualFetch: {
      type: Boolean,
      default: false,
    },
    selectDefault: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      optionList: [],
      selected: "",
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
  },
  created() {
    if (!this.manualFetch) this.search();
  },
  methods: {
    async search() {
      this.optionList = [];
      const res = await semesterQuery({});
      this.optionList = res;

      if (!this.selectDefault) return;

      if (this.value) {
        const option = this.optionList.find((item) => item.id === this.value);
        if (option) {
          this.$emit("input", this.value);
          this.$emit("change", option);
        } else {
          this.selectFirst();
        }
      } else {
        this.selectFirst();
      }
    },
    selectFirst() {
      if (!this.optionList.length) {
        this.selected = "";
        this.$emit("input", this.selected);
        this.$emit("change", {});
        return;
      }
      this.selected = this.optionList[0].id;
      this.$emit("input", this.selected);
      this.$emit("change", this.optionList[0]);
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find((item) => item.id === this.selected)
      );
    },
  },
};
</script>
