<template>
  <view class="ml-checkbox" :class="[className || '', {'is-vertical': vertical, 'is-checked': checked, 'is-half': indeterminate, 'is-disabled': disabled}]" @tap="tapEvent">
    <view class="ml-checkbox-icon">
      <ml-icon :name="checked ? 'checkbox-checked' : (indeterminate ? 'checkbox-indeterminate' : 'checkbox-unchecked')"></ml-icon>
    </view>
    <view class="ml-checkbox-content">
      <slot>
        <view>{{ content }}</view>
      </slot>
    </view>
  </view>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'MlCheckbox',
  options: {
    virtualHost: true
  },
  props: {
    modelValue: [Boolean, Number, String],
    label: {
      type: [Boolean, Number, String],
      default: null
    },
    indeterminate: Boolean,
    disabled: Boolean,
    vertical: Boolean,
    content: String,
    className: String
  },
  computed: {
    checked () {
      if (this.label === null) {
        return !!this.modelValue
      }
      return this.label === this.modelValue
    }
  },
  methods: {
    tapEvent () {
      if (this.disabled) {
        return
      }
      let value
      if (this.label === null) {
        value = !this.modelValue
      } else {
        value = this.checked ? null : this.label
      }
      this.$emit('update:modelValue', value)
      this.$emit('change', { value, label: this.label, checked: !this.checked })
    }
  }
})
</script>

<style lang="scss">
.ml-checkbox {
  display: flex;
  margin-right: 20rpx;
  align-items: center;
  flex-grow: 1;
  // #ifdef H5
  cursor: pointer;
  // #endif
  &.is-checked {
    color: $ml-theme-primary-color;
  }
  &.is-half {
    color: $ml-theme-primary-color;
  }
  &.is-disabled {
    color: rgba(0,0,0,0.25);
  }
  &.is-vertical {
    .ml-checkbox-content {
      flex-direction: column;
    }
  }
}
.ml-checkbox-icon {
  width: 40rpx;
  margin-right: 10rpx;
  align-items: center;
  font-size: 1.3em;
}
.ml-checkbox-icon,
.ml-checkbox-content {
  display: flex;
  flex-direction: row;
}
.ml-checkbox-content {
  flex-grow: 1;
}
</style>
