<template>
  <el-select
    v-model="selected"
    class="print-plan-select"
    :placeholder="placeholder"
    filterable
    :multiple="multiple"
    :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 { printPlanQuery } from "../../modules/print/api";

export default {
  name: "print-plan-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择" },
    value: { type: [Number, String, Array], default: "" },
    clearable: { type: Boolean, default: true },
    multiple: { type: Boolean, default: false }
  },
  data() {
    return {
      optionList: [],
      selected: ""
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      }
    }
  },
  async created() {
    this.search();
  },
  methods: {
    async search(query) {
      const res = await printPlanQuery(query);
      this.optionList = res;
    },
    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>
