"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.templateRichPlugins = exports["default"] = void 0;

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var Sentry = _interopRequireWildcard(require("@sentry/browser"));

var _richEditor = _interopRequireWildcard(require("@titaui/rich-editor"));

var _reactIntersectionObserver = require("react-intersection-observer");

var _tooltip = _interopRequireDefault(require("../../../tooltip"));

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

var _summaryHeader = _interopRequireDefault(require("../components/summary-header"));

var _okrProgress = _interopRequireDefault(require("../components/okr-progress"));

var _taskProgress = _interopRequireDefault(require("../components/task-progress"));

var _workProgress = _interopRequireDefault(require("../components/work-progress"));

var _tools = require("../../../../utils/tools");

var _title = _interopRequireDefault(require("../../components/title"));

var _remindUserView = _interopRequireDefault(require("./components/remind-user-view"));

var _evalute = _interopRequireDefault(require("./components/evalute"));

var _richEditorUpload = _interopRequireDefault(require("../../../rich-editor-upload"));

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

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

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

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

require("./index.css");

var _excluded = ["data", "isFold"];

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 _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

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

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

var getEReportType = function getEReportType(type) {
  var reportTextMap = {
    8: (0, _getLocale.getLocale)('Rep_Tab_Dailynewspaper'),
    26: (0, _getLocale.getLocale)('Rep_Tab_Weeklynewspaper'),
    27: (0, _getLocale.getLocale)('Rep_Tab_MonthlyReport')
  };
  return reportTextMap[type];
};

var prefix = 'titaui-dynamic-new-report-item';
var loginUserId = (0, _bsGlobal.getUserInfo)().Id;

var templateRichPlugins = function templateRichPlugins(defaultPrincipleUser, editable, delAble, endDate, newTaskLine) {
  return ["heading", "strong", "color", "underLine", "deleteLine", "list", "alignment", "blockquote", "link", "table", "image", 'mention', {
    name: 'task',
    defaultPrincipleUser: defaultPrincipleUser,
    editable: editable,
    delAble: delAble,
    endDate: endDate,
    newTaskLine: newTaskLine
  }];
};

exports.templateRichPlugins = templateRichPlugins;

