<template>
  <label :class="_class">
    <span :class="_classItem">
      <input
        type="radio"
        :checked="check"
        :name="name"
        @click="onClick"
        :disabled="isDisabled"
        :value="value"
      >
      <i :class="_classIcon" />
    </span>
    <span :class="_classChild">
      <slot />
    </span>
  </label>
</template>

<script>
import Emitter from 'utils-lib/dist/emitter';
import WatchCurValue from '../scripts/mixins/wacth-cur-value';
import GetItemChecked from '../scripts/mixins/get-item-checked';

const name = 'hive-radio';

export default {
  name,
  mixins: [
    Emitter,
    WatchCurValue,
    GetItemChecked
  ],
  model: {
    prop: 'checked',
    event: 'change'
  },
  props: {
    /**
     * 是否为禁用
     */
    disabled: {
      type: Boolean,
      default: false
    },
    /**
     * 单选的值，对应原生 input 的 value 属性
     */
    value: [String, Number, Boolean],
    /**
     * 是否选中，对应原生 input 的 checked 属性
     */
    checked: Boolean,
    /**
     * 对应原生 input 的 name 属性
     */
    name: String
  },
  data() {
    return {
      check: this.checked,
      curValue: this.value,
      checkedVal: this.gValue,
      buttonType: this.button,
      isDisabled: this.disabled
    };
  },
  computed: {
    _class() {
      return [
        {
          [`${name}`]: !this.buttonType,
          [`${name}--disabled`]: this.isDisabled,
          [`${name}--checked`]: this.check,
          [`hive-button-radio hive-button hive-button--size-default`]: this.buttonType,
          'hive-button-radio--checked hive-button--type-primary': this.check && this.buttonType
        }
      ];
    },
    _classIcon() {
      return [
        `${name}__radio-inner`
      ];
    },
    _classItem() {
      return [
        `${name}__radio`
      ];
    },
    _classChild() {
      return [
        `${name}__child`
      ];
    }
  },
  watch: {
    // 响应选中状态
    checked(value) {
      this.check = value;
    }
  },
  mounted() {
    this.$on('group.change', this.onChange);
    this.$on('group.type', type => {
      this.buttonType = type;
    });
    this.$on('group.disabled', value => {
      this.isDisabled = value;
    });
  },

  methods: {
    onChange(value) {
      if (this.curValue === value) {
        this.check = true;
      } else {
        this.check = false;
      }
    },

    onClick(event) {
      const { checked } = event.target;
      /**
       * 选中状态改变
       */
      this.$emit('change', checked);
      this.dispatch('hive-radio-group', 'radio.click', this.curValue);
    }
  }
};
</script>
