<template>
  <Select
    class="subject-select"
    v-model="selectId"
    style="width: 100%;"
    @on-change="selected"
    label-in-value
    :size="size"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
  >
    <Option v-for="item in dataList" :key="item.id" :value="item.id">{{
      item.name
    }}</Option>
  </Select>
</template>

<script>
import { subjectList } from "@/modules/admin/api";

export default {
  name: "subject-select",
  props: {
    value: {
      type: [String, Number]
    },
    size: {
      type: String,
      default: "large",
      validator(value) {
        return ["small", "large", "default"].indexOf(value) !== -1;
      }
    },
    workId: {
      type: [String, Number],
      required: true
    },
    setDefault: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: "请选择考试"
    },
    clearable: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      dataList: []
    };
  },
  watch: {
    workId(val, oldval) {
      if (val !== oldval) this.search();
    }
  },
  computed: {
    selectId: {
      get() {
        return this.value;
      },
      set(selectId) {
        this.$emit("input", selectId || "");
      }
    }
  },
  created() {
    this.search();
  },
  methods: {
    async search() {
      if (!this.workId) {
        this.dataList = [];
        this.selectId = "";
        return;
      }
      const data = await subjectList(this.workId);
      this.dataList = data.map(item => {
        return {
          id: item.id,
          name: item.name
        };
      });

      if (this.setDefault) {
        this.selectId = this.dataList[0] && this.dataList[0].id;
        const val = {
          value: (this.dataList[0] && this.dataList[0].id) || "",
          label: (this.dataList[0] && this.dataList[0].name) || ""
        };
        this.$emit("on-change", val);
        this.$emit("on-set");
      }
    },
    selected(val) {
      this.$emit("on-change", val);
    }
  }
};
</script>
