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

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

export default {
  name: "college-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择" },
    value: { type: [Number, String], default: "" },
    clearable: { type: Boolean, default: true },
    semesterId: { type: String, default: "" },
    cascader: { type: Boolean, default: false }
  },
  data() {
    return {
      optionList: [],
      selected: ""
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      }
    },
    semesterId(val, oldval) {
      if (val !== oldval) {
        this.search("");
        this.$emit("input", "");
        this.$emit("change", {});
      }
    }
  },
  created() {
    this.search();
  },
  methods: {
    async search() {
      this.optionList = [];
      if (this.cascader && !this.semesterId) return;

      if (this.cascader) {
        const res = await unitQueryByType(
          {
            semesterId: this.semesterId
          },
          "COLLEGE"
        );
        this.optionList = res;
      } else {
        // const res = await organizationFindByTypeList({ orgType: "COLLEGE" });
        const res = await unitQueryByType({}, "COLLEGE");
        this.optionList = res;
      }
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find(item => item.id === this.selected)
      );
    }
  }
};
</script>
