<template>
  <el-select
    v-model="selected"
    class="course-select"
    :placeholder="placeholder"
    filterable
    :clearable="clearable"
    :disabled="disabled"
    @change="select"
  >
    <el-option
      v-for="(item, index) in optionList"
      :key="index"
      :value="item.id"
      :label="`${item.name}（${item.code}）`"
    >
      <span>{{ `${item.name}（${item.code}）` }}</span>
    </el-option>
  </el-select>
</template>

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

export default {
  name: "course-common-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择" },
    value: { type: [Number, String], default: "" },
    clearable: { type: Boolean, default: true },
  },
  data() {
    return {
      optionList: [],
      selected: "",
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
  },
  async created() {
    this.search();
  },
  methods: {
    async search() {
      const res = await unitQueryByType({}, "COURSE");
      this.optionList = res;
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find((item) => item.id === this.selected)
      );
    },
  },
};
</script>
