<template>
  <div class="radio">
    <label class="radio__wrapper"
           :class="{disabled}">
      <span class="radio__inner">
        <input v-if="group"
               type="radio"
               class="radio__input"
               :disabled="disabled"
               :value="value"
               v-model="model"
               @change="tapChange">
        <input v-else
               type="radio"
               class="radio__input"
               :disabled="disabled"
               :checked="checked"
               @change="tapChange">
        <template v-if="icon==='radio'">
          <span class="icon icon--radio unchecked"></span>
          <span class="icon icon--radio checked"></span>
        </template>

      </span>{{` ${label}`}}
    </label>
  </div>
</template>
<script>
import { findComponentUpward } from '../utils/findComponent.js';

export default {
  name: 'Radio',
  model: {
    prop: 'checked',
    event: 'my-change'
  },
  props: {
    checked: {
      type: Boolean,
      default: false
    },
    label: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: String,
      default: ''
    },
    icon: {
      type: String,
      default: 'radio'
    }
  },
  data() {
    return {
      parent: null,
      group: false,
      // 由父组件传递过来的model
      model: ''
    };
  },
  mounted() {
    this.parent = findComponentUpward(this, 'RadioGroup');
    if (this.parent) { this.group = true; }
  },
  methods: {
    tapChange(e) {
      const checked = e.target.checked;
      this.$emit('my-change', checked);

      // 调用父组件方法，将model到父组件上
      this.group && this.parent.change(this.model);
    }
  }
};
</script>
