<template>
  <el-select
    v-model="selected"
    :clearable="clearable"
    :disabled="disabled"
    :placeholder="placeholder"
    @change="select"
  >
    <el-option
      v-for="item in optionList"
      :key="item"
      :label="item"
      :value="item"
    ></el-option>
  </el-select>
</template>

<script>
import { questionDetailNameQueryApi } from "../../modules/question/api";

export default {
  name: "DetailNameSelect",
  props: {
    value: {
      type: String,
      default: "",
    },
    filterData: {
      type: Object,
      default() {
        return {
          courseId: "",
          questionType: "",
        };
      },
    },
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择来源大题" },
    clearable: { type: Boolean, default: true },
  },
  data() {
    return {
      selected: "",
      optionList: [],
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
    filterData: {
      deep: true,
      immediate: true,
      handler(val, oldval) {
        if (JSON.stringify(val) === JSON.stringify(oldval)) return;
        this.search();
      },
    },
  },
  methods: {
    async search() {
      if (!this.filterData.courseId || !this.filterData.questionType) {
        this.optionList = [];
        this.selected = "";
        this.select();
        return;
      }

      this.loading = true;
      const res = await questionDetailNameQueryApi(this.filterData);
      this.optionList = res.data || [];
      this.loading = false;
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit("change", this.selected);
    },
  },
};
</script>
