<template>
  <el-select
    v-model="selected"
    class="status-select"
    :placeholder="placeholder"
    filterable
    :clearable="clearable"
    :disabled="disabled"
    @change="select"
  >
    <el-option
      v-for="item in optionList"
      :key="item.code"
      :value="item.code"
      :label="item.name"
    >
    </el-option>
  </el-select>
</template>

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

export default {
  name: "status-select",
  props: {
    disabled: { type: Boolean, default: false },
    placeholder: { type: String, default: "请选择状态" },
    value: { type: [Number, String], default: "" },
    clearable: { type: Boolean, default: true },
    type: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      optionList: [],
      selected: "",
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.selected = val;
      },
    },
  },
  created() {
    this.search();
  },
  methods: {
    async search() {
      if (!this.type) return;
      const res = await getEnums(this.type);
      this.optionList = res.map((item, index) => {
        return {
          code: item.code,
          name: item.name,
          ordinal: item.ordinal || index,
        };
      });
      this.optionList.sort((a, b) => a.ordinal - b.ordinal);
    },
    select() {
      this.$emit("input", this.selected);
      this.$emit(
        "change",
        this.optionList.find((item) => item.code === this.selected)
      );
    },
  },
};
</script>
