"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _classnames2 = _interopRequireDefault(require("classnames"));

var _configProvider = _interopRequireDefault(require("../config-provider"));

var _util = require("../util");

var _checkbox = _interopRequireDefault(require("./checkbox"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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 _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

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

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

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; }

var pickOthers = _util.obj.pickOthers;
/** Checkbox.Group */

var CheckboxGroup =
/*#__PURE__*/
function (_Component) {
  _inherits(CheckboxGroup, _Component);

  function CheckboxGroup(props) {
    var _this;

    _classCallCheck(this, CheckboxGroup);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(CheckboxGroup).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "onChange", function (currentValue, e) {
      var value = _this.state.value;
      var index = value.indexOf(currentValue);

      var valTemp = _toConsumableArray(value);

      if (index === -1) {
        valTemp.push(currentValue);
      } else {
        valTemp.splice(index, 1);
      }

      if (!('value' in _this.props)) {
        _this.setState({
          value: valTemp
        });
      }

      _this.props.onChange(valTemp, e);
    });

    var _value = [];

    if ('value' in props) {
      _value = props.value;
    } else if ('defaultValue' in props) {
      _value = props.defaultValue;
    }

    if (!Array.isArray(_value)) {
      if (_value === null || _value === undefined) {
        _value = [];
      } else {
        _value = [_value];
      }
    }

    _this.state = {
      value: _toConsumableArray(_value)
    };
    return _this;
  }

  _createClass(CheckboxGroup, [{
    key: "getChildContext",
    value: function getChildContext() {
      return {
        __group__: true,
        onChange: this.onChange,
        selectedValue: this.state.value,
        disabled: this.props.disabled
      };
    }
  }, {
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      if ('value' in nextProps) {
        var value = nextProps.value;

        if (!Array.isArray(value)) {
          if (value === null || value === undefined) {
            value = [];
          } else {
            value = [value];
          }
        }

        this.setState({
          value: value
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this,
          _classnames;

      var _this$props = this.props,
          className = _this$props.className,
          style = _this$props.style,
          prefix = _this$props.prefix,
          size = _this$props.size,
          disabled = _this$props.disabled,
          itemDirection = _this$props.itemDirection,
          rtl = _this$props.rtl;
      var others = pickOthers(CheckboxGroup.propTypes, this.props);
      var _size = size;

      if (_size !== 'large' && _size !== 'medium') {
        _size = 'medium';
      } // 如果内嵌标签跟dataSource同时存在，以内嵌标签为主


      var children;

      if (this.props.children) {
        children = _react["default"].Children.map(this.props.children, function (child) {
          if (!_react["default"].isValidElement(child)) {
            return child;
          }

          return _react["default"].cloneElement(child, child.props.rtl === undefined ? {
            rtl: rtl
          } : null);
        });
      } else {
        children = this.props.dataSource.map(function (item, index) {
          var option = item;

          if (_typeof(item) !== 'object') {
            option = {
              label: item,
              value: item,
              disabled: disabled
            };
          }

          var checked = _this2.state.value && _this2.state.value.indexOf(option.value) > -1;
          return _react["default"].createElement(_checkbox["default"], {
            size: _size,
            key: index,
            value: option.value,
            checked: checked,
            rtl: rtl,
            disabled: disabled || option.disabled,
            label: option.label
          });
        });
      }

      var cls = (0, _classnames2["default"])((_classnames = {}, _defineProperty(_classnames, "".concat(prefix, "checkbox-group"), true), _defineProperty(_classnames, "".concat(prefix, "checkbox-group-").concat(_size), true), _defineProperty(_classnames, "".concat(prefix, "checkbox-group-").concat(itemDirection), true), _defineProperty(_classnames, className, !!className), _defineProperty(_classnames, "disabled", disabled), _classnames));
      return _react["default"].createElement("span", _extends({
        dir: rtl ? 'rtl' : undefined
      }, others, {
        className: cls,
        style: style
      }), children);
    }
  }]);

  return CheckboxGroup;
}(_react.Component);

_defineProperty(CheckboxGroup, "propTypes", {
  prefix: _propTypes["default"].string,
  rtl: _propTypes["default"].bool,

  /**
   * 自定义类名
   */
  className: _propTypes["default"].string,

  /**
   * 自定义内敛样式
   */
  style: _propTypes["default"].object,

  /**
   * 整体禁用
   */
  disabled: _propTypes["default"].bool,

  /**
   * 可选项列表, 数据项可为 String 或者 Object, 如 `['apple', 'pear', 'orange']` 或者 `[{value: 'apple', label: '苹果',}, {value: 'pear', label: '梨'}, {value: 'orange', label: '橙子'}]`
   */
  dataSource: _propTypes["default"].arrayOf(_propTypes["default"].any),

  /**
   * 被选中的值列表
   */
  value: _propTypes["default"].oneOfType([_propTypes["default"].array, _propTypes["default"].string, _propTypes["default"].number]),

  /**
   * 默认被选中的值列表
   */
  defaultValue: _propTypes["default"].oneOfType([_propTypes["default"].array, _propTypes["default"].string, _propTypes["default"].number]),

  /**
   * checkbox的尺寸
   * @enumdesc 放大版大小, 正常大小
   */
  size: _propTypes["default"].oneOf(['large', 'medium']),

  /**
   * 通过子元素方式设置内部 checkbox
   */
  children: _propTypes["default"].arrayOf(_propTypes["default"].element),

  /**
   * 选中值改变时的事件
   * @param {Array} value 选中项列表
   * @param {Event} e Dom 事件对象
   */
  onChange: _propTypes["default"].func,

  /**
   * 子项目的排列方式
   * - hoz: 水平排列 (default)
   * - ver: 垂直排列
   */
  itemDirection: _propTypes["default"].oneOf(['hoz', 'ver'])
});

_defineProperty(CheckboxGroup, "defaultProps", {
  dataSource: [],
  onChange: function onChange() {},
  prefix: 'next-',
  itemDirection: 'hoz',
  size: 'medium'
});

_defineProperty(CheckboxGroup, "childContextTypes", {
  onChange: _propTypes["default"].func,
  __group__: _propTypes["default"].bool,
  selectedValue: _propTypes["default"].array,
  disabled: _propTypes["default"].bool
});

var _default = _configProvider["default"].config(CheckboxGroup);

exports["default"] = _default;