import { defineComponent, computed, createVNode } from 'vue';
import { UPDATE_MODEL_EVENT, CHANGE_EVENT } from '../_util/constants';
import Checkbox from '../checkbox';
import { COMPONENT_NAME } from './const';

const calcCheckStatus = (checkedNum, optionNum) => {
  if (checkedNum === 0) {
    return 'none';
  }
  if (checkedNum === optionNum) {
    return 'all';
  }
  return 'some';
};
const TransferCheckbox = defineComponent({
  name: `${COMPONENT_NAME}Checkbox`,
  props: {
    modelValue: {
      type: String,
      default: 'none'
    },
    label: {
      type: String,
      required: true
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  emits: [UPDATE_MODEL_EVENT, CHANGE_EVENT],
  setup: (props, _ref) => {
    let {
      emit
    } = _ref;
    const modelValue = computed({
      get: () => props.modelValue,
      set: nextValue => {
        emit(UPDATE_MODEL_EVENT, nextValue);
      }
    });
    const derivedIndeterminate // 公共 Checkbox 的 indeterminate 为单向 prop
    = computed(() => modelValue.value === 'some');
    const derivedModelValue = computed({
      get: () => modelValue.value === 'all',
      // 'some' 状态也视为未勾选，使得在此状态点击 checkbox，能变成勾选状态
      set: nextValue => {
        modelValue.value = nextValue ? 'all' : 'none';
      }
    });
    const handleChange = value => {
      const nextModelValue = value ? 'all' : 'none';
      emit(UPDATE_MODEL_EVENT, nextModelValue);
      emit(CHANGE_EVENT, nextModelValue);
    };
    return () => createVNode(Checkbox, {
      "modelValue": derivedModelValue.value,
      "onUpdate:modelValue": $event => derivedModelValue.value = $event,
      "indeterminate": derivedIndeterminate.value,
      "label": props.label,
      "disabled": props.disabled,
      "onChange": handleChange
    }, null);
  }
});

export { TransferCheckbox, calcCheckStatus };
