<template>
  <el-select v-model="valueSync" :multiple="multiple" :disabled="disabled" :clearable="clearable">
    <el-option v-for="item in optionsFormated" :key="item.value" :label="$l(item,'label')" :value="item.value" />
  </el-select>
</template>
<script>
export default {
  props: {
    options: Array,
    value: [String, Number, Boolean, Object],
    labelField: {
      type: [String, Function],
      default: 'label'
    },
    valueField: {
      type: String,
      default: 'value'
    },
    multiple: Boolean,
    clearable: Boolean,
    defaultable: Boolean, // 没有值的时候是否选择第一项
    disabled: Boolean
  },
  data() {
    return {
      valueSync: null
    }
  },
  computed: {
    optionsFormated() {
      const arr = []
      this.options.forEach((item, index) => {
        arr.push({
          label: typeof this.labelField === 'string' ? item[this.labelField] : (this.labelField)(item, index),
          value: item[this.valueField]
        })
      })
      return arr
    }
  },
  watch: {
    valueSync(val) {
      this.$emit('input', val)
    },
    value(value) {
      this.valueSync = value
    },
    optionsFormated() {
      this.setDefault()
    }
  },
  created() {
    this.valueSync = this.value
    this.setDefault()
  },
  methods: {
    setDefault() {
      if (!this.defaultable) {
        return false
      }
      if (this.optionsFormated.length && (this.valueSync == null || this.valueSync == '')) {
        this.valueSync = this.optionsFormated[0].value
      }
    }
  }
}
</script>
