<template>
  <el-select
    v-model="selected"
    :remote-method="search"
    :loading="loading"
    remote
    filterable
    :clearable="clearable"
    :disabled="disabled"
    :placeholder="placeholder"
    @clear="clear"
    @change="select"
  >
    <el-option
      v-for="item in optionList"
      :key="item.id"
      :label="item.name + ' - ' + item.code"
      :value="item.id"
    ></el-option>
  </el-select>
</template>

<script>
import { courseQueryApi } from "@/modules/question/api";

export default {
  name: "CourseSelect",
  props: {
    value: {
      type: [String, Number],
      default: "",
    },
    options: { type: Array, default: () => [] },
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择课程" },
    clearable: { type: Boolean, default: true },
  },
  data() {
    return {
      optionList: this.options,
      selected: "",
      loading: false,
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
  },
  created() {
    this.search("");
  },
  methods: {
    async search(query) {
      this.loading = true;
      const res = await courseQueryApi(query);
      this.optionList = res.data || [];
      this.loading = false;
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find((item) => item.id === this.selected)
      );
    },
    clear() {
      this.search("");
      this.selected = "";
      this.select();
    },
  },
};
</script>
