<template>
  <div class="micro-input-select">
    <label 
        :for="`dropdownSelect${_uid}`"
        v-if="caption">{{ caption }} <span class="mandatory-mark text-danger" v-show="mandatory">*</span></label>

    <select
        :class="`custom-select form-select ${extra_class}`"
        :id="`dropdownSelect${_uid}`" 
        :value="currentValue"
        :disabled="disabled" 
         @input="handleInput">
        <option 
            v-for="item in optionList" 
            :value="item.value" 
            :key="item.name || item.value" 
            :disabled="item.disabled"
            :selected="item.value == currentValue">{{ item.name || item.value }}
        </option>
    </select>

    <small class="form-text text-muted" v-if="description">
      {{ description }}
    </small>
  </div>
</template>

<script>
export default {
  props: {
    'caption': String, 
    'value': [String, Number, Object, Array], 
    'options': [Object, Array, String], 
    'description': String,
    'disabled' : {
      type: Boolean,
      default: false
    },
    'mandatory' : {
      type: Boolean,
      default: false
    },
    extra_class: String,
  },
  data () {
    return {
      currentValue: null,
      optionList: [],
    }
  },

  created () {
    const vm = this

    vm.loadOptions(vm.options)
    vm.currentValue = vm.value
  },

  methods: {
    loadOptions (list) {
      const vm = this

      if (typeof list == 'string') {
        list.split('|').forEach(e => {
          vm.optionList.push({
            name: e.trim(),
            value: e.trim(),
          })

          if (! vm.value && e.trim() == '-') {
            vm.currentValue = e.trim()
          }
        })
      } else {
        vm.optionList = list
      }
    },

    handleInput (e) {
      const vm = this
      vm.myValue = e.target.value
      vm.$emit('input', e.target.value)
    }
  },

  watch: {
    value: function (newValue) {
      const vm = this
      vm.currentValue = newValue
    },

    options: function (newOptions) {
      const vm = this
      vm.loadOptions(newOptions)
    }
  },
}
</script>

<style lang="scss">
  .micro-input-select {
    label {
      display: block;
    }
  }
</style>