"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 _richEditor = require("@titaui/rich-editor");

var _uuid = _interopRequireDefault(require("uuid"));

var _titaUi = require("tita-ui");

var _scrollbar = _interopRequireDefault(require("../scrollbar"));

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

var _roundWeight = require("../../utils/roundWeight");

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

var _krDatas = _interopRequireDefault(require("./kr-items/krDatas"));

var _style = require("./style");

var _oNewName = _interopRequireDefault(require("./fields/o-new-name"));

var _dateCycle = _interopRequireDefault(require("./fields/date-cycle"));

var _okrVisibility = _interopRequireDefault(require("./fields/okr-visibility"));

var _okrType = _interopRequireDefault(require("./fields/okr-type"));

var _okrClassify = _interopRequireDefault(require("./fields/okr-classify"));

var _okrParent = _interopRequireDefault(require("./fields/okr-parent"));

var _okrCase = _interopRequireDefault(require("./fields/okr-case"));

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

var _okrCreateSuggest = _interopRequireWildcard(require("./fields/okr-create-suggest"));

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

var _getCreateOkrSurpassPercent = _interopRequireDefault(require("./utils/getCreateOkrSurpassPercent"));

var _createSuccessCmpWrapper = _interopRequireDefault(require("./createSuccessCmpWrapper"));

var _createSuccessCmp = _interopRequireDefault(require("./createSuccessCmp"));

var _helpers = require("../../utils/helpers");

var _requestApi = require("./request-api");

var _teachOkr = _interopRequireDefault(require("./img/teach-okr.svg"));

var _hand = _interopRequireDefault(require("./img/hand.svg"));

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

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 _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 _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 initOCheckResult = function initOCheckResult() {
  return (0, _constant.OCheckTarget)().map(function (item) {
    return {
      text: item,
      result: _okrCreateSuggest.EOkrCreateSuggestResultType.normal
    };
  });
};

var DefaultOkrNameData = {
  mentionUsers: [],
  pureText: '',
  pureTextExcludeAt: '',
  richText: undefined
};

