"use strict";

exports.__esModule = true;
exports["default"] = void 0;

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

var _reactDom = require("react-dom");

var _instance = _interopRequireDefault(require("../Context/instance.js"));

var _excluded = ["portal", "multiple", "list", "split", "show", "value", "selected", "maskAttribute", "submitAttribute", "cancelAttribute", "optionAttribute", "onVisibleChange"],
    _excluded2 = ["caption", "onClick"];

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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 _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate 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 _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

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

  var refEl = (0, _react.useRef)(null);
  (0, _react.useImperativeHandle)(ref, function () {
    return refEl.current;
  }); // context

  var context = (0, _react.useContext)(_instance["default"]) || {};

  var locale = context.locale || function (remark) {
    return remark || '';
  };

  (0, _react.useEffect)(function () {
    if (!list || !list.length) {
      onVisibleChange && onVisibleChange(false);
      return;
    }

    ;
    [].slice.call(refEl.current.querySelectorAll('.pickerselect-option')).forEach(function (n, i) {
      n.classList.remove('active');

      if (selected && selected.length) {
        for (var _iterator = _createForOfIteratorHelperLoose(selected), _step; !(_step = _iterator()).done;) {
          var option = _step.value;

          if (option.id !== undefined && option.id === list[i].id || option.name === list[i].name) {
            n.classList.add('active');
          }
        }
      } else if (value) {
        var selectedValues = [value];

        if (multiple) {
          selectedValues = value.split(split || ',');
        }

        for (var _iterator2 = _createForOfIteratorHelperLoose(selectedValues), _step2; !(_step2 = _iterator2()).done;) {
          var name = _step2.value;

          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 handleClick(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 caption = props.caption,
        onClick = props.onClick,
        otherProps = _objectWithoutPropertiesLoose(props, _excluded2);

    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 (0, _reactDom.createPortal)( /*#__PURE__*/_react["default"].createElement("div", _extends({
    ref: refEl
  }, otherMaskAttribute, {
    className: "mask picker-mask" + (otherMaskAttribute.className ? ' ' + otherMaskAttribute.className : '') + (show ? ' active' : ''),
    onClick: handleClick
  }), /*#__PURE__*/_react["default"].createElement("div", _extends({}, others, {
    className: "pickerselect" + (others.className ? ' ' + others.className : '') + (show ? ' active' : '')
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "picker-header"
  }, /*#__PURE__*/_react["default"].createElement("a", _extends({}, otherCancelAttribute, {
    className: "picker-cancel" + (cancelAttribute.className ? ' ' + cancelAttribute.className : '')
  }), cancelAttribute.caption || locale('取消', 'cancel')), /*#__PURE__*/_react["default"].createElement("div", {
    className: "picker-header-title"
  }), /*#__PURE__*/_react["default"].createElement("a", _extends({}, otherSubmitAttribute, {
    className: "picker-submit" + (submitAttribute.className ? ' ' + submitAttribute.className : '') + (multiple ? '' : ' disabled')
  }), submitAttribute.caption || locale('完成', 'finish'))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "pickerselect-wrapper"
  }, list.map(function (item, index) {
    return /*#__PURE__*/_react["default"].createElement("div", _extends({
      key: index
    }, otherOptionAttribute, {
      className: "pickerselect-option" + (optionAttribute.className ? ' ' + optionAttribute.className : ''),
      "data-index": index
    }), /*#__PURE__*/_react["default"].createElement("p", {
      className: "pickerselect-option-caption"
    }, item.name), /*#__PURE__*/_react["default"].createElement("i", {
      className: "pickerselect-option-icon"
    }));
  })))), portal || context.portal || document.getElementById('root') || document.body);
});

var _default = _react["default"].memo(Picker, function (prevProps, nextProps) {
  if (nextProps.show === prevProps.show) return true;
  return false;
});

exports["default"] = _default;
module.exports = exports.default;