<template>
    <div :class="classes">
        <slot></slot>
    </div>
</template>
<script>
    import { findComponentsDownward, oneOf } from '../../../utils/assist'
    import Emitter from '../../../mixins/emitter'

    const prefixCls = 'yy-checkbox-group'
    /**
     * @displayName CheckboxGroup
     */
    export default {
        name: 'YYCheckboxGroup',
        mixins: [ Emitter ],
        props: {
            value: {
                type: Array,
                default () {
                    return []
                }
            },
            vertical: {
                type: Boolean,
                default: false
            },
            size: {
                validator (value) {
                    return oneOf(value, ['small', 'large'])
                }
            }
        },
        data () {
            return {
                currentValue: this.value,
                childrens: []
            }
        },
        computed: {
            classes () {
                return [
                    `${prefixCls}`,
                    {
                        [`${prefixCls}-vertical`]: this.vertical,
                        [`${prefixCls}-${this.size}`]: !!this.size
                    }
                ]
            }
        },
        watch: {
            value () {
                this.updateModel(true)
            }
        },
        methods: {
            updateModel(update) {
                this.childrens = findComponentsDownward(this, 'YYCheckbox')
                if (this.childrens) {
                    const { value } = this
                    this.childrens.forEach(child => {
                        child.model = value

                        if (update) {
                            child.currentValue = value.indexOf(child.label) >= 0
                            child.group = true
                        }
                    })
                }
            },
            handleChange(data) {
                this.currentValue = data
                this.$emit('input', data)
                this.$emit('on-change', data)
                this.dispatch('YYFormItem', 'on-form-change', data)
            }
        },
        mounted () {
            this.updateModel(true)
        }
    }
</script>
