<template>
  <el-select
    v-bind="$attrs"
    :value-key="valueKey"
    :value="value"
    @input="selectChange"
    @change="(e) => $emit('change', e)"
  >
    <el-option
      v-for="it in opt"
      :key="'my-select' + it[valueKey]"
      :label="it[labelKey]"
      :value="it[valueKey]"
    />
  </el-select>
</template>

<script>
export default {
  props: {
    valueKey: {
      type: String,
      default: 'value'
    },
    labelKey: {
      type: String,
      default: 'label'
    },
    options: {
      type: [Array, Promise, Function],
      default: () => []
    },
    value: undefined
  },
  data() {
    return {
      opt: []
    }
  },
  watch: {
    options: {
      deep: true,
      handler() {
        this.setOpt()
      }
    }
  },
  created() {
    this.setOpt()
  },
  methods: {
    setOpt() {
      const { options } = this
      if (typeof options === 'function') {
        this.opt = this.setOpt(options())
      } else if (options instanceof Promise) {
        console.log('promise')
        options.then(res => {
          this.opt = res
        })
      } else {
        this.opt = options
      }
    },
    selectChange(val) {
      this.$emit('input', val)
    }
  }
}
</script>
