<template>
    <label role="radio"
           :class="radioClass"
           :aria-checked="model === label"
           :aria-disabled="isDisabled">
        <span :class="inputClass">
            <input ref="radio"
                   v-model="model"
                   :disabled="isDisabled"
                   type="radio"
                   class="native"
                   :value="label"
                   aria-hidden="true"
                   @change="handleChange">
        </span>
        <span :class="labelClass">
            <slot>{{label}}</slot>
        </span>
    </label>
</template>

<script>
import { prefix } from 'jdd-design/utils';
export default {
    name: `${prefix}-radio`,
    inject: {
        jddForm: {
            default: null
        },
        jddFormItem: {
            default: null
        },
        jddRadioGroup: {
            default: null
        }
    },
    props: {
        value: [String, Number, Boolean],
        label: [String, Number, Boolean],
        disabled: Boolean,
        name: String,
        size: String
    },
    computed: {
        radioClass() {
            let clsNames = [`${prefix}-radio`];
            this.isDisabled && clsNames.push('is-disabled');
            this.model === this.label && clsNames.push('is-checked');
            return clsNames;
        },
        inputClass() {
            let clsNames = [`${prefix}-radio__input`];
            this.model === this.label && clsNames.push('is-checked');
            return clsNames;
        },
        labelClass() {
            let clsNames = [`${prefix}-radio__label`];
            this.model === this.label && clsNames.push('is-checked');
            return clsNames;
        },
        model: {
            get() {
                return this.jddRadioGroup
                    ? this.jddRadioGroup.value
                    : this.value;
            },
            set(val) {
                if (this.jddRadioGroup) {
                    this.jddRadioGroup.setValue(val);
                } else {
                    this.$emit('input', val);
                }
                this.$refs.radio &&
                    (this.$refs.radio.checked = this.model === this.label);
            }
        },
        isDisabled() {
            return (
                this.disabled ||
                (this.jddRadioGroup && this.jddRadioGroup.disabled) ||
                (this.jddForm && this.jddForm.disabled)
            );
        }
    },
    methods: {
        handleChange() {
            this.$nextTick(() => {
                this.$emit('change', this.model);
            });
            this.jddFormItem && this.jddFormItem.$emit('form.change');
        }
    }
};
</script>