<template>
  <label class="qf-radio" :class="[
      { 'is-disabled': isDisabled },
      { 'is-focus': focus },
      { 'is-checked': model === label }
    ]" role="radio" :tabindex="tabIndex">
    <span class="qf-radio-input" :class="{
        'is-disabled': isDisabled,
        'is-checked': model === label
      }">
      <span class="qf-radio-inner"></span>
      <input class="qf-radio-original" :value="label" type="radio"  @focus="focus = true"
             @blur="focus = false" v-model="model" @change="handleChange" :name="name"
             :disabled="isDisabled" tabindex="-1">
    </span><span class="qf-radio-label">
      <slot></slot>
      <template v-if="!$slots.default">{{label}}</template>
    </span>
  </label>
</template>

<script>
export default {
  name: 'QfRadio',
  props: {
    value: {},
    label: {},
    disabled: Boolean,
    name: String
  },
  data() {
    return {
      focus: false
    };
  },
  computed: {
    isGroup() {
      let parent = this.$parent;
      while (parent) {
        if (parent.$options.componentName !== 'QfRadioGroup') {
          parent = parent.$parent;
        } else {
          this.radioGroup = parent;
          return true;
        }
      }
      return false;
    },
    model: {
      get() {
        return this.isGroup ? this.radioGroup.value : this.value;
      },
      set(val) {
        if (this.isGroup) {
          this.radioGroup.$emit('input', val);
        } else {
          this.$emit('input', val);
        }
      }
    },
    isDisabled() {
      return this.isGroup
        ? this.radioGroup.disabled || this.disabled
        : this.disabled;
    },
    tabIndex() {
      return !this.isDisabled ? (this.isGroup ? (this.model === this.label ? 0 : -1) : 0) : -1;
    }
  },
  methods: {
    handleChange() {
      this.$nextTick(() => {
        this.$emit('change', this.model);
        this.isGroup && this.radioGroup.$emit('handleChange', this.model);
      });
    }
  }
};
</script>
