<template>
  <label :class="_class">
    <span :class="_classItem">
      <input
        type="checkbox"
        @change="onChange"
        :checked="curChecked"
        :indeterminate="curIndeterminate"
        :name="name"
        @click="onClick"
        :disabled="curDisabled"
      >
      <span class="hive-checkbox__checkbox-inner" />
    </span>
    <slot />
  </label>
</template>

<script>
import WatchCurValue from '../scripts/mixins/wacth-cur-value';

const name = 'hive-checkbox';

export default {
  name,
  mixins: [
    WatchCurValue
  ],
  model: {
    prop: 'checked',
    event: 'change'
  },
  props: {
    /**
     * 是否禁用
     */
    disabled: {
      type: Boolean,
      default: false
    },
    /**
     * 原生 value 属性
     */
    value: [String, Number, Boolean],
    /**
     * 是否为半选中状态
     */
    indeterminate: {
      type: Boolean,
      default: false
    },
    /**
     * 原生 name 属性
     */
    name: String,
    /**
     * 当前是否勾选
     */
    checked: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      curValue: this.value,
      curIndeterminate: this.indeterminate,
      curChecked: this.checked,
      curDisabled: this.disabled
    };
  },
  computed: {
    _class() {
      return [
        `${name}`,
        {
          [`${name}--disabled`]: this.curDisabled
        }
      ];
    },
    _classItem() {
      return [
        `${name}__checkbox`
      ];
    }
  },
  watch: {
    // 响应半选中状态
    indeterminate(value) {
      this.curIndeterminate = value;

      // 半选中为true时, 选中为false
      if (value) {
        this.curChecked = false;
      }
    },

    // 响应选中状态
    checked(value) {
      this.curChecked = value;
    },

    value(value) {
      // 选中为true时, 半选中为false
      if (value) {
        this.curIndeterminate = false;
      }
    },

    disabled(value) {
      this.curDisabled = value;
    }
  },
  mounted() {
    this.$on('group.change', this.parentChange);
    this.$on('group.disabled', val => {
      this.curDisabled = val;
    });
  },

  methods: {
    onChange(event) {
      const { checked } = event.target;
      /**
       * 选中变化事件
       * @param {Boolean} checked 当前操作的选中状态
       */
      this.$emit('change', checked);
      this.curChecked = checked;
    },

    parentChange(val) {
      if (val === '') {
        this.curChecked = false;
      }
      if (this.curValue === val) {
        this.curChecked = true;
      }
    },

    onClick(event) {
      /**
       * 选框点击事件
       * @param {Objeact} event 当前点击事件
       */
      this.$emit('click', event);
      if (!this.curChecked) {
        this.dispatch('hive-checkbox-group', 'checkbox.click', this.curValue);
      } else {
        this.dispatch('hive-checkbox-group', 'checkbox.remove', this.curValue);
      }
    }
  }
};
</script>
