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

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

export default {
  name: "SourceDetailSelect",
  props: {
    value: {
      type: Object,
      default() {
        return {
          questionType: "",
          sourceDetailId: "",
        };
      },
    },
    courseId: {
      type: [String, Number],
      default: "",
    },
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择题型" },
    clearable: { type: Boolean, default: true },
  },
  data() {
    return {
      selected: null,
      optionList: [],
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = {
          questionType: val.questionType,
          id: val.sourceDetailId,
        };
      },
    },
    courseId(val, oldval) {
      if (val === oldval) return;
      this.search();
    },
  },
  mounted() {
    this.search();
  },
  methods: {
    async search() {
      if (!this.courseId) {
        this.optionList = [];
        this.selected = null;
        this.select();
        return;
      }

      const res = await sourceDetailPageListApi({
        pageNumber: 1,
        pageSize: 100,
        courseId: this.courseId,
        rootOrgId: this.$store.state.user.rootOrgId,
      });
      this.optionList = res.data.content || [];
    },
    select() {
      let selectVal = null;
      if (this.selected) {
        selectVal = Object.assign({}, this.value, {
          questionType: this.selected.questionType,
          sourceDetailId: this.selected.id,
          sourceDetailName: this.selected.name,
        });
      } else {
        selectVal = Object.assign({}, this.value, {
          questionType: "",
          sourceDetailId: "",
          sourceDetailName: "",
        });
      }

      this.$emit("input", selectVal);
      this.$emit("change", this.selected);
    },
  },
};
</script>
