import { createVNode as _createVNode, isVNode as _isVNode } from "vue";
import { defineComponent, reactive, watch, provide, getCurrentInstance, toRef } from "vue";
import { getSlot } from '../_util/props-util';
import Checkbox from "./Checkbox";

function _isSlot(s) {
  return typeof s === 'function' || Object.prototype.toString.call(s) === '[object Object]' && !_isVNode(s);
}

export const checkboxGroupContext = Symbol('checkboxGroupContext');
const empty = [];
export default defineComponent({
  name: 'x-checkbox-group',
  props: {
    prefixCls: {
      default: 'x-checkbox-group'
    },
    name: String,
    options: Array,
    value: Array,
    vertical: Boolean,
    disabled: Boolean
  },
  emits: ['update:value', 'change'],

  setup(props, {
    emit
  }) {
    const {
      proxy: vm
    } = getCurrentInstance();
    const state = reactive({
      value: props.value || empty
    });
    watch(() => props.value, value => [state.value = value || empty]);

    function toggleOption(opt) {
      const i = state.value.indexOf(opt.value),
            value = [...state.value];

      if (i > -1) {
        value.splice(i, 1);
      } else {
        value.push(opt.value);
      }

      emit('update:value', value);
      emit('change', value);
    } // ========================== Provide ==========================


    provide(checkboxGroupContext, {
      disabledRef: toRef(props, 'disabled'),
      nameRef: toRef(props, 'name'),
      valueRef: toRef(state, 'value'),
      toggleOption
    });
    return () => {
      var _props$options;

      const {
        prefixCls
      } = props;
      let children;

      if ((_props$options = props.options) !== null && _props$options !== void 0 && _props$options.length) {
        children = props.options.map(opt => {
          if (typeof opt === 'string') {
            return _createVNode(Checkbox, {
              "key": opt,
              "checked": state.value.indexOf(opt) != -1,
              "name": props.name,
              "value": opt,
              "disabled": props.disabled
            }, _isSlot(opt) ? opt : {
              default: () => [opt]
            });
          } else {
            const val = opt.value,
                  style = opt.style;
            return _createVNode(Checkbox, {
              "key": val,
              "checked": state.value.indexOf(val) != -1,
              "name": props.name,
              "value": val,
              "disabled": opt.disabled || props.disabled,
              "style": style
            }, {
              default: () => [opt.label]
            });
          }
        });
      } else {
        children = getSlot(vm);
      }

      const cls = [prefixCls, {
        [`${prefixCls}-vertical`]: props.vertical
      }];
      return _createVNode("div", {
        "class": cls
      }, [children]);
    };
  }

});