"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 _toast = _interopRequireDefault(require("../../toast"));

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

var _inputWithErrPopup = _interopRequireDefault(require("./input-with-err-popup"));

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

var _okrNewUserSelector = _interopRequireDefault(require("./okr-new-user-selector"));

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

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

function ONewName(_ref) {
  var richEditorStatus = _ref.richEditorStatus,
      okrNameData = _ref.okrNameData,
      setOkrNameData = _ref.setOkrNameData,
      container = _ref.container,
      user = _ref.user,
      setUser = _ref.setUser,
      onOInputFocusStateChange = _ref.onOInputFocusStateChange,
      setONameCheckResult = _ref.setONameCheckResult,
      _ref$setIsInputConten = _ref.setIsInputContent,
      setIsInputContent = _ref$setIsInputConten === void 0 ? function () {} : _ref$setIsInputConten;
  var oCheckId = 0;
  var mentionInputRef = (0, _react.useRef)();
  var timerRef = (0, _react.useRef)();
  var okrNameIsEmpty = (0, _react.useRef)(!okrNameData.pureText);
  var oldONameRef = (0, _react.useRef)('');
  var formatUser = (0, _react.useMemo)(function () {
    var medium = user.avatar && (user.avatar.Medium || user.avatar.medium);
    var color = user.avatar && (user.avatar.Color || user.avatar.color);
    return {
      Medium: medium,
      Color: color,
      Name: user.name,
      Id: user.id
    };
  }, [user.avatar, user.avatar, user.name, user.id]);
  var changeUser = (0, _react.useCallback)(function (_ref2) {
    var _ref3 = _slicedToArray(_ref2, 1),
        user = _ref3[0];

    var avatar = {
      Color: user.UserAvatar.Color,
      Small: user.UserAvatar.Small,
      Medium: user.UserAvatar.Medium
    };

    if (setUser) {
      setUser({
        name: user.Name,
        id: user.Id,
        avatar: avatar
      });
    }
  }, [setUser]);
  var getOAnalysisInfo = (0, _react.useCallback)(function () {
    oCheckId += 1;
    var tempCheckId = oCheckId; // @ts-ignore

    return (0, _requestApi.getOAnalysisInfos)({
      text: okrNameData.pureTextExcludeAt
    }) // @ts-ignore
    .then(function (data) {
      if (tempCheckId !== oCheckId) {
        return null;
      }

      var result = (0, _constant.OCheckTarget)().map(function (item, index) {
        if (index === 0) {
          return {
            text: item,
            result: data.hasVtWords ? _okrCreateSuggest.EOkrCreateSuggestResultType.correct : _okrCreateSuggest.EOkrCreateSuggestResultType.wrong
          };
        }

        return {
          text: item,
          result: data.hasNumWords ? _okrCreateSuggest.EOkrCreateSuggestResultType.wrong : _okrCreateSuggest.EOkrCreateSuggestResultType.correct
        };
      }); // 如果已经清空了okr，则赋给默认值

      if (okrNameIsEmpty.current) {
        setONameCheckResult(initOCheckResult());
      } else {
        setONameCheckResult(result);
      }

      return null;
    })["catch"](function (err) {
      _toast["default"].Error(err);
    })["finally"](function () {
      setIsInputContent(false);
    });
  }, [okrNameData, setIsInputContent]);

  var onChangeHandler = function onChangeHandler(data) {
    setOkrNameData(data);
    setIsInputContent(true);
  };

  (0, _react.useEffect)(function () {
    // 防抖
    okrNameIsEmpty.current = !okrNameData.pureText;

    if (!okrNameData.pureText) {
      setONameCheckResult(initOCheckResult());
      setIsInputContent(false);
    } else if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = setTimeout(getOAnalysisInfo, 1000);
    } else {
      timerRef.current = setTimeout(getOAnalysisInfo, 1000);
    }

    return function () {
      clearTimeout(timerRef.current);
    };
  }, [okrNameData]);
  var handleInputFocus = (0, _react.useCallback)(function () {
    if (onOInputFocusStateChange) {
      onOInputFocusStateChange(true);
    }
  }, []);
  var handleInputBlur = (0, _react.useCallback)(function () {
    if (onOInputFocusStateChange) {
      onOInputFocusStateChange(false);
    }
  }, []);
  var handleOnKeyDown = (0, _react.useCallback)(function (e) {
    setIsInputContent(true);
  }, [setIsInputContent]);
  var handleOnKeyUp = (0, _react.useCallback)(function (e) {
    e.persist(); // 解决按功能按钮的时候一直显示检测中

    if (e.target.value === oldONameRef.current) {
      setIsInputContent(false);
    } else {
      oldONameRef.current = e.target.value;
    }
  }, []);
  var pureTextExcludeAt = okrNameData.pureTextExcludeAt,
      richText = okrNameData.richText;
  var okrNameLen = (pureTextExcludeAt === null || pureTextExcludeAt === void 0 ? void 0 : pureTextExcludeAt.length) || 0;
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "okr-o-new-name"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "okr-o-new-name__left-block"
  }, /*#__PURE__*/_react["default"].createElement("span", {
    className: "left-block__title"
  }, "O"), /*#__PURE__*/_react["default"].createElement(_inputWithErrPopup["default"], {
    strLength: okrNameLen,
    maxLength: 500,
    position: "top"
  }, /*#__PURE__*/_react["default"].createElement(_richEditor.TitaInlineRichEditor, {
    initialState: richText,
    key: richEditorStatus,
    onDocChange: onChangeHandler,
    onFocus: handleInputFocus,
    onBlur: handleInputBlur,
    onKeyDown: handleOnKeyDown,
    onKeyUp: handleOnKeyUp,
    placeholder: (0, _getLocale.getLocale)('OKR_MyO_Pop_PleInspObjective'),
    ref: mentionInputRef
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: "left-block__right-text-mask"
  })), /*#__PURE__*/_react["default"].createElement(_okrNewUserSelector["default"], {
    user: formatUser,
    container: container,
    changeUser: changeUser
  }));
}

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