<template>
  <el-select
    v-model="actualValue"
    :placeholder="placeholder"
    :size="size"
    :clearable="clearable"
    :multiple="multiple"
    :disabled="disabled"
    :filterable="filterable"
    @remove-tag="(tag) => $emit('removeTag', tag)"
    @change="$emit('input', actualValue)"
  >
    <el-option
      v-for="item in actualItems"
      :key="item.value"
      :ref="item.label"
      :label="$i18n(item.label)"
      :value="item.value"
      :disabled="item.disabled"
    />
  </el-select>
</template>

<script>
import {safeGet} from '../../utils/safeGet'
export default {
  name: 'SpSelect',
  props: ['items', 'clearable', 'value', 'size', 'multiple', 'filterable', 'disabled', 'beforeCreateOptions'],
  data() {
    return {
      actualValue: undefined,
      actualItems: [],
      placeholder: undefined
    }
  },
  watch: {
    items(items) {
      this.updateItems(items)
    },
    value(value) {
      this.updateValue(value)
    }
  },
  created() {
    if (typeof this.items === 'string') {
      try {
        this.$watch(() => {
          return safeGet(this.$store.state, this.items)
        }, (val) => {
          let options = (this.beforeCreateOptions && typeof this.beforeCreateOptions === 'function') ? this.beforeCreateOptions(val) : val
          this.updateItems(options)
        }, {
          immediate: true
        })
      } catch (e) {
        console.log(e)
        throw new Error('bad select options')
      }
    } else {
      this.updateItems(this.items)
    }
    this.updateValue(this.value)
  },
  methods: {
    updateItems(items) {
      // console.log('updateItems', items)
      if (Object.prototype.toString.call(items) === '[object Promise]') {
        this.actualItems = [{
          label: this.$i18n('loading'),
          value: null,
          disabled: true
        }]
        this.placeholder = this.$i18n('loading')
        items.then(data => {
          this.actualItems = data
          this.placeholder = undefined
        }).catch(() => {})
      } else if (typeof items === 'function') {
        this.actualItems = items(this.$store.state)
      } else {
        this.actualItems = items
      }
    },
    updateValue(value) {
      this.actualValue = value
    }
  }
}
</script>
