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

<script>
import { classQuery } from "../modules/college/api";

const initFilter = {
  inspectCollegeId: "",
  examId: "",
  courseCode: "",
  teacherId: ""
};

export default {
  name: "class-select",
  props: {
    placeholder: { type: String, default: "选择班级" },
    disabled: { type: Boolean, default: false },
    value: { type: [Number, String], default: "" },
    styles: { type: String, default: "" },
    clearable: { type: Boolean, default: true },
    filter: {
      type: Object,
      default() {
        return {
          ...initFilter
        };
      }
    }
  },
  data() {
    return {
      optionList: [],
      filterData: { ...initFilter },
      selected: ""
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      }
    },
    filter: {
      deep: true,
      handler(val) {
        const vals = this.$objAssign(initFilter, val);
        const changed = Object.keys(initFilter).some(
          key => vals[key] !== this.filterData[key]
        );
        console.log(vals, changed);
        if (!changed) return;

        this.filterData = { ...vals };
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      }
    }
  },
  methods: {
    async search() {
      if (!this.filterData.examId || !this.filterData.courseCode) {
        this.optionList = [];
        return;
      }
      const schoolId = this.$ls.get("schoolId");
      const res = await classQuery({
        schoolId,
        ...this.filterData
      });
      this.optionList = res;
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find(item => item.clazzId === this.selected)
      );
    }
  }
};
</script>
