<template>
  <el-select
    v-model="selected"
    class="clazz-select"
    popper-class="popper-filter"
    :placeholder="placeholder"
    :style="styles"
    :clearable="clearable"
    :disabled="disabled"
    :multiple="multiple"
    @change="select"
  >
    <div class="el-select-filter">
      <el-input
        v-model="filterLabel"
        placeholder="请输入"
        clearable
        @input="labelChange"
      ></el-input>
    </div>
    <el-option
      v-for="item in filterOptionList"
      :key="item.id"
      :value="item.id"
      :label="item.name"
    >
    </el-option>
  </el-select>
</template>

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

export default {
  name: "clazz-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择" },
    value: { type: [Number, String, Array], default: "" },
    styles: { type: String, default: "" },
    clearable: { type: Boolean, default: true },
    multiple: { type: Boolean, default: false },
    campusId: { type: String, default: "" },
    datas: {
      type: Array
    }
  },
  data() {
    return {
      optionList: [],
      filterOptionList: [],
      selected: "",
      filterLabel: ""
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      }
    },
    datas: {
      immediate: true,
      handler(val) {
        if (!val) return;
        this.optionList = val.map(item => {
          return { ...item };
        });
        this.labelChange();
      }
    },
    campusId(val, oldval) {
      if (val !== oldval) {
        this.search();
        this.$emit("input", "");
        this.$emit("change", null);
      }
    }
  },
  created() {
    if (!this.datas) this.search();
  },
  methods: {
    async search() {
      const res = await clazzQuery({
        campusId: this.campusId
      });
      this.optionList = res || [];
      this.labelChange();
    },
    labelChange() {
      const escapeRegexpString = (value = "") =>
        String(value).replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
      const reg = new RegExp(escapeRegexpString(this.filterLabel), "i");

      this.filterOptionList = this.optionList.filter(item =>
        reg.test(item.name)
      );
    },
    select() {
      this.$emit("input", this.selected);

      if (this.multiple) {
        this.$emit(
          "change",
          this.optionList.filter(item => this.selected.includes(item.id))
        );
      } else {
        this.$emit(
          "change",
          this.optionList.find(item => item.id === this.selected)
        );
      }
    }
  }
};
</script>
