"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 _uuid = _interopRequireDefault(require("uuid"));

var _MblogContent = _interopRequireDefault(require("./components/MblogContent"));

var _MblogAction = _interopRequireDefault(require("./components/MblogAction"));

var _avatar = _interopRequireDefault(require("../avatar"));

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

var _index = require("./common/index");

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

var _platform = require("../../utils/platform");

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

var _editor = _interopRequireWildcard(require("../../utils/editor"));

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var prefix = 'titaui-mblog';

var MBlog = /*#__PURE__*/function (_PureComponent) {
  _inherits(MBlog, _PureComponent);

  var _super = _createSuper(MBlog);

  function MBlog(props) {
    var _BSGlobal$loginUserIn, _BSGlobal$loginUserIn2, _BSGlobal$loginUserIn3;

    var _this;

    _classCallCheck(this, MBlog);

    _this = _super.call(this, props);
    _this.isManager = ((_BSGlobal$loginUserIn = BSGlobal.loginUserInfo) === null || _BSGlobal$loginUserIn === void 0 ? void 0 : _BSGlobal$loginUserIn.IsRoot) || ((_BSGlobal$loginUserIn2 = BSGlobal.loginUserInfo) === null || _BSGlobal$loginUserIn2 === void 0 ? void 0 : _BSGlobal$loginUserIn2.IsBoss) || ((_BSGlobal$loginUserIn3 = BSGlobal.loginUserInfo) === null || _BSGlobal$loginUserIn3 === void 0 ? void 0 : _BSGlobal$loginUserIn3.IsOkrManager);
    _this.previewid = (0, _uuid["default"])();

    _this.getTextareaValue = function () {
      var _this$props = _this.props,
          commentsTypeKey = _this$props.commentsTypeKey,
          privateValue = _this$props.privateValue,
          defaultContent = _this$props.defaultContent;
      var localStroageKey = "mblogLocalStroage1_".concat((0, _bsGlobal.getUserInfo)().Id, "_commentsTypeKey_").concat(commentsTypeKey); // 根据commentsTypeKey设置localStroageKey

      var textareaValue = (0, _index.htmlDecodeByRegExp)(localStorage.getItem(localStroageKey) || defaultContent); // 获取本地缓存内容

      var atAll = !!textareaValue.match(/@\[所有同事:all_members\]/g);

      _this.setState({
        isAtAll: atAll,
        localStroageKey: localStroageKey,
        textareaValue: textareaValue.trim(),
        visibility: atAll ? 1 : privateValue || 1,
        isAllowSubmit: _this.allowSubmit(textareaValue) // 根据内容判断是否可以提交

      });
    };

    _this.onEditorContentChange = function (_ref) {
      var mentionUsers = _ref.mentionUsers,
          pureText = _ref.pureText,
          richText = _ref.richText,
          state = _ref.state;
      var contentValue = pureText;
      var atAll = !!mentionUsers.find(function (_ref2) {
        var mentionType = _ref2.mentionType;
        return mentionType === 2;
      });

      _this.setState({
        mentionUsers: mentionUsers,
        richText: richText,
        pureText: pureText,
        textareaValue: contentValue,
        isAllowSubmit: state.doc.content.size > 2,
        isAtAll: atAll,
        visibility: atAll ? 1 : _this.state.visibility
      });

      localStorage.setItem(_this.state.localStroageKey, contentValue);
    };

    _this.onActionsAllMembersChange = function () {
      var editorRef = _this.refs.textEditor.refs.editorRef;
      editorRef.append((0, _editor["default"])([{
        type: 'all_members',
        Name: (0, _getLocale.getLocale)('Per_Ma_form_newdetail_All'),
        Id: 0
      }]), {
        insertPos: true
      });
      editorRef.focus();
    };

    _this.onActionsEmotionChange = function (emotion) {
      var editorRef = _this.refs.textEditor.refs.editorRef;
      editorRef.append((0, _editor.appendImgs)(emotion.host + emotion.address, emotion.name), {
        insertPos: true
      });
      editorRef.focus();
    };

    _this.onActionsTextChange = function (actionValue) {
      if (actionValue === 'allowSendSMS') {
        return _this.setState({
          isSendSMS: true
        });
      }

      if (actionValue === 'public') {
        return _this.setState({
          visibility: 1
        });
      }

      if (actionValue === 'private') {
        return _this.setState({
          visibility: 2
        });
      }

      if (actionValue === 'department') {
        return _this.setState({
          visibility: 3
        });
      }
    };

    _this.onActionsSelectedUserChange = function (_ref3, _ref4, _ref5) {
      var departments = _ref3.departments,
          groups = _ref3.groups,
          users = _ref3.users;
      var isWechat = _ref4.isWechat;
      var selectNodes = _ref5.selectNodes;
      var editorRef = _this.refs.textEditor.refs.editorRef;
      editorRef.append((0, _editor.appendUserSelectorData)(selectNodes), {
        insertPos: true
      });
      editorRef.focus(); // @ts-ignore
      // const { textareaInput } = this.refs.textEditor.refs
      // const mark = generateSelectedMark(users, textareaInput)
      // const nextContent = insertTextAtPointer(textareaInput, mark)

      _this.setState({
        isInputAt: false
      }, function () {
        _this.focus();
      });
    };

    _this.handlerDealAttachemntData = function (uploadSuccessFilesPath) {
      var attachemntCanSubmit = _this.props.attachemntCanSubmit;
      var successFilesPath = uploadSuccessFilesPath.filter(function (item) {
        return item !== '';
      });

      if (successFilesPath.length > 0 && attachemntCanSubmit) {
        _this.setState({
          isAllowSubmit: true
        });
      }

      _this.setState({
        uploadSuccessFilesPath: successFilesPath,
        dragFilesList: []
      });
    };

    _this.focus = function () {
      // @ts-ignore
      var textareaInput = _this.refs.textEditor.refs.textareaInput;

      if (textareaInput) {
        setTimeout(function () {
          textareaInput.focus();
        }, 300);
      }
    };

    _this.allowSubmit = function (content) {
      return content.trim().length > 0 && content.trim().length <= _this.props.maxLength || _this.state.uploadSuccessFilesPath.length > 0;
    };

    _this.onActionSubmit = function (submitType) {
      var _this$state = _this.state,
          textareaValue = _this$state.textareaValue,
          uploadSuccessFilesPath = _this$state.uploadSuccessFilesPath,
          isSendSMS = _this$state.isSendSMS,
          visibility = _this$state.visibility,
          mentionUsers = _this$state.mentionUsers,
          richText = _this$state.richText,
          pureText = _this$state.pureText,
          isAllowSubmit = _this$state.isAllowSubmit;
      if (!isAllowSubmit) return;
      var _this$props2 = _this.props,
          isShowAttachment = _this$props2.isShowAttachment,
          isShowSendSms = _this$props2.isShowSendSms,
          isShowRange = _this$props2.isShowRange,
          submitStatus = _this$props2.submitStatus;
      var sentData = {}; // 发送的数据

      var FileUrl = uploadSuccessFilesPath.join(','); // 附件链接

      if (isShowAttachment) {
        // @ts-ignore
        sentData.FileUrl = FileUrl;
      }

      if (isShowSendSms) {
        // @ts-ignore
        sentData.IsSendSMS = isSendSMS;
      }

      if (isShowRange) {
        // @ts-ignore
        sentData.visibility = visibility;
      } // @ts-ignore


      sentData.Content = richText; // @ts-ignore

      if (pureText) {
        sentData.contentTxt = pureText.replace(/@\$userName=0\$/g, '@所有人');
      } // @ts-ignore


      if (mentionUsers) sentData.mentionUsers = (0, _editor.usersTypeToNumber)(mentionUsers);
      sentData.version = 1; // @ts-ignore

      if (submitType === 'submit' && submitStatus !== 2) {
        // 发送
        _this.props.onMblogSubmit(submitType, sentData);
      } else if (submitType === 'cancel') {
        // 取消
        _this.props.onMblogSubmit(submitType);
      }

      var editorRef = _this.refs.textEditor.refs.editorRef;
      editorRef.clear();

      _this.setState({
        textareaValue: '',
        uploadSuccessFilesPath: []
      });
    };

    _this._dropHandler = function (event) {
      event.preventDefault();
      var fileList = event.dataTransfer.files;

      if (fileList.length > 0) {
        var dragFilesList = [];

        for (var i = 0; i < fileList.length; i++) {
          dragFilesList.push(fileList[i]); // 将对象转换成数组
        }

        _this.setState({
          dragFilesList: dragFilesList // isShowDragMask: false

        });
      }

      _this.setState({
        isShowDragMask: false
      });
    };

    _this._dragEnterHandler = function (event) {
      event.preventDefault();

      _this.setState({
        dragFilesList: [],
        isShowDragMask: true
      });
    };

    _this._dragLeaveHandler = function (event) {
      event.preventDefault();
      event.target.parentNode == _this.refs.mblogbox ? _this.setState({
        isShowDragMask: false
      }) : _this.setState({
        isShowDragMask: true
      });
    };

    _this._dragOverHandler = function (event) {
      event.preventDefault();

      _this.setState({
        isShowDragMask: true
      });
    };

    _this.handlerPasteChange = function (file) {
      // if (!isPlatform('wx')) {
      _this.setState({
        dragFilesList: []
      });

      var dragFilesList = [];
      dragFilesList.push(file);
      setTimeout(function () {
        _this.setState({
          dragFilesList: dragFilesList
        });
      }, 300); // }
    };

    _this.state = {
      mentionUsers: [],
      richText: '',
      pureText: '',
      uploadSuccessFilesPath: [],
      isAllowSubmit: false,
      localStroageKey: '',
      // 本地存储key
      textareaValue: '',
      isSendSMS: false,
      visibility: 1,
      isInputAt: false,
      isInputEnterSubmit: false,
      dragFilesList: [],
      isShowDragMask: false,
      isAtAll: false
    };
    return _this;
  } // @ts-ignore @所有同事权限设置，有权限的：超管、老板、助理、目标负责人、目标管理员


  _createClass(MBlog, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.getTextareaValue();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState) {
      if (prevProps.commentsTypeKey != this.props.commentsTypeKey) {
        this.getTextareaValue();
      }
    } // 获取输入框显示内容

  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props3 = this.props,
          className = _this$props3.className,
          submitStatus = _this$props3.submitStatus,
          contentClassName = _this$props3.contentClassName,
          isHasPlaceholder = _this$props3.isHasPlaceholder,
          _this$props3$placehol = _this$props3.placeholderText,
          placeholderText = _this$props3$placehol === void 0 ? '有事需要提醒ta，请@ta' : _this$props3$placehol,
          maxLength = _this$props3.maxLength,
          autoResizing = _this$props3.autoResizing,
          initialTextHeight = _this$props3.initialTextHeight,
          autoFocus = _this$props3.autoFocus,
          actionClassName = _this$props3.actionClassName,
          isShowAttachment = _this$props3.isShowAttachment,
          _this$props3$attachme = _this$props3.attachmentText,
          attachmentText = _this$props3$attachme === void 0 ? (0, _getLocale.getLocale)('Mod_Annexes') : _this$props3$attachme,
          attachmentTipText = _this$props3.attachmentTipText,
          fileNumLimit = _this$props3.fileNumLimit,
          attachmentPreviewBox = _this$props3.attachmentPreviewBox,
          _this$props3$atAllTex = _this$props3.atAllText,
          atAllText = _this$props3$atAllTex === void 0 ? (0, _getLocale.getLocale)('Mod_AllColleagues') : _this$props3$atAllTex,
          _this$props3$atAllVal = _this$props3.atAllValue,
          atAllValue = _this$props3$atAllVal === void 0 ? '@[所有同事:all_members] ' : _this$props3$atAllVal,
          _this$props3$atAllTip = _this$props3.atAllTipText,
          atAllTipText = _this$props3$atAllTip === void 0 ? (0, _getLocale.getLocale)('OKR_MyO_Popup_Allcolleagues') : _this$props3$atAllTip,
          isShowAt = _this$props3.isShowAt,
          showAtAll = _this$props3.showAtAll,
          _this$props3$atText = _this$props3.atText,
          atText = _this$props3$atText === void 0 ? (0, _getLocale.getLocale)('Mod_colleague') : _this$props3$atText,
          _this$props3$atTipTex = _this$props3.atTipText,
          atTipText = _this$props3$atTipTex === void 0 ? (0, _getLocale.getLocale)('OKR_MyO_Popup_Butt_Colleagues') : _this$props3$atTipTex,
          userSelectorPopAlign = _this$props3.userSelectorPopAlign,
          isShowEmotion = _this$props3.isShowEmotion,
          _this$props3$emotionT = _this$props3.emotionText,
          emotionText = _this$props3$emotionT === void 0 ? (0, _getLocale.getLocale)('Mod_Expressions') : _this$props3$emotionT,
          emotionTipText = _this$props3.emotionTipText,
          emotionsSelectorPopAlign = _this$props3.emotionsSelectorPopAlign,
          isShowSendSms = _this$props3.isShowSendSms,
          _this$props3$sendSmsT = _this$props3.sendSmsTipText,
          sendSmsTipText = _this$props3$sendSmsT === void 0 ? (0, _getLocale.getLocale)('Tasks_Tab_MyS_Thecollenotified') : _this$props3$sendSmsT,
          isShowRange = _this$props3.isShowRange,
          isShowRangeDropDown = _this$props3.isShowRangeDropDown,
          isShowBtnCancel = _this$props3.isShowBtnCancel,
          _this$props3$submitTe = _this$props3.submitText,
          submitText = _this$props3$submitTe === void 0 ? (0, _getLocale.getLocale)('Mod_Publish') : _this$props3$submitTe,
          setTextareaRef = _this$props3.setTextareaRef,
          disableRangeSelect = _this$props3.disableRangeSelect,
          showUser = _this$props3.showUser,
          useMouseDown = _this$props3.useMouseDown;
      var _this$state2 = this.state,
          localStroageKey = _this$state2.localStroageKey,
          visibility = _this$state2.visibility,
          isInputAt = _this$state2.isInputAt,
          isInputEnterSubmit = _this$state2.isInputEnterSubmit,
          isAllowSubmit = _this$state2.isAllowSubmit,
          textareaValue = _this$state2.textareaValue,
          dragFilesList = _this$state2.dragFilesList,
          isShowDragMask = _this$state2.isShowDragMask,
          isAtAll = _this$state2.isAtAll;
      var fSize = (0, _bsGlobal.getUploadMaxSize)();
      var fTip = attachmentTipText || (0, _getLocale.getLocale)('OKR_MyO_KRP_Draganddropu').replace('50MB', "".concat(fSize, "MB"));
      var user = (0, _bsGlobal.getUserInfo)();
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: prefix
      }, showUser && /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(prefix, "__avatar")
      }, /*#__PURE__*/_react["default"].createElement(_avatar["default"], {
        size: {
          width: 28,
          textNum: 1,
          fontSize: 14
        },
        name: user.Name,
        color: user.UserAvatar.Color,
        src: user.UserAvatar.Medium,
        userId: user.Id
      })), /*#__PURE__*/_react["default"].createElement(_style.MBlogBox, {
        className: className,
        ref: "mblogbox",
        onDrop: this._dropHandler,
        onDragEnter: this._dragEnterHandler,
        onDragLeave: this._dragLeaveHandler,
        onDragOver: this._dragOverHandler
      }, /*#__PURE__*/_react["default"].createElement(_MblogContent["default"], {
        ref: "textEditor",
        setTextareaRef: setTextareaRef || function () {},
        textareaValue: textareaValue,
        className: contentClassName,
        isHasPlaceholder: isHasPlaceholder,
        placeholderText: placeholderText,
        maxLength: maxLength,
        autoFocus: autoFocus,
        autoResizing: autoResizing,
        initialTextHeight: initialTextHeight,
        visibility: visibility,
        submitStatus: submitStatus,
        onPasteSubmit: function onPasteSubmit(file) {
          _this2.handlerPasteChange(file);
        },
        onContentChange: function onContentChange(contentValue) {
          _this2.onEditorContentChange(contentValue);
        },
        onActionSubmit: function onActionSubmit(submitType) {
          _this2.onActionSubmit(submitType);
        }
      }), /*#__PURE__*/_react["default"].createElement(_MblogAction["default"], {
        className: actionClassName,
        isShowAttachment: isShowAttachment,
        attachmentText: attachmentText,
        attachmentTipText: fTip,
        attachmentPreviewBox: attachmentPreviewBox || this.previewid,
        fileNumLimit: fileNumLimit,
        fileSizeLimit: fSize,
        isShowAtAll: showAtAll != undefined ? showAtAll : this.isManager,
        atAllText: atAllText,
        atAllValue: atAllValue,
        atAllTipText: atAllTipText,
        isInputAt: isInputAt,
        isShowAt: isShowAt,
        atText: atText,
        atTipText: atTipText,
        userSelectorPopAlign: userSelectorPopAlign,
        isShowEmotion: isShowEmotion,
        emotionText: emotionText,
        emotionTipText: emotionTipText,
        emotionsSelectorPopAlign: emotionsSelectorPopAlign,
        isShowSendSms: isShowSendSms,
        sendSmsTipText: sendSmsTipText,
        isShowRange: isShowRange,
        isShowRangeDropDown: isShowRangeDropDown,
        visibility: isAtAll ? 1 : visibility,
        dragFilesList: dragFilesList,
        isShowBtnCancel: isShowBtnCancel,
        isInputEnterSubmit: isInputEnterSubmit,
        isAllowSubmit: isAllowSubmit,
        submitText: submitText,
        submitStatus: submitStatus,
        localStroageKey: localStroageKey,
        disableRangeSelect: disableRangeSelect || isAtAll,
        onActionsTextChange: this.onActionsTextChange,
        onActionsAllMembersChange: this.onActionsAllMembersChange,
        onActionsEmotionChange: this.onActionsEmotionChange,
        onActionsSelectedUserChange: this.onActionsSelectedUserChange,
        onActionsAttachmentChange: this.handlerDealAttachemntData,
        onActionSubmit: this.onActionSubmit,
        useMouseDown: useMouseDown
      }), /*#__PURE__*/_react["default"].createElement(_style.PreviewBox, {
        id: this.previewid
      }), !(0, _platform.isPlatform)('wx') && isShowDragMask && /*#__PURE__*/_react["default"].createElement(_style.DragEffect, {
        className: "tu-icon-inbox-upload"
      })));
    }
  }]);

  return MBlog;
}(_react.PureComponent);

exports["default"] = MBlog;
MBlog.defaultProps = {
  // 样式相关
  contentClassName: '',
  // 输入框class
  actionClassName: '',
  // 功能栏class
  // 输入相关
  defaultContent: '',
  isHasPlaceholder: false,
  maxLength: 2000,
  autoFocus: false,
  autoResizing: true,
  initialTextHeight: 48,
  // 功能相关
  // 附件
  isShowAttachment: true,
  // attachmentTipText: `<p>支持拖拽上传</p><p>单次最多支持上传20个</p><p>每个不超过50MB</p>`,
  attachmentTipText: '',
  fileNumLimit: 20,
  fileSizeLimit: 50,
  // @同事
  isShowAt: true,
  // @所有同事
  // @表情
  isShowEmotion: true,
  emotionTipText: '',
  // @按钮相关
  isShowSendSms: true,
  isShowRange: true,
  privateValue: 1,
  // 1公开，2私密 3部门
  isShowRangeDropDown: true,
  isShowBtnCancel: true,
  submitStatus: 0,
  showUser: false,
  attachemntCanSubmit: true
};