<template>
  <el-select
    v-model="selected"
    class="question-teacher-user-select"
    :placeholder="placeholder"
    filterable
    :clearable="clearable"
    :disabled="disabled"
    @change="select"
  >
    <el-option-group
      v-for="group in groups"
      :key="group.label"
      :label="group.label"
    >
      <el-option
        v-for="item in group.options"
        :key="item.id"
        :value="item.id"
        :label="`${item.name}（${item.loginName}）`"
      >
      </el-option>
    </el-option-group>
  </el-select>
</template>

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

export default {
  name: "question-teacher-user-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择" },
    value: { type: [Number, String], default: "" },
    clearable: { type: Boolean, default: true },
    courseId: { type: String, default: "" },
  },
  data() {
    return {
      groups: [],
      selected: "",
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
    courseId(val, oldval) {
      if (val !== oldval) {
        this.search("");
        this.$emit("input", "");
        this.$emit("change", {});
      }
    },
  },
  async created() {
    this.search();
  },
  methods: {
    async search(query) {
      if (!this.courseId) return;
      const res = await questionTeatherUserQuery({
        param: query,
        courseId: this.courseId,
      });
      this.groups = [
        {
          label: "机构",
          options: res.blurryUserDtoList,
        },
        {
          label: "课程",
          options: res.courseUserList.map((item) => {
            return {
              id: item.id,
              name: item.realName,
              loginName: item.loginName,
            };
          }),
        },
      ];
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find((item) => item.id === this.selected)
      );
    },
  },
};
</script>
