"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

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

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

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

var _userSelector = _interopRequireDefault(require("../../../user-selector"));

var _errorTip = _interopRequireDefault(require("../../../tooltip/error-tip"));

var _userInput = _interopRequireDefault(require("./user-input"));

require("./index.css");

var _excluded = ["name", "label", "placeholder", "value", "onChange", "require", "maxSize", "multiple", "getContainer"];

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

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

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 preCls = 'form-field-user';

function OverlayInner(_ref) {
  var hasError = _ref.hasError,
      hasActive = _ref.hasActive,
      tip = _ref.tip;
  if (hasError) return /*#__PURE__*/_react["default"].createElement("span", {
    style: {
      color: '#F05E5E'
    }
  }, tip);
  if (hasActive) return /*#__PURE__*/_react["default"].createElement("span", {
    style: {
      color: '#3F4755'
    }
  }, tip);
  return /*#__PURE__*/_react["default"].createElement("span", null);
}

var _default = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _classNames;

  var name = props.name,
      label = props.label,
      placeholder = props.placeholder,
      value = props.value,
      onChange = props.onChange,
      require = props.require,
      maxSize = props.maxSize,
      multiple = props.multiple,
      getContainer = props.getContainer,
      restProps = _objectWithoutProperties(props, _excluded);

  var _useState = (0, _react.useState)(''),
      _useState2 = _slicedToArray(_useState, 2),
      tip = _useState2[0],
      setTip = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = _slicedToArray(_useState3, 2),
      hasError = _useState4[0],
      setHasError = _useState4[1];

  var _useState5 = (0, _react.useState)(false),
      _useState6 = _slicedToArray(_useState5, 2),
      hasActive = _useState6[0],
      setHasActive = _useState6[1];

  var _useState7 = (0, _react.useState)(function () {
    if (multiple) {
      return {
        users: value
      };
    }

    if (!value) return {
      users: []
    };
    return {
      users: [value]
    };
  }),
      _useState8 = _slicedToArray(_useState7, 2),
      selectNodes = _useState8[0],
      setSlectNodes = _useState8[1];

  (0, _react.useEffect)(function () {
    var userValue = value; // 单选时，传入是单个节点，要处理成数组

    if (!multiple) {
      if (!value) userValue = [];else userValue = [value];
    }

    setSlectNodes({
      users: userValue
    });
  }, [value]);

  var onUserSelectHandler = function onUserSelectHandler(data) {
    setHasActive(false);
    setHasError(false);
    setTip('');
    var users = [];

    if (multiple) {
      users = data.users;
    } else {
      users = [data[0].data];
    }

    if (maxSize != undefined && users && users.length > maxSize) {
      setHasError(true);
      setTip("\u6700\u591A\u53EF\u8BBE\u7F6E".concat(maxSize, "\u4EBA"));
    }

    setSlectNodes({
      users: users
    });

    if (multiple) {
      onChange(users);
    } else {
      onChange(users[0]);
    }
  };

  var verifing = function verifing() {
    if (maxSize != undefined && selectNodes.users.length > maxSize) {
      var _tip = "\u6700\u591A\u53EF\u8BBE\u7F6E".concat(maxSize, "\u4EBA");

      setHasError(true);
      setTip(_tip);
      return [{
        name: name,
        tip: _tip
      }];
    }

    return [];
  };

  var onPopupVisibleChangeHandler = function onPopupVisibleChangeHandler(visible) {
    setHasActive(false);
    setHasError(false);

    if (visible) {
      var errors = verifing();

      if (errors.length) {
        setHasError(true);
      }

      setHasActive(true);
    }
  };

  var onClearHandler = function onClearHandler() {
    if (multiple) {
      onChange([]);
    } else {
      onChange(undefined);
    }
  };

  var onCancelHandler = function onCancelHandler() {
    setHasActive(false);
  };

  (0, _react.useImperativeHandle)(ref, function () {
    return {
      verifing: verifing
    };
  });
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])(preCls)
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(preCls, "__label"))
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(preCls, "__label-text"))
  }, label), require && /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(preCls, "__label-require"))
  }, "*")), /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(preCls, "__border"), (_classNames = {}, _defineProperty(_classNames, "".concat(preCls, "__border--error"), hasError), _defineProperty(_classNames, "".concat(preCls, "__border--active"), hasActive), _classNames))
  }, /*#__PURE__*/_react["default"].createElement(_errorTip["default"], {
    placement: "topLeft",
    destroyTooltipOnHide: true,
    visible: (hasActive || hasError) && tip,
    overlay: /*#__PURE__*/_react["default"].createElement(OverlayInner, {
      hasActive: hasActive,
      hasError: hasError,
      tip: tip
    }),
    getTooltipContainer: getContainer
  }, /*#__PURE__*/_react["default"].createElement(_userSelector["default"], _extends({
    multiple: multiple,
    selectNodes: selectNodes,
    position: "centerRight",
    onOk: onUserSelectHandler,
    onCancel: onCancelHandler,
    onSelect: onUserSelectHandler,
    disabledDepartSelect: true,
    panes: {
      depart: true,
      group: false
    },
    searchedPanes: {
      user: true,
      depart: false,
      group: false
    },
    onPopupVisibleChange: onPopupVisibleChangeHandler
  }, restProps), /*#__PURE__*/_react["default"].createElement(_userInput["default"], {
    multiple: multiple,
    users: selectNodes.users,
    onClear: onClearHandler,
    placeholder: placeholder
  })))));
});

exports["default"] = _default;