"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 _context = require("../../context");

var _requestApis = require("../../request-apis");

var _openData = require("../../../../utils/open-data");

var _selectorGenerater = _interopRequireDefault(require("./selector-generater"));

var _popup = _interopRequireDefault(require("../../../popup"));

var _getLocale = require("../../../../utils/getLocale");

var _enum = require("../../enum");

require("../../index.css");

require("./index.css");

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

var defauleSelectNodes = {
  groups: [],
  departments: [],
  users: []
};

var _default = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var multiple = props.multiple,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      trigger = props.trigger,
      children = props.children,
      _props$onOk = props.onOk,
      onOk = _props$onOk === void 0 ? function () {} : _props$onOk,
      onCancel = props.onCancel,
      _props$onSelect = props.onSelect,
      onSelect = _props$onSelect === void 0 ? function () {} : _props$onSelect,
      _props$position = props.position,
      position = _props$position === void 0 ? 'bottomRight' : _props$position,
      _props$selectNodes = props.selectNodes,
      selectNodes = _props$selectNodes === void 0 ? defauleSelectNodes : _props$selectNodes,
      sourceFrom = props.sourceFrom,
      departOnly = props.departOnly,
      searchUserOnly = props.searchUserOnly,
      isVerify = props.isVerify,
      _props$departId = props.departId,
      departId = _props$departId === void 0 ? '-1' : _props$departId,
      _props$auth = props.auth,
      auth = _props$auth === void 0 ? false : _props$auth,
      _props$placeholder = props.placeholder,
      placeholder = _props$placeholder === void 0 ? (0, _getLocale.getLocale)('Mod_Pleaseselect') : _props$placeholder,
      authType = props.authType,
      getDepartRoot = props.getDepartRoot,
      _props$destroyPopupOn = props.destroyPopupOnHide,
      destroyPopupOnHide = _props$destroyPopupOn === void 0 ? true : _props$destroyPopupOn,
      _props$forceRender = props.forceRender,
      forceRender = _props$forceRender === void 0 ? false : _props$forceRender,
      _props$isGetRoot = props.isGetRoot,
      isGetRoot = _props$isGetRoot === void 0 ? false : _props$isGetRoot,
      _props$disabledDepart = props.disabledDepartSelect,
      disabledDepartSelect = _props$disabledDepart === void 0 ? false : _props$disabledDepart,
      _props$panes = props.panes,
      panes = _props$panes === void 0 ? {
    depart: true,
    group: true,
    subordinate: true
  } : _props$panes,
      _props$searchedPanes = props.searchedPanes,
      searchedPanes = _props$searchedPanes === void 0 ? {
    user: true,
    depart: true,
    group: true
  } : _props$searchedPanes,
      _onPopupVisibleChange = props.onPopupVisibleChange,
      popClass = props.popClass,
      _props$searchWord = props.searchWord,
      searchWord = _props$searchWord === void 0 ? '' : _props$searchWord,
      _props$showSearchInpu = props.showSearchInput,
      showSearchInput = _props$showSearchInpu === void 0 ? true : _props$showSearchInpu,
      _props$noText = props.noText,
      noText = _props$noText === void 0 ? false : _props$noText,
      getPopupContainer = props.getPopupContainer,
      _props$popupAlign = props.popupAlign,
      popupAlign = _props$popupAlign === void 0 ? {
    offset: [0, 0],
    overflow: {
      adjustX: true,
      adjustY: true
    },
    targetOffset: [0, 0]
  } : _props$popupAlign,
      _props$enableDimissio = props.enableDimissionSwitch,
      enableDimissionSwitch = _props$enableDimissio === void 0 ? false : _props$enableDimissio,
      staffStatusDefault = props.staffStatusDefault,
      autoClear = props.autoClear;

  var _useState = (0, _react.useState)([]),
      _useState2 = _slicedToArray(_useState, 2),
      selected = _useState2[0],
      setSelected = _useState2[1];

  var _useState3 = (0, _react.useState)(''),
      _useState4 = _slicedToArray(_useState3, 2),
      selectedText = _useState4[0],
      setSelectedText = _useState4[1];

  var _useState5 = (0, _react.useState)((staffStatusDefault === null || staffStatusDefault === void 0 ? void 0 : staffStatusDefault.toString()) || _enum.StaffStatus.OnTheJob),
      _useState6 = _slicedToArray(_useState5, 2),
      staffStatus = _useState6[0],
      setStaffStatus = _useState6[1];

  var _useState7 = (0, _react.useState)(),
      _useState8 = _slicedToArray(_useState7, 2),
      jsxDomValues = _useState8[0],
      setJsxDomValues = _useState8[1];

  var _useState9 = (0, _react.useState)(false),
      _useState10 = _slicedToArray(_useState9, 2),
      visible = _useState10[0],
      setVisible = _useState10[1];

  var setSelectedByProps = function setSelectedByProps() {
    var selected = [];
    var texts = [];
    var jsxDomValues = [];
    var groups = selectNodes.groups;
    var departments = selectNodes.departments;
    var users = selectNodes.users;
    (groups || []).forEach(function (data) {
      selected.push({
        nodeType: 'group',
        id: data.id,
        data: data
      });
      texts.push(data.name);
      jsxDomValues.push( /*#__PURE__*/_react["default"].createElement("span", null, data.name));
    });
    (departments || []).forEach(function (data) {
      selected.push({
        nodeType: 'depart',
        id: data.id,
        data: data
      });
      texts.push(data.name);
      jsxDomValues.push( /*#__PURE__*/_react["default"].createElement(_openData.OpenDepartmentName, {
        id: data.id,
        name: data.name
      }));
    });
    (users || []).forEach(function (data) {
      selected.push({
        nodeType: 'person',
        id: "".concat(data.userId),
        data: data
      });
      texts.push(data.name);
      jsxDomValues.push( /*#__PURE__*/_react["default"].createElement(_openData.OpenUserName, {
        id: data.userId,
        name: data.name
      }));
    });
    var text = texts.join('、'); // if (!text) text = placeholder;

    setSelectedText(text);
    setJsxDomValues(jsxDomValues);
    setSelected(selected);
  };

  (0, _react.useEffect)(function () {
    setSelectedByProps();
  }, [selectNodes]); // 如果需要或许tree的顶级部门节点，则独立调用接口取出数据

  (0, _react.useEffect)(function () {
    if (getDepartRoot) {
      (0, _requestApis.getTreeData)('-1', {
        departOnly: departOnly,
        auth: auth,
        isGetRoot: isGetRoot,
        sourceFrom: sourceFrom,
        staffStatus: staffStatus
      }).then(function (departs) {
        var rootNode;

        for (var i = 0; i < departs.length; i++) {
          var it = departs[i];

          if (it.id == '-1') {
            rootNode = it;
            break;
          }

          if (!rootNode) rootNode = departs[0];
        }

        getDepartRoot(rootNode);
      });
    }
  }, [staffStatus]);
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      open: function open() {
        return setVisible(true);
      },
      close: function close() {
        return setVisible(false);
      }
    };
  });

  var onOkHandler = function onOkHandler(selectNodes, e) {
    if (autoClear) setSelected([]);else setSelected(selectNodes);
    var texts = [];
    var users = [];
    var groups = [];
    var departments = []; // 返回react组件形式的value，应用于企业微信

    var jsxDomValues = [];
    selectNodes.forEach(function (item) {
      switch (item.nodeType) {
        case 'person':
          users.push(item.data);
          texts.push(item.data.name);
          jsxDomValues.push( /*#__PURE__*/_react["default"].createElement(_openData.OpenUserName, {
            id: item.data.userId,
            name: item.data.name
          }));
          break;

        case 'depart':
          departments.push(item.data);
          texts.push(item.data.name);
          jsxDomValues.push( /*#__PURE__*/_react["default"].createElement(_openData.OpenDepartmentName, {
            id: item.data.departmentId,
            name: item.data.departmentName
          }));
          break;

        case 'group':
          groups.push(item.data);
          texts.push(item.data.name);
          jsxDomValues.push( /*#__PURE__*/_react["default"].createElement("span", null, item.data.name));
          break;

        default:
          break;
      }
    });
    var wechartOpts = {
      isWechat: (0, _openData.isWechat)(),
      jsxDomValues: jsxDomValues
    };

    if (multiple) {
      onOk({
        users: users,
        departments: departments,
        groups: groups
      }, wechartOpts, {
        selectNodes: selectNodes
      });
    } else {
      onSelect(selectNodes, wechartOpts, e);
    }

    var text = texts.join('、'); // if (!text) text = placeholder;

    if (!noText) {
      setSelectedText(text);
      setJsxDomValues(jsxDomValues);
    }

    setTimeout(function () {
      setVisible(false);
    }, 0);
  };

  var onCancelHandler = function onCancelHandler() {
    setVisible(false);
    onCancel && onCancel();
  };

  var onChangeVisible = function onChangeVisible() {
    setVisible(!visible);
  };

  var popup = /*#__PURE__*/_react["default"].createElement(_selectorGenerater["default"], {
    multiple: multiple,
    autoClear: autoClear // key={staffStatus}
    ,
    onCancel: onCancelHandler,
    onOk: onOkHandler,
    selected: selected,
    onSelect: onOkHandler,
    onStaffStatusChange: setStaffStatus,
    showSearchInput: showSearchInput,
    staffStatus: staffStatus
  });

  if (disabled) return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("span", {
    className: "persel-selector-field persel-selector-field--disabled"
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: "persel-selector-field__text"
  }, (0, _openData.isWechat)() ? jsxDomValues : selectedText || /*#__PURE__*/_react["default"].createElement("span", {
    className: "persel-selector-field__text-holder"
  }, placeholder))));
  if (!visible && noText) return null;
  return /*#__PURE__*/_react["default"].createElement(_context.CommonContext.Provider, {
    value: {
      sourceFrom: sourceFrom,
      departOnly: departOnly,
      searchUserOnly: searchUserOnly,
      isVerify: isVerify,
      auth: auth,
      departId: departId,
      authType: authType,
      isGetRoot: isGetRoot,
      disabledDepartSelect: disabledDepartSelect,
      panes: panes,
      searchWord: searchWord,
      searchedPanes: searchedPanes,
      enableDimissionSwitch: enableDimissionSwitch,
      staffStatus: staffStatus
    }
  }, /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_popup["default"], {
    popup: popup,
    popupVisible: visible,
    popupPlacement: position,
    forceRender: forceRender,
    destroyPopupOnHide: destroyPopupOnHide,
    extraClass: popClass,
    getPopupContainer: getPopupContainer,
    popupAlign: popupAlign,
    onPopupVisibleChange: function onPopupVisibleChange(visible) {
      setVisible(visible);
      _onPopupVisibleChange && _onPopupVisibleChange(visible);
    }
  }, children || trigger ? /*#__PURE__*/_react["default"].createElement("span", {
    onClick: function onClick() {
      return setVisible(true);
    }
  }, children || trigger) : /*#__PURE__*/_react["default"].createElement("span", {
    className: "persel-selector-field",
    onClick: onChangeVisible
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: "persel-selector-field__text"
  }, (0, _openData.isWechat)() ? jsxDomValues : selectedText || /*#__PURE__*/_react["default"].createElement("span", {
    className: "persel-selector-field__text-holder"
  }, placeholder)), /*#__PURE__*/_react["default"].createElement("span", {
    className: "persel-selector-field__suffix"
  })))));
});

exports["default"] = _default;