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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

import React, { forwardRef, useRef, useImperativeHandle, useEffect, useContext } from 'react';
import { createPortal } from 'react-dom';
import Context from '../Context/instance.js';

var Picker = forwardRef(function (_ref, ref) {
  var portal = _ref.portal,
      _ref$multiple = _ref.multiple,
      multiple = _ref$multiple === undefined ? false : _ref$multiple,
      _ref$list = _ref.list,
      list = _ref$list === undefined ? [] : _ref$list,
      _ref$split = _ref.split,
      split = _ref$split === undefined ? ',' : _ref$split,
      _ref$show = _ref.show,
      show = _ref$show === undefined ? false : _ref$show,
      value = _ref.value,
      selected = _ref.selected,
      _ref$maskAttribute = _ref.maskAttribute,
      maskAttribute = _ref$maskAttribute === undefined ? {} : _ref$maskAttribute,
      _ref$submitAttribute = _ref.submitAttribute,
      submitAttribute = _ref$submitAttribute === undefined ? {} : _ref$submitAttribute,
      _ref$cancelAttribute = _ref.cancelAttribute,
      cancelAttribute = _ref$cancelAttribute === undefined ? {} : _ref$cancelAttribute,
      _ref$optionAttribute = _ref.optionAttribute,
      optionAttribute = _ref$optionAttribute === undefined ? {} : _ref$optionAttribute,
      others = _objectWithoutProperties(_ref, ['portal', 'multiple', 'list', 'split', 'show', 'value', 'selected', 'maskAttribute', 'submitAttribute', 'cancelAttribute', 'optionAttribute']);

  var refEl = useRef(null);
  useImperativeHandle(ref, function () {
    return refEl.current;
  });
  // context
  var context = useContext(Context) || {};
  var locale = context.locale || function (key) {
    return key || '';
  };
  useEffect(function () {
    if (!list || !list.length) return;
    [].slice.call(refEl.current.querySelectorAll('.pickerselect-option')).forEach(function (n, i) {
      n.classList.remove('active');
      if (selected && selected.length) {
        for (var _iterator = selected, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
          var _ref2;

          if (_isArray) {
            if (_i >= _iterator.length) break;
            _ref2 = _iterator[_i++];
          } else {
            _i = _iterator.next();
            if (_i.done) break;
            _ref2 = _i.value;
          }

          var option = _ref2;

          if (option.id !== undefined && option.id === list[i].id || option.name === list[i].name) {
            n.classList.add('active');
          }
        }
      } else if (value) {
        var selectedValues = value.split(split || ',');
        for (var _iterator2 = selectedValues, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
          var _ref3;

          if (_isArray2) {
            if (_i2 >= _iterator2.length) break;
            _ref3 = _iterator2[_i2++];
          } else {
            _i2 = _iterator2.next();
            if (_i2.done) break;
            _ref3 = _i2.value;
          }

          var name = _ref3;

          if (name === list[i].name) {
            n.classList.add('active');
          }
        }
      }
    });
  }, [show]); // eslint-disable-line
  // 构建值
  function buildValue(options) {
    if (!multiple) return options[0].name;
    var value = options.map(function (item) {
      return item.name;
    });
    return value.join(split || ',');
  }
  // 点击遮罩
  function onClick(e) {
    if (e.target.classList.contains('picker-mask')) {
      // 点击遮罩
      if (maskAttribute.onClick) maskAttribute.onClick(e);
    } else if (e.target.classList.contains('pickerselect-option')) {
      // 点击项
      if (optionAttribute.onClick) optionAttribute.onClick(e);
      var index = e.target.getAttribute('data-index');
      if (!multiple && submitAttribute.onClick) {
        e.activeOptions = [list[index]];
        e.activeIndex = [Number(index)];
        var _value = buildValue(e.activeOptions);
        var options = e.activeOptions;
        submitAttribute.onClick(e, _value, options);
      } else {
        e.target.classList.toggle('active');
      }
    } else if (e.target.classList.contains('picker-submit')) {
      // 点击确定按钮
      var selectedOptions = [];
      var selectedIndex = [];
      [].slice.call(refEl.current.querySelectorAll('.pickerselect-option.active')).forEach(function (n) {
        var index = n.getAttribute('data-index');
        selectedOptions.push(list[index]);
        selectedIndex.push(index);
      });
      e.activeOptions = selectedOptions;
      e.activeIndex = selectedIndex;
      var _value2 = buildValue(e.activeOptions);
      var _options = e.activeOptions;
      if (submitAttribute.onClick) submitAttribute.onClick(e, _value2, _options);
    } else if (e.target.classList.contains('picker-cancel')) {
      // 点击取消按钮
      if (cancelAttribute.onClick) cancelAttribute.onClick(e);
    }
  }
  // 过滤已经回调的属性
  function filterProps(props) {
    if (!props) return {};

    var onClick = props.onClick,
        otherProps = _objectWithoutProperties(props, ['onClick']);

    return _extends({}, otherProps);
  }
  // 如果没有数据, 则不显示
  if (!list || !list.length) return null;
  // 剔除掉onClick事件, 因为在instance时已经回调了
  var otherMaskAttribute = filterProps(maskAttribute);
  var otherSubmitAttribute = filterProps(submitAttribute);
  var otherCancelAttribute = filterProps(cancelAttribute);
  var otherOptionAttribute = filterProps(optionAttribute);
  return createPortal(React.createElement(
    'div',
    _extends({ ref: refEl }, otherMaskAttribute, { className: 'mask picker-mask' + (otherMaskAttribute.className ? ' ' + otherMaskAttribute.className : '') + (show ? ' active' : ''), onClick: onClick }),
    React.createElement(
      'div',
      _extends({}, others, { className: 'pickerselect' + (others.className ? ' ' + others.className : '') + (show ? ' active' : '') }),
      React.createElement(
        'div',
        { className: 'picker-header' },
        React.createElement(
          'a',
          _extends({}, otherCancelAttribute, { className: 'picker-cancel' + (otherCancelAttribute.className ? ' ' + otherCancelAttribute.className : '') }),
          otherCancelAttribute.caption || locale('取消', 'cancel')
        ),
        React.createElement(
          'a',
          _extends({}, otherSubmitAttribute, { className: 'picker-submit' + (otherSubmitAttribute.className ? ' ' + submitAttribute.className : '') + (multiple ? '' : ' disabled') }),
          otherSubmitAttribute.caption || locale('完成', 'finish')
        )
      ),
      React.createElement(
        'div',
        { className: 'pickerselect-wrapper' },
        list.map(function (item, index) {
          return React.createElement(
            'div',
            _extends({ key: index }, otherOptionAttribute, { className: 'pickerselect-option' + (otherOptionAttribute.className ? ' ' + otherOptionAttribute.className : ''), 'data-index': index }),
            React.createElement(
              'p',
              { className: 'pickerselect-option-caption' },
              item.name
            ),
            React.createElement('i', { className: 'pickerselect-option-icon' })
          );
        })
      )
    )
  ), portal || context.portal || document.getElementById('root') || document.body);
});

export default React.memo(Picker, function (prevProps, nextProps) {
  if (nextProps.show === prevProps.show) return true;
  return false;
});