<template>
  <el-select
    v-model="selected"
    class="scan-task-select"
    :placeholder="placeholder"
    remote
    :remote-method="search"
    :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 { commonScanTaskQuery } from "../../modules/base/api";

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

      let data = {};
      if (this.paperArchivesId) data.paperArchivesId = this.paperArchivesId;

      const res = await commonScanTaskQuery(data);
      this.optionList = res;
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find(item => item.id === this.selected)
      );
    }
  }
};
</script>
