<template>
  <div class="uif-checkbox-group" :name="name">
    <u-checkbox v-for="data in options" :key="data.value" :disabled="disabled" v-bind="data"
                :value="currentValue.includes(data.value)" @u-change="handleChange(data.value, $event)"></u-checkbox>
  </div>
</template>

<script>
import UCheckbox from '@uif/hq/src/components/checkbox'
import {toArray} from '@uif/hq/src/utils/array'
export default {
  inheritAttrs: false,
  name: 'u-checkbox-group',
  components: {
    UCheckbox
  },
  props: {
    value: {
      type: Array,
      default () {
        return []
      }
    },
    name: {
      type: String
    },
    options: {
      type: Array,
      default () {
        return []
      }
    },
    disabled: {
      type: Boolean,
      default () {
        return false
      }
    }
  },
  data () {
    return {
      currentValue: this.value
    }
  },
  watch: {
    value: {
      immediate: true,
      handler (value) {
        this.syncValue()
      }
    }
  },
  created () {
  },
  mounted () {
  },
  methods: {
    handleChange (value, isSelected) {
      if (isSelected) {
        this.currentValue.push(value)
      } else {
        this.currentValue = this.currentValue.filter(val => value !== val)
      }
      this.$emit('input', this.currentValue)
      this.$emit('u-change', this.currentValue)
    },
    syncValue () {
      if (this.value.join(',') !== this.currentValue.join(',')) {
        this.currentValue = toArray(this.value)
      }
    }
  }
}
</script>
