<template>
  <el-select
    v-model="selected"
    class="type-org-select"
    :placeholder="placeholder"
    :style="styles"
    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 { organizationFindByTypeList } from "../../modules/base/api";
import { ORG_TYPE } from "@/constants/enumerate";

export default {
  name: "type-org-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择" },
    value: { type: [Number, String], default: "" },
    styles: { type: String, default: "" },
    clearable: { type: Boolean, default: true },
    type: {
      type: String,
      default: "COLLEG",
      validator(val) {
        return Object.keys(ORG_TYPE).indexOf(val) > -1;
      }
    }
  },
  data() {
    return {
      optionList: [],
      selected: ""
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      }
    }
  },
  created() {
    this.search();
  },
  methods: {
    async search() {
      const res = await organizationFindByTypeList({ orgType: this.type });
      this.optionList = res;
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find(item => item.id === this.selected)
      );
    }
  }
};
</script>