var DynamicReply = function DynamicReply(_ref) {
  var _classNames;

  var data = _ref.data,
      _ref$isFold = _ref.isFold,
      isFold = _ref$isFold === void 0 ? true : _ref$isFold,
      restProps = _objectWithoutProperties(_ref, _excluded);

  var feedId = data.feedId,
      submitState = data.submitState,
      publishUser = data.publishUser,
      reportType = data.reportType,
      dailyContent = data.dailyContent,
      atUsers = data.atUsers,
      attachments = data.attachments,
      evaluates = data.evaluates,
      canEvaluate = data.canEvaluate;
  var curAtUser = restProps.curAtUser;
  var files = (0, _util.formatAttachments)(attachments);

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

  var _useState3 = (0, _react.useState)(null),
      _useState4 = _slicedToArray(_useState3, 2),
      atValue = _useState4[0],
      setAtValue = _useState4[1];

  var _useState5 = (0, _react.useState)(false),
      _useState6 = _slicedToArray(_useState5, 2),
      showDelete = _useState6[0],
      setShowDelete = _useState6[1];

  var _useState7 = (0, _react.useState)(false),
      _useState8 = _slicedToArray(_useState7, 2),
      showEdit = _useState8[0],
      setShowEdit = _useState8[1];

  var contentRichTextRef = (0, _react.useRef)();
  var workPlanRichTextRef = (0, _react.useRef)();

  var _useContext = (0, _react.useContext)(_context.SearchKeyContext),
      searchKeyWord = _useContext.searchKeyWord;

  var _useState9 = (0, _react.useState)(evaluates || []),
      _useState10 = _slicedToArray(_useState9, 2),
      currentEvalutes = _useState10[0],
      setCurrentEvalutes = _useState10[1];

  var renderSuffix = /*#__PURE__*/_react["default"].createElement("span", {
    className: (0, _classnames["default"])("".concat(prefix, "__complete-type"), (_classNames = {}, _defineProperty(_classNames, "".concat(prefix, "__complete-type--normal"), submitState === 1), _defineProperty(_classNames, "".concat(prefix, "__complete-type--delay"), submitState === 2), _classNames))
  }, submitState === 1 && (0, _getLocale.getLocale)('Rep_Tab_Mys_Submitontime'), submitState === 2 && (0, _getLocale.getLocale)('Tasks_Tab_DelaSubmission'));

  var renderDesc = (0, _react.useMemo)(function () {
    var reportTextMap = {
      8: (0, _getLocale.getLocale)('Rep_Tab_Mys_Dailynewsp'),
      26: (0, _getLocale.getLocale)('Rep_Tab_Mys_sweeklyReport'),
      27: (0, _getLocale.getLocale)('Rep_Tab_Sub_monthlyeport')
    };
    return /*#__PURE__*/_react["default"].createElement("span", {
      className: "".concat(prefix, "__operate-desc")
    }, reportTextMap[reportType]);
  }, [reportType]);
  var edit = true;
  var delAble = true;
  var newTaskLine = true;

  var renderContent = function renderContent() {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: prefix
    }, /*#__PURE__*/_react["default"].createElement(_summaryHeader["default"], _extends({
      data: data
    }, restProps, {
      desc: renderDesc,
      user: publishUser,
      suffixContent: renderSuffix,
      showDelete: showDelete,
      showEdit: showEdit,
      canEvaluate: canEvaluate && !currentEvalutes,
      setEvaluates: setCurrentEvalutes
    })), /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__content")
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__content-title")
    }, /*#__PURE__*/_react["default"].createElement(_title["default"], {
      content: (0, _tools.htmlDecodeByRegExp)(data.name),
      type: getEReportType(reportType),
      typeBgColor: "rgba(92, 142, 255, 0.5)",
      titleBgColor: "rgba(92, 142, 255, 0.1)",
      contentColor: "#5C8EFF"
    }), (motionValue === null || motionValue === void 0 ? void 0 : motionValue.img) && /*#__PURE__*/_react["default"].createElement(_tooltip["default"], {
      overlay: motionValue.tips,
      placement: "top",
      align: {
        offset: [0, 5]
      }
    }, /*#__PURE__*/_react["default"].createElement("img", {
      src: motionValue.img,
      className: "".concat(prefix, "__content-mind"),
      alt: ""
    }))), dailyContent.map(function (item) {
      if (item.contentType === _constant.dailyContentType.richText) {
        return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, ((item === null || item === void 0 ? void 0 : item.richContent) || !(0, _util.isEmptyImage)(item === null || item === void 0 ? void 0 : item.richContent)) && /*#__PURE__*/_react["default"].createElement("div", {
          className: "".concat(prefix, "__work"),
          key: item.richContent || Math.random()
        }, /*#__PURE__*/_react["default"].createElement("p", {
          className: "".concat(prefix, "__richTitle")
        }, item.title), /*#__PURE__*/_react["default"].createElement(_richEditor["default"], {
          plugins: templateRichPlugins({}, edit, delAble, undefined, newTaskLine)
        }, /*#__PURE__*/_react["default"].createElement(_richEditor.EditorComponent, {
          editable: false,
          initialState: !!item.richContent ? JSON.parse(item.richContent || '{}') : undefined,
          placeholder: (0, _getLocale.getLocale)('Rep_NewS_Notfilled')
        }))));
      }

      if (item.contentType === _constant.dailyContentType.okr) {
        return item.content && /*#__PURE__*/_react["default"].createElement(_okrProgress["default"], {
          data: item.content,
          title: item.title,
          reportType: data.reportType
        });
      }

      if (item.contentType === _constant.dailyContentType.work && data.openWorkSetting) {
        return item.content && /*#__PURE__*/_react["default"].createElement(_workProgress["default"], {
          data: item.content,
          title: item.title,
          reportType: data.reportType,
          openWorkMileSetting: data.openWorkMileSetting,
          openWorkTaskSetting: data.openWorkTaskSetting
        });
      }

      if (item.contentType === _constant.dailyContentType.task) {
        return item.content && /*#__PURE__*/_react["default"].createElement(_taskProgress["default"], {
          data: item.content,
          title: item.title,
          reportType: data.reportType
        });
      }
    }), files.length > 0 && /*#__PURE__*/_react["default"].createElement("div", {
      className: "".concat(prefix, "__upload")
    }, /*#__PURE__*/_react["default"].createElement(_richEditorUpload["default"], {
      text: (0, _getLocale.getLocale)('Per_Ass_New_Err_Attachment'),
      files: files,
      editable: false,
      enableDelete: false
    })), /*#__PURE__*/_react["default"].createElement(_remindUserView["default"], {
      data: atValue,
      curAtUser: curAtUser
    }), currentEvalutes && currentEvalutes.length !== 0 && /*#__PURE__*/_react["default"].createElement(_evalute["default"], {
      evaluation: currentEvalutes[0],
      feedId: feedId,
      publishUser: publishUser,
      canEvaluate: canEvaluate
    })));
  };

  (0, _react.useEffect)(function () {
    setCurrentEvalutes(evaluates);
  }, [evaluates]);
  (0, _react.useEffect)(function () {
    (0, _tools.highLightWord)({
      parentDom: contentRichTextRef.current,
      keyWord: searchKeyWord
    });
    (0, _tools.highLightWord)({
      parentDom: workPlanRichTextRef.current,
      keyWord: searchKeyWord
    });
  }, [data, searchKeyWord]);
  (0, _react.useEffect)(function () {
    if (dailyContent) {
      var mindData = dailyContent.find(function (item) {
        return item.contentType === 1;
      });
      if (!(mindData !== null && mindData !== void 0 && mindData.content)) return;

      var motion = _constant.Motion.find(function (item) {
        var _JSON$parse$SelectedV;

        return item.id === (((_JSON$parse$SelectedV = JSON.parse(mindData.content || '{}').SelectedValues) === null || _JSON$parse$SelectedV === void 0 ? void 0 : _JSON$parse$SelectedV[0]) || 0);
      });

      setMotionValue(motion);
    }
  }, [dailyContent]);
  (0, _react.useEffect)(function () {
    if (dailyContent) {
      var atData = dailyContent.find(function (item) {
        return item.contentType === 5;
      });
      if (!(atData !== null && atData !== void 0 && atData.content)) return;
      var atMotion = JSON.parse(atData.content || '{}');
      setAtValue(atMotion);
    }
  }, [dailyContent]);
  (0, _react.useEffect)(function () {
    if (loginUserId === publishUser.userId) {
      setShowDelete(true);
      setShowEdit(true);
    }
  }, []);

  if (!window.IntersectionObserver) {
    Sentry.withScope(function (scope) {
      scope.setTag('error-level', "P0");
      scope.setTag('error-type', '总结在 window 找不到 IntersectionObserver');
      scope.setExtra('componentStack', '总结在 window 找不到 IntersectionObserver');
    });
    return renderContent();
  }

  var handleInView = function handleInView(inview) {
    if (!isFold) return;

    if (inview && window.titaTracker) {
      window.titaTracker('planAction').record({
        actionName: '查看日报',
        actionGroup: '动态-查看日报',
        productName: '动态',
        feedId: feedId
      });
    }
  };

  return /*#__PURE__*/_react["default"].createElement(_reactIntersectionObserver.InView, {
    triggerOnce: true,
    onChange: handleInView,
    threshold: 0.5
  }, renderContent());
};

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