"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 _oDesc = _interopRequireDefault(require("./o-desc"));

var _otherInfos = _interopRequireDefault(require("./other-infos"));

require("./base-info.css");

var _person = _interopRequireDefault(require("./person"));

var _toast = _interopRequireDefault(require("../../toast"));

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

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

var _bsGlobal = require("../../../utils/bs-global");

var _dialogConfirm = _interopRequireWildcard(require("../../dialog-confirm"));

var _context = require("../context");

var _auth = require("../../../utils/auth");

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

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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

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

var BaseInfo = function BaseInfo(_ref) {
  var okrId = _ref.okrId;

  var _useContext = (0, _react.useContext)(_context.GeneralDataContext),
      generalOkrClassify = _useContext.generalOkrClassify,
      setGeneralOkrClassify = _useContext.setGeneralOkrClassify,
      generalPrincipalUser = _useContext.generalPrincipalUser,
      setGeneralPrincipalUser = _useContext.setGeneralPrincipalUser,
      generalRoleType = _useContext.generalRoleType,
      setGeneralRoleType = _useContext.setGeneralRoleType,
      generalVisibility = _useContext.generalVisibility,
      setGeneralVisibility = _useContext.setGeneralVisibility;

  var _useContext2 = (0, _react.useContext)(_context.CommonContext),
      okrInfo = _useContext2.okrInfo,
      setOkrInfo = _useContext2.setOkrInfo;

  var originDesc = decodeURI(encodeURI(okrInfo.description)) === 'null' ? '' : decodeURI(encodeURI(okrInfo.description));

  var _useState = (0, _react.useState)(originDesc || ''),
      _useState2 = _slicedToArray(_useState, 2),
      originalDesc = _useState2[0],
      setOriginalDesc = _useState2[1];

  var _useState3 = (0, _react.useState)([]),
      _useState4 = _slicedToArray(_useState3, 2),
      participant = _useState4[0],
      setParticipant = _useState4[1];

  var _useState5 = (0, _react.useState)([]),
      _useState6 = _slicedToArray(_useState5, 2),
      followers = _useState6[0],
      setFollowers = _useState6[1];

  var _useState7 = (0, _react.useState)(new _auth.OAuth({
    principalUser: okrInfo.principalUser,
    createUserId: okrInfo.createUserId
  }).hasAuth() && okrInfo.status === 1),
      _useState8 = _slicedToArray(_useState7, 2),
      canEditAllInfo = _useState8[0],
      setCanEditAllInfo = _useState8[1];

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

  var _useState11 = (0, _react.useState)(new _auth.OAuth({
    principalUser: okrInfo.principalUser,
    createUserId: okrInfo.createUserId
  }).hasAuth()),
      _useState12 = _slicedToArray(_useState11, 2),
      canEditFocusPerson = _useState12[0],
      setCanEditFocusPerson = _useState12[1];

  var _useState13 = (0, _react.useState)(false),
      _useState14 = _slicedToArray(_useState13, 2),
      showDialogConfirm = _useState14[0],
      setShowDialogConfirm = _useState14[1];

  var _useState15 = (0, _react.useState)(0),
      _useState16 = _slicedToArray(_useState15, 2),
      delUserType = _useState16[0],
      setDelUserType = _useState16[1]; // 1: 参与人 2: 关注人


  var _useState17 = (0, _react.useState)(),
      _useState18 = _slicedToArray(_useState17, 2),
      delUser = _useState18[0],
      setDelUser = _useState18[1];

  var isChangePrincipalRef = (0, _react.useRef)(false);
  var oldGeneralRoleTypeRef = (0, _react.useRef)(generalRoleType);
  var loginUser = (0, _bsGlobal.getUserInfo)();
  var setting = (0, _bsGlobal.getOkrAdvancedSetting)().KRSetting;
  (0, _react.useEffect)(function () {
    setOriginalDesc(okrInfo.description);
  }, [okrInfo]);
  var handleChangeDesc = (0, _react.useCallback)(function (desc) {
    if (desc.trim().length > 5000) return;
    (0, _requestApis.saveODesc)(okrInfo.workId, desc).then(function (resp) {
      if (resp.Code === 1) {
        _toast["default"].Success((0, _getLocale.getLocale)('Mod_Successfuloperat'), {
          canClose: false
        });

        setOkrInfo(_objectSpread(_objectSpread({}, okrInfo), {}, {
          description: desc
        }));
      } else {
        _toast["default"].Error('操作失败', {
          canClose: false
        });
      }
    });
  }, [okrInfo.workId]);
  var handleChangePrincipalUser = (0, _react.useCallback)(function (user) {
    (0, _requestApis.transferPrincipal)(okrInfo.workId, user.email, user.id).then(function (resp) {
      if (resp.Code === 1) {
        _toast["default"].Success((0, _getLocale.getLocale)('Mod_Successfuloperat'), {
          canClose: false
        });

        var tempParticipant = _toConsumableArray(participant); // 当前登录的是有权限的人，将负责人转为参与人或者关注人中的一个


        var isParticipantIndex = (0, _util.findUserIndex)(tempParticipant, user.id);
        var isFollowerIndex = (0, _util.findUserIndex)(followers, user.id);

        if (isParticipantIndex !== -1) {
          tempParticipant.splice(isParticipantIndex, 1);
        } // 当前负责人，转交了负责人自动转为参与人


        isParticipantIndex === -1 && tempParticipant.push(_objectSpread(_objectSpread({}, generalPrincipalUser), {}, {
          id: generalPrincipalUser.userId
        }));

        if (isFollowerIndex !== -1) {
          followers.splice(isFollowerIndex, 1);
          setFollowers(_toConsumableArray(followers));
        }

        setParticipant(_toConsumableArray(tempParticipant));
        setGeneralPrincipalUser(_objectSpread(_objectSpread({}, user), {}, {
          id: user.userId
        }));
        isChangePrincipalRef.current = true;

        if (generalPrincipalUser.userId === loginUser.Id && loginUser.Id !== user.id) {
          setGeneralRoleType(user.id === loginUser.Id ? 1 : 0);
        }
      } else {
        _toast["default"].Error(resp.Message, {
          canClose: false
        });
      }
    });
  }, [participant, followers, generalPrincipalUser]);
  var handleChangeClassify = (0, _react.useCallback)(function (classify) {
    (0, _requestApis.updateOClassify)(classify, okrInfo.workId).then(function (resp) {
      if (resp.Code === 1) {
        _toast["default"].Success((0, _getLocale.getLocale)('Mod_Successfuloperat'), {
          canClose: false
        });

        setGeneralOkrClassify(classify);
      } else {
        _toast["default"].Error(resp.Message, {
          canClose: false
        });
      }
    });
  }, []);
  var handleVisiableLimitChanged = (0, _react.useCallback)(function (visiableValue, data) {
    var areaUserIds = data && data.users && data.users.map(function (user) {
      return user.userId;
    });
    var areaOrgIds = data && data.departments && data.departments.map(function (department) {
      return department.id;
    });
    var areaGroupIds = data && data.groups && data.groups.map(function (group) {
      return group.id;
    });
    (0, _requestApis.updateVisibility)(okrInfo.workId, visiableValue, areaUserIds, areaOrgIds, areaGroupIds).then(function (resp) {
      if (resp.Code === 1) {
        _toast["default"].Success((0, _getLocale.getLocale)('Mod_Successfuloperat'), {
          canClose: false
        });

        setGeneralVisibility({
          visibility: visiableValue,
          visibilityScope: data
        });
      }
    });
  }, [okrInfo]);
  var handleAddUser = (0, _react.useCallback)(function (data, type) {
    var users = data.users,
        departments = data.departments,
        groups = data.groups;
    var reqData = [];
    users.forEach(function (user) {
      reqData.push({
        Name: user.name,
        Id: user.userId,
        Email: user.email
      });
    });
    departments.forEach(function (department) {
      reqData.push({
        Id: department.id,
        Email: "".concat(department.name, ":").concat(department.id, ":dep_members")
      });
    });
    groups.forEach(function (group) {
      reqData.push({
        Id: group.id,
        Email: "".concat(group.name, ":").concat(group.id, ":group_members_")
      });
    });
    (0, _requestApis.addUserRelation)(okrInfo.workId, type === 'participant' ? 2 : 3, reqData).then(function (resp) {
      if (resp.Code === 1) {
        if (data.userId === loginUser.Id) {
          setGeneralRoleType(type === "participant" ? 2 : 3);
        } else {
          setGeneralRoleType(generalRoleType);
        }

        if (type === 'participant') {
          setParticipant([].concat(_toConsumableArray(participant), _toConsumableArray(resp.Data.map(function (item) {
            return {
              name: item.name,
              id: item.userId,
              avatar: {
                medium: item.avatar.Medium,
                small: item.avatar.Small,
                hasAvatar: item.avatar.HasAvatar,
                color: item.avatar.Color
              }
            };
          }))));
        } else {
          setFollowers([].concat(_toConsumableArray(followers), _toConsumableArray(resp.Data.map(function (item) {
            return {
              name: item.name,
              id: item.userId,
              avatar: {
                medium: item.avatar.Medium,
                small: item.avatar.Small,
                hasAvatar: item.avatar.HasAvatar,
                color: item.avatar.Color
              }
            };
          }))));
        }
      } else {
        // 不这样添加会导致添加已添加的相关人员时选人组件不会清空上次的选中
        if (type === 'participant') {
          setParticipant(_toConsumableArray(participant));
        } else {
          setFollowers(_toConsumableArray(followers));
        }

        _toast["default"].Error(resp.Message, {
          canClose: false
        });
      }
    })["catch"](function () {
      _toast["default"].Error('网络异常', {
        canClose: false
      });
    });
  }, [participant, followers, canEditPerson]);

  var handleDelParticipantUser = function handleDelParticipantUser(data) {
    setDelUserType(1);
    setShowDialogConfirm(true);
    setDelUser(data);
  };

  var handleDelFollower = function handleDelFollower(data) {
    setDelUserType(2);
    setShowDialogConfirm(true);
    setDelUser(data);
  };

  var cancelDelPerson = (0, _react.useCallback)(function () {
    setShowDialogConfirm(false);
  }, []);
  var ensureDelPerson = (0, _react.useCallback)(function () {
    setShowDialogConfirm(false);

    if (isChangePrincipalRef.current) {
      isChangePrincipalRef.current = false;
      return;
    }

    var userIndex = (0, _util.findUserIndex)(delUserType === 1 ? participant : followers, delUser.id || delUser.userId);
    (0, _requestApis.deleteUser)(delUser.id, okrInfo.workId, delUserType === 1 ? 2 : 3).then(function (resp) {
      if (resp.Code === 1) {
        _toast["default"].Success((0, _getLocale.getLocale)('Pro_detail_Deletsuccess'), {
          canClose: false
        });

        setGeneralRoleType(delUser.id === loginUser.Id ? 0 : generalRoleType);

        if (delUserType === 1) {
          participant.splice(userIndex, 1);
          setParticipant(_toConsumableArray(participant));
        } else {
          followers.splice(userIndex, 1);
          setFollowers(_toConsumableArray(followers));
        }
      } else {
        _toast["default"].Error(resp.Message);
      }
    })["finally"](function () {
      setShowDialogConfirm(false);
    });
  }, [delUserType, delUser, participant, followers]);
  (0, _react.useEffect)(function () {
    (0, _requestApis.getOkrUsers)(okrInfo.workId).then(function (resp) {
      if (resp.Code === 1) {
        var _data$;

        var data = resp.Data;
        setGeneralPrincipalUser((0, _util.formatAvatarInfo)(data[0].users)[0]);
        setParticipant((0, _util.formatAvatarInfo)(data[1].users));
        setFollowers((0, _util.formatAvatarInfo)(((_data$ = data[2]) === null || _data$ === void 0 ? void 0 : _data$.users) || []));
      }
    });
  }, []);
  (0, _react.useEffect)(function () {
    setCanEditAllInfo(new _auth.OAuth({
      principalUser: generalPrincipalUser,
      createUserId: okrInfo.createUserId
    }).hasAuth() && okrInfo.status === 1);
  }, [generalPrincipalUser, okrInfo]); // 判断是否有权限和是否上面可编辑

  (0, _react.useEffect)(function () {
    var inParticipant = (0, _util.findUser)(participant, loginUser.Id);
    var canEditParticipantAndFollowers = canEditAllInfo || inParticipant;
    setCanEditPerson(!!canEditParticipantAndFollowers);
  }, [participant, canEditAllInfo]);
  (0, _react.useEffect)(function () {
    if (isChangePrincipalRef.current || oldGeneralRoleTypeRef.current === generalRoleType) {
      isChangePrincipalRef.current = false;
      oldGeneralRoleTypeRef.current = generalRoleType;
      return;
    }

    if (generalRoleType === 0) {
      var isParticipantIndex = (0, _util.findUserIndex)(participant, loginUser.Id);
      var isFollowerIndex = (0, _util.findUserIndex)(followers, loginUser.Id);

      if (isParticipantIndex !== -1) {
        participant.splice(isParticipantIndex, 1);
        setParticipant(_toConsumableArray(participant));
      } else if (isFollowerIndex !== -1) {
        followers.splice(isFollowerIndex, 1);
        setFollowers(_toConsumableArray(followers));
      }
    } else if (generalRoleType === 3) {
      var follower = {
        name: loginUser === null || loginUser === void 0 ? void 0 : loginUser.Name,
        id: loginUser === null || loginUser === void 0 ? void 0 : loginUser.Id,
        email: loginUser === null || loginUser === void 0 ? void 0 : loginUser.Email,
        avatar: {
          small: loginUser === null || loginUser === void 0 ? void 0 : loginUser.UserAvatar.Small,
          medium: loginUser === null || loginUser === void 0 ? void 0 : loginUser.UserAvatar.Medium,
          hasAvatar: loginUser === null || loginUser === void 0 ? void 0 : loginUser.UserAvatar.HasAvatar,
          color: loginUser === null || loginUser === void 0 ? void 0 : loginUser.UserAvatar.Color
        }
      };
      setFollowers([].concat(_toConsumableArray(followers), [follower]));
    }
  }, [generalRoleType, participant, followers]);
  var renderDialogConfirm = (0, _react.useMemo)(function () {
    return /*#__PURE__*/_react["default"].createElement(_dialogConfirm["default"], {
      zIndex: 1200,
      visible: showDialogConfirm,
      type: "warning"
    }, /*#__PURE__*/_react["default"].createElement("span", {
      type: "title"
    }, delUserType === 1 ? (0, _getLocale.getLocale)('OKR_MyO_Err_Delepar') : (0, _getLocale.getLocale)('OKR_MyO_Err_Delefol'), "\uFF1F"), /*#__PURE__*/_react["default"].createElement(_dialogConfirm.CancelButton, {
      type: "button",
      onClick: cancelDelPerson
    }, (0, _getLocale.getLocale)('Mod_Cancel')), /*#__PURE__*/_react["default"].createElement(_dialogConfirm.WarningButton, {
      type: "button",
      onClick: ensureDelPerson
    }, (0, _getLocale.getLocale)('Mod_Delete')));
  }, [showDialogConfirm, delUserType]);
  return /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("div", {
    className: "base-info__infos-wrapper"
  }, setting.ShowWorkDescription && /*#__PURE__*/_react["default"].createElement(_oDesc["default"], {
    onChangeDesc: handleChangeDesc,
    data: okrInfo,
    originalDesc: originalDesc,
    canEdit: canEditAllInfo
  }), /*#__PURE__*/_react["default"].createElement(_otherInfos["default"], {
    classifyValue: generalOkrClassify,
    setClassifyValue: handleChangeClassify,
    principalUser: generalPrincipalUser,
    setPrincipalUser: handleChangePrincipalUser,
    visibility: generalVisibility.visibility,
    onChangeVisiableLimit: handleVisiableLimitChanged,
    visiableLimit: generalVisibility.visibilityScope,
    canEdit: canEditAllInfo,
    okrId: okrId
  })), !canEditPerson && !okrInfo.isParticipant && !canEditAllInfo && participant.length === 0 && followers.length === 0 ? null : /*#__PURE__*/_react["default"].createElement("div", {
    className: "base-info__divider"
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "base-info__participant-followers-wrapper"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "base-info__person-block"
  }, !canEditPerson && !canEditAllInfo && !okrInfo.isParticipant && participant.length === 0 ? null : /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("span", {
    className: "base-info__person-block-title"
  }, (0, _getLocale.getLocale)('Mod_Participants')), /*#__PURE__*/_react["default"].createElement(_person["default"], {
    users: participant,
    canEdit: canEditPerson,
    onAddUser: handleAddUser,
    onDelUser: handleDelParticipantUser
  }))), (setting === null || setting === void 0 ? void 0 : setting.TargetFollowers) && /*#__PURE__*/_react["default"].createElement("div", {
    className: "base-info__person-block"
  }, !canEditFocusPerson && !canEditAllInfo && followers.length === 0 ? null : /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("span", {
    className: "base-info__person-block-title"
  }, (0, _getLocale.getLocale)('Mod_Followers')), /*#__PURE__*/_react["default"].createElement(_person["default"], {
    type: "followers",
    users: followers,
    canEdit: canEditFocusPerson,
    onAddUser: handleAddUser,
    onDelUser: handleDelFollower
  })))), renderDialogConfirm);
};

var _default = BaseInfo;
exports["default"] = _default;