"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 _userSelector = _interopRequireDefault(require("../../user-selector"));

var _drawer = _interopRequireDefault(require("../../drawer"));

var _actions = require("./actions");

var _confirm = _interopRequireDefault(require("./confirm"));

var _wechatBtn = _interopRequireDefault(require("../../wechat-btn"));

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

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

var _okrShare = _interopRequireDefault(require("../../okr-share"));

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

var _constant = require("./constant");

var _deleteConfirm = _interopRequireDefault(require("./delete-confirm/delete-confirm"));

var _drawerManager = _interopRequireDefault(require("../../drawer-manager"));

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

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

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 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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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 StrRreg = /@\$(userName|departmentName)\=(.+?)\$(\s|$)/g;

function OkrDetailHeader(_ref) {
  var _window$BSGlobal$logi;

  var detailInfo = _ref.detailInfo;

  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      shareVisible = _useState2[0],
      setShareVisible = _useState2[1];

  var userSelectRef = (0, _react.useRef)();
  var deletePopRef = (0, _react.useRef)();

  var _useState3 = (0, _react.useState)([]),
      _useState4 = _slicedToArray(_useState3, 2),
      krs = _useState4[0],
      setKrs = _useState4[1]; // @ts-ignore


  var loginUserId = (_window$BSGlobal$logi = window.BSGlobal.loginUserInfo) === null || _window$BSGlobal$logi === void 0 ? void 0 : _window$BSGlobal$logi.Id;
  var context = (0, _react.useContext)(_context6.GeneralDataContext);
  var commonContext = (0, _react.useContext)(_context6.CommonContext);
  var approvalSetting = commonContext.approvalSetting,
      okrInfo = commonContext.okrInfo;
  var approveStatusColor = (0, _constant.ApproveStatusColor)(okrInfo.applyState);
  var changVisiblity = (0, _react.useCallback)( /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(workId, visibility) {
      var visibilityScope,
          _args = arguments;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              visibilityScope = _args.length > 2 && _args[2] !== undefined ? _args[2] : {};
              _context.next = 3;
              return (0, _requestApis.updateOkrVisibility)(_objectSpread({
                workId: workId,
                visibility: visibility
              }, {
                areaGroupIds: (visibilityScope.groups || []).map(function (g) {
                  return g.id;
                }),
                areaOrgIds: (visibilityScope.departments || []).map(function (g) {
                  return g.id;
                }),
                areaUserIds: (visibilityScope.users || []).map(function (g) {
                  return g.userId;
                })
              }));

            case 3:
              _toast["default"].Success((0, _getLocale.getLocale)('Mod_Successfuloperat'));

              context.setGeneralVisibility({
                visibility: visibility,
                visibilityScope: visibilityScope
              });

            case 5:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function (_x, _x2) {
      return _ref2.apply(this, arguments);
    };
  }(), [detailInfo]);
  var closeShareModal = (0, _react.useCallback)(function () {
    setShareVisible(false);
  }, []);

  var handleDeleteOkr = function handleDeleteOkr(selected) {
    (0, _requestApis.workDelete)({
      deleteType: selected,
      workId: detailInfo.workId
    }).then(function (resp) {
      if (resp.Code === 1) {
        _toast["default"].Success((0, _getLocale.getLocale)('Mod_Successfuloperat'));

        setTimeout(function () {
          commonContext.refreshAll();
        }, 500);
      } else {
        _toast["default"].Error(resp.Message);
      }
    });
  };

  var actions = (0, _react.useMemo)(function () {
    if (!detailInfo) {
      return [];
    }

    return (0, _actions.getOkrHeadActions)({
      roleType: context.generalRoleType,
      principalUser: context.generalPrincipalUser,
      visibility: context.generalVisibility.visibility,
      detailInfo: detailInfo,
      openShareModal: function () {
        var _openShareModal = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
          var krss;
          return regeneratorRuntime.wrap(function _callee2$(_context2) {
            while (1) {
              switch (_context2.prev = _context2.next) {
                case 0:
                  _context2.next = 2;
                  return (0, _requestApis.getKrs)({
                    okrId: detailInfo.workId
                  });

                case 2:
                  krss = _context2.sent;
                  setKrs(krss);
                  setShareVisible(true);

                case 5:
                case "end":
                  return _context2.stop();
              }
            }
          }, _callee2);
        }));

        function openShareModal() {
          return _openShareModal.apply(this, arguments);
        }

        return openShareModal;
      }(),
      changeVisiblilty: function changeVisiblilty(visibility) {
        if (visibility === 4) {
          if (userSelectRef.current) {
            userSelectRef.current.open();
          }

          return;
        }

        changVisiblity(detailInfo.workId, visibility);
      },
      onDeleteOkr: function onDeleteOkr(e) {
        deletePopRef.current.show();
      },
      onCopyOkr: function onCopyOkr() {
        // @ts-ignore
        window.openCopyOkrModal({
          okrId: detailInfo.workId,
          okrType: detailInfo.okrType
        });
      },
      onChangeOkrFollow: function () {
        var _onChangeOkrFollow = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(follow) {
          var res;
          return regeneratorRuntime.wrap(function _callee3$(_context3) {
            while (1) {
              switch (_context3.prev = _context3.next) {
                case 0:
                  _context3.next = 2;
                  return (0, _confirm["default"])(follow ? (0, _getLocale.getLocale)('OKR_MyO_Err_Focuson') : (0, _getLocale.getLocale)('OKR_MyO_Err_Unfollow'), follow ? (0, _getLocale.getLocale)('OKR_MyO_Err_Payatten') : (0, _getLocale.getLocale)('OKR_MyO_Err_Progress'));

                case 2:
                  res = _context3.sent;

                  if (!res) {
                    _context3.next = 14;
                    break;
                  }

                  if (!follow) {
                    _context3.next = 9;
                    break;
                  }

                  _context3.next = 7;
                  return (0, _requestApis.addUser)(loginUserId, detailInfo.workId, 3);

                case 7:
                  _context3.next = 11;
                  break;

                case 9:
                  _context3.next = 11;
                  return (0, _requestApis.deleteUser)(loginUserId, detailInfo.workId, 3);

                case 11:
                  context.setGeneralRoleType(follow ? 3 : 0); // 关注

                  _toast["default"].Success((0, _getLocale.getLocale)('Mod_Successfuloperat'));

                  if (!follow) {
                    commonContext.refreshAll();
                  }

                case 14:
                case "end":
                  return _context3.stop();
              }
            }
          }, _callee3);
        }));

        function onChangeOkrFollow(_x3) {
          return _onChangeOkrFollow.apply(this, arguments);
        }

        return onChangeOkrFollow;
      }(),
      onFinishOrReOpen: function () {
        var _onFinishOrReOpen = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(isFinish) {
          var res;
          return regeneratorRuntime.wrap(function _callee4$(_context4) {
            while (1) {
              switch (_context4.prev = _context4.next) {
                case 0:
                  _context4.next = 2;
                  return (0, _confirm["default"])(isFinish ? (0, _getLocale.getLocale)('OKR_MyO_Areycloseobjective') : (0, _getLocale.getLocale)('OKR_MyO_Err_Restart'));

                case 2:
                  res = _context4.sent;

                  if (!res) {
                    _context4.next = 13;
                    break;
                  }

                  if (!isFinish) {
                    _context4.next = 9;
                    break;
                  }

                  _context4.next = 7;
                  return (0, _requestApis.close)(detailInfo.workId);

                case 7:
                  _context4.next = 11;
                  break;

                case 9:
                  _context4.next = 11;
                  return (0, _requestApis.start)(detailInfo.workId);

                case 11:
                  commonContext.refreshAll(); // 刷新

                  _toast["default"].Success((0, _getLocale.getLocale)('Mod_Successfuloperat'));

                case 13:
                case "end":
                  return _context4.stop();
              }
            }
          }, _callee4);
        }));

        function onFinishOrReOpen(_x4) {
          return _onFinishOrReOpen.apply(this, arguments);
        }

        return onFinishOrReOpen;
      }(),
      onQuit: function () {
        var _onQuit = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() {
          var res;
          return regeneratorRuntime.wrap(function _callee5$(_context5) {
            while (1) {
              switch (_context5.prev = _context5.next) {
                case 0:
                  _context5.next = 2;
                  return (0, _confirm["default"])((0, _getLocale.getLocale)('OKR_MyO_Err_Quit'), (0, _getLocale.getLocale)('OKR_MyO_Err_Inchargec'));

                case 2:
                  res = _context5.sent;

                  if (!res) {
                    _context5.next = 8;
                    break;
                  }

                  _context5.next = 6;
                  return (0, _requestApis.deleteUser)(loginUserId, detailInfo.workId, 2);

                case 6:
                  // context.setGeneralRoleType(0)
                  commonContext.refreshAll(); // 刷新

                  _toast["default"].Success((0, _getLocale.getLocale)('Mod_Successfuloperat'));

                case 8:
                case "end":
                  return _context5.stop();
              }
            }
          }, _callee5);
        }));

        function onQuit() {
          return _onQuit.apply(this, arguments);
        }

        return onQuit;
      }()
    });
  }, [detailInfo, context.generalRoleType, context.generalPrincipalUser, context.generalVisibility.visibility]);
  var parent = null;

  if (context.generalParent) {
    if (context.generalParent.parentKr) {
      parent = {
        type: 'kr',
        id: context.generalParent.parentKr.mileStoneId,
        name: context.generalParent.parentKr.mileStoneName
      };
    } else if (context.generalParent.parentOkr) {
      parent = {
        type: 'okr',
        id: context.generalParent.parentOkr.workId,
        name: context.generalParent.parentOkr.workName
      };
    }
  }

  return /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_drawer["default"].Header, {
    actions: actions,
    approvalSetting: approvalSetting,
    detailInfo: detailInfo,
    actionComponent: /*#__PURE__*/_react["default"].createElement(_wechatBtn["default"], {
      id: detailInfo.workId,
      objType: 62,
      name: detailInfo.workName.replace(StrRreg, ''),
      principalUser: detailInfo.principalUser
    }),
    content: parent && /*#__PURE__*/_react["default"].createElement("span", {
      className: "okr-detail-head-parent"
    }, /*#__PURE__*/_react["default"].createElement("i", {
      className: "tu-icon-liebiao-duiqinubiao"
    }), /*#__PURE__*/_react["default"].createElement("span", {
      onClick: function onClick() {
        return parent.type === 'okr' ? _drawerManager["default"].open('okrDetail', {
          okrId: parent.id
        }) : _drawerManager["default"].open('krDetail', {
          krId: parent.id
        });
      }
    }, /*#__PURE__*/_react["default"].createElement("span", null, parent.type === 'okr' ? 'O ' : 'KR '), (0, _openData.parseString)(parent.name))),
    onlyShowContent: /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, approveStatusColor ? /*#__PURE__*/_react["default"].createElement("div", {
      className: "okr-detail-header-status",
      style: {
        color: approveStatusColor.color,
        backgroundColor: approveStatusColor.bgColor
      }
    }, (0, _constant.getApproveStatusTextMap)(okrInfo.applyState)) : null, Number(detailInfo.status) === 2 && /*#__PURE__*/_react["default"].createElement("span", {
      className: "okr-drawer-header__over-tag"
    }, (0, _getLocale.getLocale)('OKR_MyO_Butt_Hasended')))
  }), /*#__PURE__*/_react["default"].createElement(_okrShare["default"], {
    visible: shareVisible,
    onClose: closeShareModal,
    data: {
      okrName: detailInfo.workName,
      okrId: detailInfo.workId,
      krs: krs.map(function (kr) {
        return kr.mileStoneName;
      }),
      user: _objectSpread(_objectSpread({}, detailInfo.principalUser), {}, {
        avatar: {
          color: detailInfo.principalUser.avatar.color,
          src: detailInfo.principalUser.avatar.original
        }
      })
    },
    zIndex: 2400
  }), /*#__PURE__*/_react["default"].createElement(_deleteConfirm["default"], {
    ref: deletePopRef,
    okrInfo: okrInfo,
    approvalSetting: approvalSetting,
    onConfirm: handleDeleteOkr
  }), /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      textAlign: 'right',
      height: 0
    }
  }, /*#__PURE__*/_react["default"].createElement(_userSelector["default"], {
    ref: userSelectRef // @ts-ignore
    ,
    multiple: true,
    onOk: function onOk(data) {
      changVisiblity(detailInfo.workId, 4, data);
    },
    position: "bottomRight",
    selectNodes: context.generalVisibility.visibilityScope || {},
    trigger: /*#__PURE__*/_react["default"].createElement("div", {
      style: {
        visibility: 'hidden',
        zIndex: -1,
        display: 'inline-block',
        height: 0
      }
    }, "empty select")
  })));
}

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