
import { ref, watch } from 'vue'

export default () => {
  let cache = []

  return {
    props: ['modelValue', 'label', 'hideAll', 'allText', 'notDefault', 'disabled'],
    setup(props) {
      let options = ref(cache)
      let value = ref(props.modelValue || '')
  
      watch(options, () => cache = options.value)

      return {
        options,
        value
      }
    },
    watch: {
      value() {
        this.$emit('update:modelValue', this.value)
        this.$emit('update:label', this.getLabel())
      },
      modelValue() {
        this.value = this.modelValue
      }
    },
    computed:{
      showAll() {
        return this.hideAll !== '' || this.hideAll
      }
    }, 
    methods: {
      getLabel() {
        let item = this.options.find(item => item.id == this.value)
        if (item) {
          return item.name
        } else {
          return ''
        }
      }
    },
    mounted() {
      if (!this.modelValue && this.hideAll === '' && !this.notDefault) {
        this.value = this.options[0].id
      }
      this.$emit('update:modelValue', this.value)
      this.$emit('update:label', this.getLabel())
    }
  }
}