function CreateOkrModal(_ref, ref) {
  var _BSGlobal$loginUserIn;

  var initCycle = _ref.initCycle,
      userInfo = _ref.userInfo,
      onSuccess = _ref.onSuccess,
      _ref$isHiddenCreatedC = _ref.isHiddenCreatedCard,
      isHiddenCreatedCard = _ref$isHiddenCreatedC === void 0 ? false : _ref$isHiddenCreatedC,
      _ref$handleCreatedClo = _ref.handleCreatedClose,
      handleCreatedClose = _ref$handleCreatedClo === void 0 ? function () {} : _ref$handleCreatedClo,
      _ref$visible = _ref.visible,
      visible = _ref$visible === void 0 ? false : _ref$visible,
      _ref$onClose = _ref.onClose,
      onClose = _ref$onClose === void 0 ? function () {} : _ref$onClose,
      _ref$isFromAssess = _ref.isFromAssess,
      isFromAssess = _ref$isFromAssess === void 0 ? false : _ref$isFromAssess,
      _ref$asyncOpenBookDem = _ref.asyncOpenBookDemoFun,
      asyncOpenBookDemoFun = _ref$asyncOpenBookDem === void 0 ? function () {} : _ref$asyncOpenBookDem;

  var _useState = (0, _react.useState)('initialization'),
      _useState2 = _slicedToArray(_useState, 2),
      richEditorStatus = _useState2[0],
      setRichEditorStatus = _useState2[1];

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


  var userId = (_BSGlobal$loginUserIn = BSGlobal.loginUserInfo) === null || _BSGlobal$loginUserIn === void 0 ? void 0 : _BSGlobal$loginUserIn.Id;
  var setting = (0, _bsGlobal.getBSGlobal)('OkrAdvancedSetting').KRSetting;
  var openOkrType = setting.OkrTypeSetting;
  var openClassify = setting.OkrClassify;
  var openKrWeight = setting.KrWeight;

  var _ref2 = userInfo || (0, _bsGlobal.getUserInfo)(),
      Name = _ref2.Name,
      Id = _ref2.Id,
      UserAvatar = _ref2.UserAvatar;

  var _useState5 = (0, _react.useState)(DefaultOkrNameData),
      _useState6 = _slicedToArray(_useState5, 2),
      okrNameData = _useState6[0],
      setOkrNameData = _useState6[1]; // 目标名称


  var _useState7 = (0, _react.useState)({
    name: Name,
    id: Id,
    avatar: UserAvatar
  }),
      _useState8 = _slicedToArray(_useState7, 2),
      user = _useState8[0],
      setUser = _useState8[1]; // 负责人


  var _useState9 = (0, _react.useState)(false),
      _useState10 = _slicedToArray(_useState9, 2),
      isCustomWeight = _useState10[0],
      setIsCustomWeight = _useState10[1]; // 是否自定义权重


  var _useState11 = (0, _react.useState)({
    departmentId: 0,
    departmentName: ''
  }),
      _useState12 = _slicedToArray(_useState11, 2),
      dept = _useState12[0],
      setDept = _useState12[1]; // 部门信息 用于目标类型为部门时


  var _useState13 = (0, _react.useState)({
    groupId: 0,
    groupName: ''
  }),
      _useState14 = _slicedToArray(_useState13, 2),
      team = _useState14[0],
      setTeam = _useState14[1]; // 团队信息 用于目标类型为团队时


  var _useState15 = (0, _react.useState)({
    typeName: (0, _getLocale.getLocale)('OKR_MyO_Pop_Individual'),
    typeId: 1
  }),
      _useState16 = _slicedToArray(_useState15, 2),
      type = _useState16[0],
      setType = _useState16[1]; // 目标类型


  var _useState17 = (0, _react.useState)(initCycle),
      _useState18 = _slicedToArray(_useState17, 2),
      cycle = _useState18[0],
      setCycle = _useState18[1]; // 目标周期信息


  var _useState19 = (0, _react.useState)(),
      _useState20 = _slicedToArray(_useState19, 2),
      okrClassify = _useState20[0],
      setOkrClassify = _useState20[1]; // 目标类别


  var _useState21 = (0, _react.useState)(function () {
    if (window.BSGlobal.tenantInfo.isOpenInfo) {
      return 1;
    } else {
      return 2;
    }
  }),
      _useState22 = _slicedToArray(_useState21, 2),
      visibility = _useState22[0],
      setVisibility = _useState22[1]; // 可见性


  var _useState23 = (0, _react.useState)({}),
      _useState24 = _slicedToArray(_useState23, 2),
      visiableLimit = _useState24[0],
      setVisiableLimit = _useState24[1]; // 可见性指定范围


  var _useState25 = (0, _react.useState)([{
    // kr信息
    uuid: _uuid["default"].v1(),
    principalId: Id,
    principalName: Name,
    userAvatar: UserAvatar,
    krWeight: 100,
    mileStoneName: '',
    mileStoneNamePureTextExcludeAt: '',
    mileStoneNameRichText: undefined,
    aiteUsers: [],
    confidenceIndex: 5
  }]),
      _useState26 = _slicedToArray(_useState25, 2),
      krDatas = _useState26[0],
      setKrDatas = _useState26[1];

  var _useState27 = (0, _react.useState)({
    // 对其目标
    parentWorkId: 0,
    parentWorkName: '',
    parentType: 0,
    parentKrId: 0
  }),
      _useState28 = _slicedToArray(_useState27, 2),
      parent = _useState28[0],
      setParent = _useState28[1];

  var _useState29 = (0, _react.useState)(false),
      _useState30 = _slicedToArray(_useState29, 2),
      oNameIsInput = _useState30[0],
      setONameIsInput = _useState30[1];

  var _useState31 = (0, _react.useState)(false),
      _useState32 = _slicedToArray(_useState31, 2),
      krIsInput = _useState32[0],
      setKrIsInput = _useState32[1];

  var _useState33 = (0, _react.useState)(initOCheckResult()),
      _useState34 = _slicedToArray(_useState33, 2),
      oNameCheckResult = _useState34[0],
      setONameCheckResult = _useState34[1];

  var _useState35 = (0, _react.useState)({
    finalResult: _okrCreateSuggest.EOkrCreateSuggestResultType.normal,
    friendlyResult: []
  }),
      _useState36 = _slicedToArray(_useState35, 2),
      krsCheckResult = _useState36[0],
      setKrsCheckResult = _useState36[1];

  var _useState37 = (0, _react.useState)(false),
      _useState38 = _slicedToArray(_useState37, 2),
      customCloseOSuggest = _useState38[0],
      setCustomCloseOSuggest = _useState38[1]; // 用户点击收起后不再自动弹出


  var _useState39 = (0, _react.useState)(false),
      _useState40 = _slicedToArray(_useState39, 2),
      customCloseKrSuggest = _useState40[0],
      setCustomCloseKrSuggest = _useState40[1];

  var _useState41 = (0, _react.useState)(),
      _useState42 = _slicedToArray(_useState41, 2),
      createdSuccessInfo = _useState42[0],
      setCreatedSuccessInfo = _useState42[1];

  var _useState43 = (0, _react.useState)(false),
      _useState44 = _slicedToArray(_useState43, 2),
      showCreatedSuccessInfo = _useState44[0],
      setShowCreatedSuccessInfo = _useState44[1];

  var _useState45 = (0, _react.useState)(Math.floor(Math.random() * 6)),
      _useState46 = _slicedToArray(_useState45, 2),
      tipIndex = _useState46[0],
      setTipIndex = _useState46[1];

  var _useState47 = (0, _react.useState)(''),
      _useState48 = _slicedToArray(_useState47, 2),
      userAvatarBase64Url = _useState48[0],
      setUserAvatarBase64Url = _useState48[1];

  var _useState49 = (0, _react.useState)(false),
      _useState50 = _slicedToArray(_useState49, 2),
      krIsValidate = _useState50[0],
      setKrIsValidate = _useState50[1];

  var _useState51 = (0, _react.useState)(false),
      _useState52 = _slicedToArray(_useState51, 2),
      isApplyTpl = _useState52[0],
      setIsApplyTpl = _useState52[1];

  var _useState53 = (0, _react.useState)(false),
      _useState54 = _slicedToArray(_useState53, 2),
      isInputContent = _useState54[0],
      setIsInputContent = _useState54[1];

  var wrapperRef = (0, _react.useRef)();
  var modalRef = (0, _react.useRef)();
  var oInputFoucsRef = (0, _react.useRef)(false);
  var krInputFoucsRef = (0, _react.useRef)(false);
  var downloadDomRef = (0, _react.useRef)(document.createElement('div'));
  var newOkrDataRef = (0, _react.useRef)(); // kr权重总计

  var total = 0;
  krDatas.forEach(function (kr) {
    return total += Number(kr.krWeight);
  }); // 权重未自定义过或总计为100为合法权重

  var krWeightValid = !isCustomWeight || Number(total.toFixed(1)) == 100 || krDatas.length == 0 || !openKrWeight;
  var allKrHasName = krDatas.filter(function (kr) {
    return !kr.mileStoneName.trim().length;
  }).length == 0;
  var showCreateOkrModal = (0, _react.useCallback)(function () {
    setVisible(true);
  }, []);
  var hideCreateOkrModal = (0, _react.useCallback)(function () {
    onClose && onClose();
    setVisible(false);
    asyncOpenBookDemoFun && asyncOpenBookDemoFun();
  }, []);
  (0, _react.useEffect)(function () {
    setVisible(visible);
  }, [visible]);
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      setCase: function setCase(data) {
        var name = data.name,
            subelements = data.subelements;
        setOkrNameData({
          mentionUsers: [],
          pureText: name,
          pureTextExcludeAt: name,
          richText: (0, _richEditor.TitaRichEditorInitTextState)(name)
        });
        setKrDatas(subelements.map(function (s) {
          return {
            uuid: _uuid["default"].v1(),
            principalId: Id,
            principalName: Name,
            userAvatar: UserAvatar,
            krWeight: (0, _roundWeight.RoundWeight)(100 / subelements.length),
            mileStoneName: s.name,
            mileStoneNamePureTextExcludeAt: '',
            mileStoneNameRichText: (0, _richEditor.TitaRichEditorInitTextState)(s.name),
            aiteUsers: [],
            confidenceIndex: 5
          };
        }));
        setIsCustomWeight(false);
      },
      setData: function setData(data) {
        setOkrNameData({
          mentionUsers: [],
          pureText: data.okrName,
          pureTextExcludeAt: data.okrName,
          richText: (0, _richEditor.TitaRichEditorInitTextState)(data.okrName)
        });
        setUser(data.user);
      },
      show: showCreateOkrModal,
      hide: hideCreateOkrModal
    };
  });
  var handleOnSuccess = (0, _react.useCallback)(function () {
    var data = newOkrDataRef.current;
    data.userAvatarBase64Url = userAvatarBase64Url;
    setCreatedSuccessInfo(data);

    if (!localStorage.getItem("dontShowValue".concat(userId)) && !isHiddenCreatedCard && !isApplyTpl) {
      setShowCreatedSuccessInfo(true);
      setTipIndex(Math.floor(Math.random() * 6));
    } else {
      _toast["default"].Success((0, _getLocale.getLocale)('OKR_Db_Success'), {
        duration: 3000
      });

      onSuccess && onSuccess(data);
    }
  }, [userAvatarBase64Url, isApplyTpl]);

  var formatVisiableLimit = function formatVisiableLimit() {
    var _visiableLimit$users = visiableLimit.users,
        users = _visiableLimit$users === void 0 ? [] : _visiableLimit$users,
        _visiableLimit$depart = visiableLimit.departments,
        departments = _visiableLimit$depart === void 0 ? [] : _visiableLimit$depart,
        _visiableLimit$groups = visiableLimit.groups,
        groups = _visiableLimit$groups === void 0 ? [] : _visiableLimit$groups;
    var areaUserIds = (users || []).reduce(function (res, cur) {
      return [].concat(_toConsumableArray(res), [cur.userId]);
    }, []);
    var areaOrgIds = (departments || []).reduce(function (res, cur) {
      return [].concat(_toConsumableArray(res), [cur.id]);
    }, []);
    var areaGroupIds = (groups || []).reduce(function (res, cur) {
      return [].concat(_toConsumableArray(res), [cur.id]);
    }, []);
    return {
      areaUserIds: areaUserIds,
      areaOrgIds: areaOrgIds,
      areaGroupIds: areaGroupIds
    };
  }; // 表单保存功能


  var onModalOkHandler = /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var mentionUsers, pureText, pureTextExcludeAt, richText, orkNameLengthValidate, visibilityArea, formData, data, krNum, krTotalLength, krAvarageLength, krMeasurableLength, oHasVtWords, callData, workId;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              mentionUsers = okrNameData.mentionUsers, pureText = okrNameData.pureText, pureTextExcludeAt = okrNameData.pureTextExcludeAt, richText = okrNameData.richText;

              if (pureText) {
                _context.next = 4;
                break;
              }

              _toast["default"].Error((0, _getLocale.getLocale)('OKR_MyO_Pop_Targetname'), {
                canClose: false
              });

              return _context.abrupt("return");

            case 4:
              if (!(pureTextExcludeAt.length > 500)) {
                _context.next = 7;
                break;
              }

              _toast["default"].Error('目标名称不能超过500字', {
                canClose: false
              });

              return _context.abrupt("return");

            case 7:
              if (allKrHasName) {
                _context.next = 11;
                break;
              }

              _toast["default"].Error('关键成果不能为空', {
                canClose: false
              });

              setKrIsValidate(true);
              return _context.abrupt("return");

            case 11:
              orkNameLengthValidate = krDatas.filter(function (kr) {
                var _trim;

                return ((_trim = (kr.mileStoneNamePureTextExcludeAt || '').trim()) === null || _trim === void 0 ? void 0 : _trim.length) > 500;
              }).length == 0;

              if (orkNameLengthValidate) {
                _context.next = 15;
                break;
              }

              _toast["default"].Error('关键成果不能超过500字', {
                canClose: false
              });

              return _context.abrupt("return");

            case 15:
              setKrIsValidate(false);

              if (krWeightValid) {
                _context.next = 19;
                break;
              }

              _toast["default"].Error((0, _getLocale.getLocale)('OKR_MyO_Pop_Totalkrnot100'), {
                canClose: false
              });

              return _context.abrupt("return");

            case 19:
              if (cycle) {
                _context.next = 21;
                break;
              }

              return _context.abrupt("return");

            case 21:
              handleCreatedClose();
              visibilityArea = formatVisiableLimit();
              formData = _objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({
                krInfos: krDatas.map(function (kr) {
                  // @ts-ignore
                  delete kr.mileStoneNamePureTextExcludeAt;
                  return _objectSpread(_objectSpread({}, kr), {}, {
                    startDate: cycle.startDate,
                    endDate: cycle.endDate
                  });
                })
              }, cycle), {}, {
                workName: pureText,
                workNameRichText: richText,
                aiteUsers: mentionUsers === null || mentionUsers === void 0 ? void 0 : mentionUsers.map(function (user) {
                  return user.mentionId;
                })
              }, parent), {}, {
                workType: 6,
                visibility: visibility,
                okrClassify: openClassify ? okrClassify : '',
                okrType: openOkrType ? type.typeId : ''
              }, dept), team), {}, {
                workRoles: [{
                  roleType: 1,
                  models: [user]
                }]
              }, visibilityArea), {}, {
                CreateFromAssess: isFromAssess
              });
              _context.next = 26;
              return (0, _requestApi.createWidthKr)(formData);

            case 26:
              data = _context.sent;

              if (!(data.Code === 0)) {
                _context.next = 30;
                break;
              }

              _toast["default"].Error('创建失败，请重试', {
                canClose: false
              });

              return _context.abrupt("return");

            case 30:
              hideCreateOkrModal();

              if (onSuccess || !isHiddenCreatedCard) {
                // 带上超过创建okr人数的计算值
                krNum = krDatas.length;
                krTotalLength = 0;
                krDatas && krDatas.forEach(function (kr) {
                  var _kr$mileStoneNamePure;

                  // 计算平均长度要去掉百分号和数字
                  krTotalLength += (_kr$mileStoneNamePure = kr.mileStoneNamePureTextExcludeAt) === null || _kr$mileStoneNamePure === void 0 ? void 0 : _kr$mileStoneNamePure.replace(/(%|\d)/g, '').length;
                });
                krAvarageLength = krDatas.length > 0 ? krTotalLength / krDatas.length : 0;
                krMeasurableLength = krsCheckResult.friendlyResult.filter(function (kr) {
                  return kr.hasNumWords === true;
                }).length;
                oHasVtWords = oNameCheckResult[0].result === _okrCreateSuggest.EOkrCreateSuggestResultType.correct;
                callData = data;
                callData.countSurpassPercentage = (0, _getCreateOkrSurpassPercent["default"])(okrNameData.pureTextExcludeAt.replace(/(%|\d)/g, '').length, oHasVtWords, krNum, krMeasurableLength, Number.parseInt(krAvarageLength.toString()));
                newOkrDataRef.current = callData;
                handleOnSuccess();
              } else {
                workId = data.workId;

                _drawerManager["default"].open('okrDetail', {
                  okrId: workId
                });
              }

              setIsApplyTpl(false);

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

    return function onModalOkHandler() {
      return _ref3.apply(this, arguments);
    };
  }(); // 从OKR案例库中应用模板


  var OnOkRApplyTplHandler = function OnOkRApplyTplHandler(data) {
    var name = data.name,
        subelements = data.subelements;
    setOkrNameData(function () {
      return {
        mentionUsers: [],
        pureText: name,
        pureTextExcludeAt: name,
        richText: (0, _richEditor.TitaRichEditorInitTextState)(name)
      };
    });
    setKrDatas(function () {
      return subelements.map(function (s) {
        return {
          uuid: _uuid["default"].v1(),
          principalId: Id,
          principalName: Name,
          userAvatar: UserAvatar,
          krWeight: (0, _roundWeight.RoundWeight)(100 / subelements.length),
          mileStoneName: s.name,
          mileStoneNamePureTextExcludeAt: s.name,
          mileStoneNameRichText: (0, _richEditor.TitaRichEditorInitTextState)(s.name),
          aiteUsers: [],
          confidenceIndex: 5
        };
      });
    });
    setIsCustomWeight(false);
    setIsApplyTpl(true);
    setRichEditorStatus('refresh');
  };

  (0, _react.useEffect)(function () {
    if (!isVisible) {
      setKrDatas([{
        uuid: _uuid["default"].v1(),
        principalId: Id,
        principalName: Name,
        userAvatar: UserAvatar,
        krWeight: 100,
        mileStoneName: '',
        mileStoneNamePureTextExcludeAt: '',
        mileStoneNameRichText: undefined,
        aiteUsers: [],
        confidenceIndex: 5
      }]);
      setOkrNameData(DefaultOkrNameData);
      setUser({
        name: Name,
        id: Id,
        avatar: UserAvatar
      });
      setIsCustomWeight(false);
      setDept({
        departmentId: 0,
        departmentName: ''
      });
      setType({
        typeName: (0, _getLocale.getLocale)('OKR_MyO_Pop_Individual'),
        typeId: 1
      });
      setCycle(cycle);
      setOkrClassify(undefined);

      if (window.BSGlobal.tenantInfo.isOpenInfo) {
        setVisibility(1);
      } else {
        setVisibility(2);
      }

      setParent({
        parentWorkId: 0,
        parentWorkName: '',
        parentType: 0,
        parentKrId: 0
      });
    }

    return function () {
      return setRichEditorStatus('initialization');
    };
  }, [isVisible]);
  var handleONameSuggestClose = (0, _react.useCallback)(function () {
    setONameIsInput(false);
    setCustomCloseOSuggest(true);
  }, []);
  var handleKrSuggestClose = (0, _react.useCallback)(function () {
    setKrIsInput(false);
    setCustomCloseKrSuggest(true);
  }, []);
  var handleOInputFocusStateChange = (0, _react.useCallback)(function (state) {
    if (state) {
      setKrIsInput(false);
      oInputFoucsRef.current = true;
      setONameIsInput(state);
    } else {
      // 为了解决输入框聚焦之后，点击小手检查窗口还在引入了这个 ref，但是这个 ref 会在正常失焦也被赋值，所以需要一定时间后赋为默认值，krInputFoucsRef 也是
      setTimeout(function () {
        oInputFoucsRef.current = false;
      }, 500); // 为了解决输入框聚焦之后，点击收起时组件先销毁然后无法触发关闭事件

      setTimeout(function () {
        setONameIsInput(false);
      }, 100);
    }
  }, []);
  var handleKrInputStateChange = (0, _react.useCallback)(function (state) {
    if (state) {
      setONameIsInput(false);
      krInputFoucsRef.current = true; // 防止从上一个kr输入框聚焦情况直接tab切到下一个不展示输入框

      setTimeout(function () {
        setKrIsInput(state);
      }, 100);
    } else {
      setTimeout(function () {
        krInputFoucsRef.current = false;
      }, 500);
      setTimeout(function () {
        setKrIsInput(false);
      }, 100);
    }
  }, []);
  var handleShowOSuggest = (0, _react.useCallback)(function () {
    setCustomCloseOSuggest(false);

    if (oInputFoucsRef.current) {
      oInputFoucsRef.current = false;
      var result = oNameIsInput;

      if (customCloseOSuggest) {
        result = true;
      } else {
        result = !oNameIsInput;
      }

      setTimeout(function () {
        setONameIsInput(result);

        if (!result) {
          setCustomCloseOSuggest(true);
        }
      }, 100);
      return;
    }

    setTimeout(function () {
      setONameIsInput(!oNameIsInput);

      if (oNameIsInput) {
        setCustomCloseOSuggest(true);
      }
    }, 100);
    setKrIsInput(false);
  }, [oNameIsInput, customCloseOSuggest]);
  var handleShowKrSuggest = (0, _react.useCallback)(function () {
    setCustomCloseKrSuggest(false);

    if (krInputFoucsRef.current) {
      krInputFoucsRef.current = false;
      var result = krIsInput;

      if (customCloseKrSuggest) {
        result = true;
      } else {
        result = !krIsInput;
      }

      setTimeout(function () {
        setKrIsInput(result);

        if (!result) {
          setCustomCloseKrSuggest(true);
        }
      }, 100);
      return;
    }

    setTimeout(function () {
      setKrIsInput(!krIsInput);

      if (krIsInput) {
        setCustomCloseKrSuggest(true);
      }
    }, 100);
    setONameIsInput(false);
  }, [krIsInput, krIsInput]);
  var ModalTitle = (0, _react.useMemo)(function () {
    return /*#__PURE__*/_react["default"].createElement(_style.Line, null, /*#__PURE__*/_react["default"].createElement("span", {
      className: "create-modal__title"
    }, (0, _getLocale.getLocale)('OKR_MyO_Pop_Title_Newobjective')), /*#__PURE__*/_react["default"].createElement(_okrCase["default"], {
      okrTemplateEnabled: true,
      onOkrApply: OnOkRApplyTplHandler,
      onVisibleChange: function onVisibleChange() {
        setIsApplyTpl(false);
        setRichEditorStatus('initialization');
      }
    }));
  }, []);
  var krCheckFinalResult = (0, _react.useMemo)(function () {
    return (0, _constant.getKrCheckTarget)().map(function (item, index) {
      if (index === 0) {
        return {
          text: item,
          result: krDatas.length > 0 ? _okrCreateSuggest.EOkrCreateSuggestResultType.correct : _okrCreateSuggest.EOkrCreateSuggestResultType.wrong
        };
      }

      if (index === 1) {
        return {
          text: item,
          result: krDatas.length <= 5 ? _okrCreateSuggest.EOkrCreateSuggestResultType.correct : _okrCreateSuggest.EOkrCreateSuggestResultType.wrong
        };
      }

      return {
        text: item,
        result: krsCheckResult.finalResult
      };
    });
  }, [krDatas, krsCheckResult.finalResult]);
  var handleCloseShowSuccessInfo = (0, _react.useCallback)(function (dontShowValue) {
    if (dontShowValue) {
      localStorage.setItem("dontShowValue".concat(userId), userId);
    }

    setShowCreatedSuccessInfo(false);
    onSuccess && onSuccess(newOkrDataRef.current);
  }, []);
  var handleCloseAndShowDetail = (0, _react.useCallback)(function (dontShowValue, workId) {
    if (dontShowValue) {
      localStorage.setItem("dontShowValue".concat(userId), userId);
    }

    setShowCreatedSuccessInfo(false);

    _drawerManager["default"].open('okrDetail', {
      okrId: workId
    });

    onSuccess && onSuccess(newOkrDataRef.current);
  }, []);
  (0, _react.useEffect)(function () {
    if (!isVisible) return; // @ts-ignore

    (0, _requestApi.getImageBase64ByUrl)(user.id).then(function (data) {
      // console.log(data)
      setUserAvatarBase64Url(data.Data.obj);
    })["catch"](function (err) {
      _toast["default"].Error(err);
    });
  }, [user, isVisible]);

  var trackAction = function trackAction() {
    // @ts-ignore
    window.titaTracker && window.titaTracker('action').record({
      actionName: '点击【教你写OKR】',
      actionGroup: (0, _getLocale.getLocale)('OKR_MyO_Collr_Butt_CreatOKR'),
      productName: (0, _getLocale.getLocale)('Menu_Title_OKRs')
    });
  };

  var renderFooterTeachWriteOKr = (0, _react.useMemo)(function () {
    {
      /* 钉钉用  https://wiki.tita.com/pages/viewpage.action?pageId=15696093 */
    }
    return /*#__PURE__*/_react["default"].createElement("a", {
      className: "teact-write-okr",
      href: (0, _helpers.isDingDing)() ? 'https://wiki.tita.com/pages/viewpage.action?pageId=15696093' : 'https://docs.tita.com/question/okr-write/',
      target: "_blank",
      onClick: trackAction,
      rel: "noreferrer"
    }, /*#__PURE__*/_react["default"].createElement("img", {
      className: "teact-write-okr__icon",
      src: _teachOkr["default"]
    }), /*#__PURE__*/_react["default"].createElement("span", {
      className: "teact-write-okr__text"
    }, (0, _getLocale.getLocale)('OKR_MyO_Pop_TeachwriteOKR')));
  }, []);
  (0, _react.useEffect)(function () {
    // @ts-ignore
    window.showCreateOkrModal = showCreateOkrModal; // @ts-ignore

    window.hideCreateOkrModal = hideCreateOkrModal;
  }, []);
  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_titaUi.Modal, {
    ref: modalRef,
    width: 600,
    mask: true,
    centered: true,
    onOk: onModalOkHandler,
    okText: (0, _getLocale.getLocale)('OKR_MyO_Pop_Createnow'),
    cancelText: (0, _getLocale.getLocale)('Mod_Cancel'),
    title: ModalTitle,
    visible: isVisible,
    onCancel: hideCreateOkrModal,
    maskClosable: false,
    footerLeftContent: renderFooterTeachWriteOKr,
    zIndex: 1200,
    bodyStyle: {
      flexBasis: 'auto'
    }
  }, /*#__PURE__*/_react["default"].createElement(_style.Wrapper, {
    ref: wrapperRef
  }, /*#__PURE__*/_react["default"].createElement(_scrollbar["default"], null, /*#__PURE__*/_react["default"].createElement("div", {
    className: "create-modal__wrapper-inner"
  }, /*#__PURE__*/_react["default"].createElement(_oNewName["default"], {
    container: modalRef,
    richEditorStatus: richEditorStatus,
    key: richEditorStatus,
    user: user,
    setUser: setUser,
    okrNameData: okrNameData,
    setOkrNameData: setOkrNameData,
    onOInputFocusStateChange: handleOInputFocusStateChange,
    setONameCheckResult: setONameCheckResult,
    setIsInputContent: setIsInputContent
  }), /*#__PURE__*/_react["default"].createElement(_krDatas["default"], {
    isApplyTpl: isApplyTpl,
    isCustomWeight: isCustomWeight,
    wrapperRef: wrapperRef,
    krDatas: krDatas,
    setKrDatas: setKrDatas,
    container: modalRef,
    setIsCustomWeight: setIsCustomWeight,
    handleKrInputStateChange: handleKrInputStateChange,
    setKrsCheckResult: setKrsCheckResult,
    krIsValidate: krIsValidate,
    setKrIsValidate: setKrIsValidate,
    setIsInputContent: setIsInputContent
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "create-modal__title-line"
  }, /*#__PURE__*/_react["default"].createElement(_style.BlueBar, null), (0, _getLocale.getLocale)('Per_Ass_New_Appr_detail_moreS')), /*#__PURE__*/_react["default"].createElement("div", {
    className: "space-between-row"
  }, /*#__PURE__*/_react["default"].createElement(_okrParent["default"], {
    parent: parent,
    modalRef: modalRef,
    setParent: setParent,
    isCreateModal: true
  }), /*#__PURE__*/_react["default"].createElement(_dateCycle["default"], {
    cycle: cycle,
    modalRef: modalRef,
    setCycle: setCycle,
    user: user,
    setUser: setUser,
    isCreateModal: true
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: "space-between-row space-between-row--margin-bottom-4"
  }, /*#__PURE__*/_react["default"].createElement(_okrVisibility["default"], {
    visibility: visibility,
    setVisibility: setVisibility,
    visiableLimit: visiableLimit,
    setVisiableLimit: setVisiableLimit,
    isCreateModal: true
  }), openOkrType && /*#__PURE__*/_react["default"].createElement(_style.Space, null), /*#__PURE__*/_react["default"].createElement("div", {
    className: "space-between-row okr-type-classify"
  }, openOkrType && /*#__PURE__*/_react["default"].createElement(_okrType["default"], {
    dept: dept,
    type: type,
    setDept: setDept,
    setType: setType,
    team: team,
    setTeam: setTeam,
    isCreateModal: true
  }), openClassify && /*#__PURE__*/_react["default"].createElement(_style.Space, null), openClassify && /*#__PURE__*/_react["default"].createElement(_okrClassify["default"], {
    okrClassify: okrClassify,
    setOkrClassify: setOkrClassify,
    isCreateModal: true
  }))))), /*#__PURE__*/_react["default"].createElement("img", {
    className: "teach-suggest teach-suggest__o",
    src: _hand["default"],
    onClick: handleShowOSuggest
  }), /*#__PURE__*/_react["default"].createElement("img", {
    className: "teach-suggest teach-suggest__kr",
    src: _hand["default"],
    onClick: handleShowKrSuggest
  }), !customCloseOSuggest && oNameIsInput ? /*#__PURE__*/_react["default"].createElement(_okrCreateSuggest["default"], {
    isInput: isInputContent,
    isOSuggest: true,
    descs: (0, _constant.getODesc)(),
    example: (0, _constant.getOExample)(),
    results: oNameCheckResult,
    handleClose: handleONameSuggestClose
  }) : null, !customCloseKrSuggest && krIsInput ? /*#__PURE__*/_react["default"].createElement(_okrCreateSuggest["default"], {
    isInput: isInputContent,
    isOSuggest: false,
    descs: (0, _constant.getKrDesc)(),
    example: (0, _constant.KrExample)(),
    results: krCheckFinalResult,
    handleClose: handleKrSuggestClose
  }) : null))), !isApplyTpl && !isHiddenCreatedCard && showCreatedSuccessInfo ? /*#__PURE__*/_react["default"].createElement(_createSuccessCmpWrapper["default"], null, /*#__PURE__*/_react["default"].createElement(_createSuccessCmp["default"], {
    tipIndex: tipIndex,
    createdSuccessInfo: createdSuccessInfo,
    isDownload: false,
    onCloseModel: handleCloseShowSuccessInfo,
    onShowDetail: handleCloseAndShowDetail,
    downLoadRef: downloadDomRef
  })) : null, !isApplyTpl && !isHiddenCreatedCard && showCreatedSuccessInfo ? /*#__PURE__*/_react["default"].createElement("div", {
    className: "download-dom--hidden"
  }, /*#__PURE__*/_react["default"].createElement(_createSuccessCmp["default"], {
    tipIndex: tipIndex,
    createdSuccessInfo: createdSuccessInfo,
    isDownload: true,
    onCloseModel: handleCloseShowSuccessInfo,
    onShowDetail: handleCloseAndShowDetail,
    downLoadRef: downloadDomRef
  })) : null);
}

var _default = /*#__PURE__*/(0, _react.forwardRef)(CreateOkrModal);

exports["default"] = _default;