<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}）`"
    >
    </el-option>
  </el-select>
</template>

<script>
import { commonCourseQuery } from "../../modules/client/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 },
    filterData: {
      type: Object,
      default: null,
    },
    defaultSelect: { type: Boolean, default: false },
  },
  data() {
    return {
      optionList: [],
      selected: "",
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
    filterData(val, oldval) {
      if (val && oldval) {
        const vse = `${val.semesterId}-${val.examId}`;
        const oldvse = `${oldval.semesterId}-${oldval.examId}`;
        if (vse !== oldvse) {
          this.search();
          this.$emit("input", "");
          this.$emit("change", {});
        }
        return;
      }

      if (val !== oldval) {
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      }
    },
  },
  async created() {
    this.search();
  },
  methods: {
    async search() {
      this.optionList = [];

      if (
        this.filterData &&
        (!this.filterData.semesterId || !this.filterData.examId)
      )
        return;

      const datas = this.filterData || {};

      const res = await commonCourseQuery(datas);
      this.optionList = res;
      if (this.defaultSelect && !this.value) this.selectDefault();
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find((item) => item.code === this.selected)
      );
    },
    selectDefault() {
      const defaultData = this.optionList[0];
      if (defaultData) {
        this.selected = defaultData.code;
        this.select();
        this.$emit("default-selected", defaultData);
      }
    },
  },
};
</script>
