<template>
  <el-select
    v-model="selected"
    remote
    filterable
    :remote-method="search"
    :loading="loading"
    :clearable="clearable"
    :disabled="disabled"
    :placeholder="placeholder"
    @clear="clear"
    @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 { propertyNameQueryApi } from "@/modules/question/api";

export default {
  name: "PropertyNameSelect",
  props: {
    value: {
      type: [String, Number],
      default: "",
    },
    options: { type: Array, default: () => [] },
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择属性名" },
    clearable: { type: Boolean, default: true },
    courseId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      optionList: this.options,
      selected: "",
      loading: false,
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
    courseId(val, oldval) {
      if (val !== oldval) {
        this.search();
        this.selected = "";
        this.select();
      }
    },
  },
  created() {
    this.search("");
  },
  methods: {
    async search(query) {
      if (!this.courseId) {
        this.optionList = [];
        return;
      }
      this.loading = true;
      const res = await propertyNameQueryApi(this.courseId, 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>
