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

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

const initFilter = {
  absent: "0",
  current: "1",
  examId: "",
  courseCode: ""
};

export default {
  name: "inspect-college-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 },
    selectDefault: { type: Boolean, default: false },
    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, oldval) {
        const vals = this.$objAssign(initFilter, val);
        const changed = Object.keys(initFilter).some(
          key => vals[key] !== this.filterData[key]
        );

        if (!changed) return;

        this.filterData = { ...vals };
        this.search();
        this.$emit("input", "");
        this.$emit("change", {});
      }
    }
  },
  methods: {
    async initData() {
      const vals = this.$objAssign(initFilter, this.filter);
      this.filterData = { ...vals };
      await this.search();
    },
    async search() {
      if (!this.filterData.examId || !this.filterData.courseCode) {
        this.optionList = [];
        return;
      }
      const schoolId = this.$ls.get("schoolId");
      let datas = {
        schoolId,
        ...this.filterData
      };
      if (datas.current) datas.current = !!(datas.current * 1);
      if (datas.absent) datas.absent = !!(datas.absent * 1);
      const res = await inspectCollegeQuery(datas);
      this.optionList = res;

      if (this.selectDefault && this.optionList.length) {
        this.selected = this.optionList[0].inspectCollegeId;
        this.select();
      }
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find(item => item.inspectCollegeId === this.selected)
      );
    }
  }
};
</script>
