<template>
  <el-select
    class="level-one"
    v-model="levelModel"
    style="width: 200px"
    @change="selected"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
  >
    <el-option
      v-for="item in dataList"
      :key="item.id"
      :value="item.id"
      :label="item.name"
    >
    </el-option>
  </el-select>
</template>

<script>
import { getData } from "./com-func";

export default {
  name: "level-one",
  props: {
    value: {
      type: [String, Number],
    },
    setDefault: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: "请选择选项",
    },
    clearable: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      dataList: [],
    };
  },
  computed: {
    levelModel: {
      get() {
        return this.value;
      },
      set(selectId) {
        this.$emit("input", selectId);
      },
    },
  },
  created() {
    this.search();
  },
  methods: {
    async search() {
      const data = await getData("level-one");
      this.dataList = data.map((item) => {
        return {
          id: item.id,
          name: item.name,
        };
      });

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