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

    const prefixCls = 'yy-radio-group'
    export default {
        name: 'YYRadioGroup',
        mixins: [ Emitter ],
        props: {
            value: {
                type: [String, Number],
                default: ''
            },
            type: {
                validator (value) {
                    return oneOf(value, ['button'])
                }
            },
            vertical: {
                type: Boolean,
                default: false
            },
            size: {
                validator (value) {
                    return oneOf(value, ['small', 'large'])
                }
            }
        },
        data () {
            return {
                currentValue: this.value,
                childrens: []
            }
        },
        computed: {
            classes () {
                return [
                    `${prefixCls}`,
                    {
                        [`${prefixCls}-${this.type}`]: !!this.type,
                        [`${prefixCls}-vertical`]: this.vertical,
                        [`${prefixCls}-${this.size}`]: !!this.size
                    }
                ]
            }
        },
        watch: {
            value () {
                if(this.currentValue !== this.value){
                    this.currentValue = this.value
                    this.$nextTick(()=>{
                        this.updateValue()
                    })
                }
            }
        },
        methods: {
            updateValue () {
                this.childrens = findComponentsDownward(this, 'YYRadio')
                if (this.childrens) {
                    this.childrens.forEach(child => {
                        child.currentValue = this.currentValue === child.label
                        child.group = true
                    })
                }
            },
            handleChange (data) {
                this.currentValue = data.value
                this.updateValue()
                this.$emit('input', data.value)
                this.$emit('on-change', data.value)
                this.dispatch('YYFormItem', 'on-form-change', data.value)
            }
        },
        mounted () {
            this.updateValue()
        }
    }
</script>
