<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>
    </span>
    <slot></slot>
  </label>
</template>

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

  const name = 'hive-checkbox';

  export default {
    name,
    mixins: [
      FormSize,
      WatchCurValue,
    ],
    model: {
      prop: 'checked',
      event: 'change',
    },
    props: {
      disabled: {
        type: Boolean,
        default: false,
      },
      value: [String, Number, Boolean],
      indeterminate: {
        type: Boolean,
        default: false,
      },
      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;
        this.$emit('change', checked);
        this.curChecked = checked;
      },

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

      onClick(event) {
        const { checked } = event.target;
        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>
