<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.basicCourseId"
      :value="item.basicCourseId"
      :label="`${item.courseName}（${item.courseCode}）`"
    >
      <span>{{ `${item.courseName}（${item.courseCode}）` }}</span>
    </el-option>
  </el-select>
</template>

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

export default {
  name: "org-course-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择" },
    value: { type: [Number, String], default: "" },
    clearable: { type: Boolean, default: true },
    filterParam: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      optionList: [],
      selected: "",
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
    filterParam(val, oldval) {
      if (JSON.stringify(val) !== JSON.stringify(oldval)) {
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      }
    },
  },
  methods: {
    async search() {
      this.optionList = [];
      if (!this.filterParam.examId || !this.filterParam.belongOrgId) return;

      const res = await courseQueryByOrg(this.filterParam);
      this.optionList = res || [];
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find((item) => item.basicCourseId === this.selected)
      );
    },
  },
};
</script>
