import { rpx2vw4style as __rpx2vw__ } from "babel-runtime-jsx-style-transform";

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import { __rest } from "tslib";
import classNames from 'classnames';
import React, { createElement, forwardRef, useCallback, Children } from "react";
import { Text } from "@alifd/meet-react-component-one";
import { getDataSourceFromChildren, isFunction, isNumber, isString, isValidArray } from '../utils';
import { useValue } from '../utils/hooks';
import { getItemsFromDataSource } from '../utils/tree';
import View from '../view';
import Checkbox from './checkbox';

var CheckboxGroup = function CheckboxGroup(props, ref) {
  var _props$size = props.size,
      size = _props$size === void 0 ? 'medium' : _props$size,
      _props$prefix = props.prefix,
      prefix = _props$prefix === void 0 ? 'mt-' : _props$prefix,
      _props$direction = props.direction,
      direction = _props$direction === void 0 ? 'ver' : _props$direction,
      defaultValue = props.defaultValue,
      dataSource = props.dataSource,
      className = props.className,
      onChange = props.onChange,
      disabled = props.disabled,
      children = props.children,
      readOnly = props.readOnly,
      valueProp = props.value,
      labelAlign = props.labelAlign,
      isPreview = props.isPreview,
      renderPreview = props.renderPreview,
      previewClassNameProp = props.previewClassName,
      previewStyle = props.previewStyle,
      others = __rest(props, ["size", "prefix", "direction", "defaultValue", "dataSource", "className", "onChange", "disabled", "children", "readOnly", "value", "labelAlign", "isPreview", "renderPreview", "previewClassName", "previewStyle"]);

  var previewClassName = classNames(previewClassNameProp, "".concat(prefix, "form-item-input--preview-").concat(size));

  var _useValue = useValue(props, [], {
    fitValue: function fitValue(v) {
      if (v && !Array.isArray(v)) {
        return [v];
      }

      if (!isValidArray(v)) {
        return [];
      }

      return v;
    },
    compare: function compare(a, b) {
      return a.toString() === b.toString();
    }
  }),
      _useValue2 = _slicedToArray(_useValue, 3),
      value = _useValue2[0],
      setValue = _useValue2[1],
      isControlled = _useValue2[2];

  var handleChange = useCallback(function (selected, checkBoxValue, e) {
    if (!selected) {
      var index = value.indexOf(checkBoxValue);

      var newGroup = _toConsumableArray(value);

      if (index >= 0) {
        newGroup.splice(index, 1);

        if (!isControlled) {
          setValue(newGroup);
        }
      }

      if (!disabled && !readOnly && onChange) {
        onChange(newGroup, e);
      }
    }

    if (!disabled && !readOnly && selected) {
      var _newGroup = [].concat(_toConsumableArray(value), [checkBoxValue]);

      if (!isControlled) {
        setValue(_newGroup);
      }

      if (onChange) {
        onChange(_newGroup, e);
      }
    }
  }, [value, setValue, isControlled, onChange]);
  var content;
  var ds = dataSource;

  if (!ds && Children.count(children) > 0) {
    ds = getDataSourceFromChildren(children);
  }

  if (isValidArray(ds)) {
    content = ds.map(function (item, index) {
      var itemData = {
        style: {},
        value: null,
        checked: false,
        label: '',
        text: '',
        disabled: false,
        size: size
      };

      if (isString(item) || isNumber(item)) {
        itemData.value = item;
      } else {
        itemData = Object.assign(Object.assign({}, itemData), item);
      }

      var label = itemData.label || itemData.text || itemData.value;
      var isLast = index === ds.length - 1;
      return /*#__PURE__*/React.createElement(Checkbox, _extends({}, itemData, {
        key: "meet_ck_".concat(index),
        className: classNames(_defineProperty({}, "".concat(prefix, "checkbox-item--").concat(direction, "-").concat(size), !isLast)),
        style: __rpx2vw__(itemData.style),
        onChange: function onChange(selected, e) {
          return handleChange(selected, itemData.value, e);
        },
        checked: itemData.checked || value.includes(itemData.value),
        disabled: disabled || itemData.disabled
      }), label);
    });
  }

  if (isPreview) {
    if (isFunction(renderPreview)) {
      return /*#__PURE__*/React.createElement(View, {
        className: previewClassName,
        style: __rpx2vw__(previewStyle)
      }, renderPreview(getItemsFromDataSource(ds, value)));
    }

    return /*#__PURE__*/React.createElement(Text, {
      className: previewClassName,
      style: __rpx2vw__(previewStyle)
    }, getItemsFromDataSource(ds, value).map(function (v) {
      return v.label || v.text;
    }).join(','));
  }

  return /*#__PURE__*/React.createElement(View, _extends({
    ref: ref,
    className: classNames(className, "".concat(prefix, "checkbox-group"), "".concat(prefix, "checkbox-group--").concat(direction), "".concat(prefix, "checkbox-group--").concat(labelAlign, "-").concat(size))
  }, others), content);
};

export default /*#__PURE__*/forwardRef(CheckboxGroup);