"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RenderText = exports.Editor = undefined;

var _message2 = require("antd/es/message");

var _message3 = _interopRequireDefault(_message2);

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

var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

require("antd/es/message/style/css");

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

var _propTypes = require("prop-types");

var _propTypes2 = _interopRequireDefault(_propTypes);

var _axios = require("axios");

var _axios2 = _interopRequireDefault(_axios);

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

var _Comment = require("./Comment");

var _helper = require("./helper");

var _CommentInput = require("./components/CommentInput");

var _CommentInput2 = _interopRequireDefault(_CommentInput);

var _CommentList = require("./components/CommentList");

var _CommentList2 = _interopRequireDefault(_CommentList);

var _Editor = require("./components/Editor");

var _Editor2 = _interopRequireDefault(_Editor);

var _RenderText = require("./components/RenderText");

var _RenderText2 = _interopRequireDefault(_RenderText);

var _lang = require("./lang");

var _lang2 = _interopRequireDefault(_lang);

require("./App.css");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

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

// import styles from "./App.module.css";

var App = function (_Component) {
  _inherits(App, _Component);

  function App(props) {
    _classCallCheck(this, App);

    var _this = _possibleConstructorReturn(this, (App.__proto__ || Object.getPrototypeOf(App)).call(this, props));

    _this.state = {
      loading: {},

      // oss 配置
      oss: {},

      // 评论数据
      list: [],
      page: 1,
      total: 0,
      // 是否没有更多评论了
      isNoMoreComment: false
    };
    _this.handleChangeLoading = _this.handleChangeLoading.bind(_this);
    _this.sCreateComment = _this.sCreateComment.bind(_this);
    _this.sDeleteComment = _this.sDeleteComment.bind(_this);
    _this.sCommentFavor = _this.sCommentFavor.bind(_this);
    _this.sCreateReply = _this.sCreateReply.bind(_this);
    _this.sDeleteReply = _this.sDeleteReply.bind(_this);
    _this.errorHandler = _this.errorHandler.bind(_this);
    _this.sGetComment = _this.sGetComment.bind(_this);
    _this.sReplyFavor = _this.sReplyFavor.bind(_this);
    _this.sGetReply = _this.sGetReply.bind(_this);
    _this.sOssSts = _this.sOssSts.bind(_this);
    return _this;
  }

  _createClass(App, [{
    key: "componentWillMount",
    value: function componentWillMount() {
      this.axios = _axios2.default;
      this.axios.defaults.withCredentials = true;
      if (this.props.token) {
        this.axios.defaults.headers.common["Authorization"] = "Bearer " + this.props.token;
      }
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {}
  }, {
    key: "error",
    value: function error(msg) {
      var info = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      if (this.props.showError) {
        _message3.default.error(msg);
      }
      if (this.props.onError) {
        this.props.onError(msg, info);
      }
    }
  }, {
    key: "errorHandler",
    value: function errorHandler(error) {
      if (error.response && error.response.data && error.response.data.msg) {
        this.error(_lang2.default[error.response.data.msg] || _constant.ERROR_DEFAULT, {
          response: error.response
        });
        return;
      }
      this.error(_lang2.default[error.message] || _constant.ERROR_DEFAULT, {
        response: error.response
      });
    }

    /**
     * 改变 loading 状态
     * @param {string} key key
     * @param {string} value value
     */

  }, {
    key: "handleChangeLoading",
    value: function handleChangeLoading(key, value) {
      var loading = this.state.loading;

      loading[key] = value;
      this.setState({ loading: loading });
    }

    /**
     * 获取评论列表
     */

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

      var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref$page = _ref.page,
          page = _ref$page === undefined ? 1 : _ref$page;

      var pageType = this.props.pageType;

      this.handleChangeLoading("sGetComment", true);
      var _props = this.props,
          API = _props.API,
          type = _props.type,
          businessId = _props.businessId;

      this.axios.get(API + "/comments?type=" + type + "&business_id=" + businessId + "&page=" + page + "&limit=" + _constant.LIMIT).then(function (response) {
        var _response$data = response.data,
            list = _response$data.list,
            page = _response$data.page,
            total = _response$data.total;

        if (list) {
          var newList = list;
          var oldList = _this2.state.list;

          if (pageType === "more") {
            if (page > 1) {
              // 删除临时数据
              oldList = oldList.filter(function (o) {
                return !o.isTemporary;
              });
              newList = oldList.concat(newList);
            }
          } else if (pageType === "pagination") {
            // TODO 滚动到顶部
            window.scrollTo(0, 0);
          }

          _this2.setState({
            list: newList,
            page: page,
            total: total
          });
        } else {
          _message3.default.info("没有更多评论了");
          _this2.setState({
            isNoMoreComment: true
          });
        }
      }).catch(this.errorHandler).finally(function () {
        _this2.handleChangeLoading("sGetComment", false);
      });
    }

    /**
     * 获取更多回复
     */

  }, {
    key: "sGetReply",
    value: function sGetReply() {
      var _this3 = this;

      var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          commentId = _ref2.commentId,
          _ref2$page = _ref2.page,
          page = _ref2$page === undefined ? 1 : _ref2$page;

      this.handleChangeLoading("sGetReply", true);
      var API = this.props.API;

      this.axios.get(API + "/replies?comment_id=" + commentId + "&page=" + page + "&limit=" + _constant.LIMIT).then(function (response) {
        if (!response.data.list) {
          _message3.default.info("没有更多数据了！");
        }
        var list = _this3.state.list.map(function (item) {
          if (item.id === commentId) {
            if (!item.replies) item.replies = [];
            if (response.data.list) {
              if (page === 1) {
                // 如果当前页数为第一页，则清空当前所有的 replies
                // 并将获取到的 replies 存放在 state
                item.replies = response.data.list;
              } else {
                item.replies = item.replies.filter(function (o) {
                  return !o.isTemporary;
                }).concat(response.data.list);
                // 如果当前页数非第一页，则合并 replies
              }
              item.reply_count = response.data.total;
              item.reply_page = response.data.page;
            } else {
              item.isNoMoreReply = true;
            }
          }
          return item;
        });
        _this3.setState({ list: list });
      }).catch(this.errorHandler).finally(function () {
        _this3.handleChangeLoading("sGetReply", false);
      });
    }

    /**
     * 添加评论
     * @param {object} {content} comment content
     */

  }, {
    key: "sCreateComment",
    value: function sCreateComment() {
      var _this4 = this;

      var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          content = _ref3.content;

      var cb = arguments[1];

      if (!content) return this.error("评论内容不能为空 ");
      this.handleChangeLoading("sCreateComment", true);
      var _props2 = this.props,
          API = _props2.API,
          type = _props2.type,
          businessId = _props2.businessId;

      this.axios(API + "/comments", {
        method: "post",
        data: {
          type: type,
          business_id: businessId,
          content: content
        },
        withCredentials: true
      }).then(function (response) {
        if (_this4.props.showAlertComment) {
          _message3.default.success("评论成功！");
        }
        if ((0, _helper.isFunction)(cb)) cb();
        // 将数据写入到 list 中
        // 临时插入
        // 等到获取数据之后，删除临时数据
        var _state = _this4.state,
            list = _state.list,
            total = _state.total;

        list.unshift(_extends({}, response.data, {
          isTemporary: true // 临时的数据
        }));
        _this4.setState({ list: list, total: total + 1 });
      }).catch(this.errorHandler).finally(function () {
        _this4.handleChangeLoading("sCreateComment", false);
      });
    }

    /**
     * 删除评论
     */

  }, {
    key: "sDeleteComment",
    value: function sDeleteComment(commentId) {
      var _this5 = this;

      this.handleChangeLoading("sDeleteComment", true);
      var API = this.props.API;

      this.axios(API + "/comments/" + commentId, {
        method: "delete",
        withCredentials: true
      }).then(function () {
        var _state2 = _this5.state,
            list = _state2.list,
            total = _state2.total;

        var res = list.filter(function (item) {
          return item.id !== commentId;
        });
        _this5.setState({ list: res, total: total - 1 });
        _this5.props.onDelete(_constant.COMMENT_TYPE.COMMENT);
      }).catch(this.errorHandler).finally(function () {
        _this5.handleChangeLoading("sDeleteComment", false);
      });
    }

    /**
     * 添加回复
     * 回复评论/回复回复
     * @param {object} data { comment_id, content, [reply_id] }
     */

  }, {
    key: "sCreateReply",
    value: function sCreateReply(data, cb) {
      var _this6 = this;

      if (!data.content) return this.error("回复内容不能为空 ");
      this.handleChangeLoading("sCreateReply", true);
      var API = this.props.API;

      this.axios(API + "/replies", {
        method: "post",
        data: data,
        withCredentials: true
      }).then(function (response) {
        if (_this6.props.showAlertReply) {
          _message3.default.success("回复成功！");
        }
        if ((0, _helper.isFunction)(cb)) cb();
        // 将数据写入到 list 中
        // 临时插入
        // 等到获取数据之后，删除临时数据
        var list = _this6.state.list.map(function (item) {
          if (item.id === data.comment_id) {
            if (!item.replies) item.replies = [];
            item.replies.push(_extends({}, response.data, {
              isTemporary: true // 临时的数据
            }));
            item.reply_count += 1;
          }
          return item;
        });
        _this6.setState({ list: list });
      }).catch(this.errorHandler).finally(function () {
        _this6.handleChangeLoading("sCreateReply", false);
      });
    }

    /**
     * 删除回复
     * @param {*} replyId
     * @param {*} commentId
     */

  }, {
    key: "sDeleteReply",
    value: function sDeleteReply(replyId, commentId) {
      var _this7 = this;

      this.handleChangeLoading("sDeleteReply", true);
      var API = this.props.API;

      this.axios(API + "/replies/" + replyId + "?CommentID=" + commentId, {
        method: "delete",
        withCredentials: true
      }).then(function () {
        var list = _this7.state.list.map(function (item) {
          if (item.id === commentId) {
            var replies = item.replies.filter(function (item) {
              return item.id !== replyId;
            });
            item.replies = replies;
            item.reply_count -= 1;
          }
          return item;
        });
        _this7.setState({ list: list });
        _this7.props.onDelete(_constant.COMMENT_TYPE.REPLY);
      }).catch(this.errorHandler).finally(function () {
        _this7.handleChangeLoading("sDeleteReply", false);
      });
    }

    /**
     * 评论 点赞/取消点赞
     * @param {string} commentId { commentId }
     * @param {boolean} favored   是否已经点过赞
     */

  }, {
    key: "sCommentFavor",
    value: function sCommentFavor(commentId, favored) {
      var _this8 = this;

      this.handleChangeLoading("sCommentFavor", true);
      var API = this.props.API;

      this.axios(API + "/comments/" + commentId + "/favor", {
        method: favored ? "delete" : "put",
        withCredentials: true
      }).then(function (response) {
        if (_this8.props.showAlertFavor) {
          _message3.default.success(favored ? "取消点赞成功！" : "点赞成功！");
        }
        // 更新 list 中的该项数据的 favored
        var list = _this8.state.list.map(function (item) {
          if (item.id === commentId) {
            item.favored = !favored;
            item.favor_count += favored ? -1 : 1;
          }
          return item;
        });
        _this8.setState({ list: list });
      }).catch(this.errorHandler).finally(function () {
        _this8.handleChangeLoading("sCommentFavor", false);
      });
    }

    /**
     * 回复 点赞/取消点赞
     * @param {string} replyId  replyId
     * @param {string} commentId  commentId
     * @param {boolean} favored   是否已经点过赞
     */

  }, {
    key: "sReplyFavor",
    value: function sReplyFavor(replyId, commentId, favored) {
      var _this9 = this;

      this.handleChangeLoading("sReplyFavor", true);
      var API = this.props.API;

      this.axios(API + "/replies/" + replyId + "/favor", {
        method: favored ? "delete" : "put",
        data: {
          comment_id: commentId
        },
        withCredentials: true
      }).then(function (response) {
        _message3.default.success(favored ? "取消点赞成功！" : "点赞成功！");
        // 更新 list 中的该项数据的 favored
        var list = _this9.state.list.map(function (item) {
          if (item.id === commentId) {
            item.replies = item.replies.map(function (r) {
              if (r.id === replyId) {
                r.favored = !favored;
                // r.favor_count =  response.data.favor_count;
                // 点赞数 +1，而不是使用后端返回的点赞数
                // 不然如果返回的不是增加 1，用户可能以为程序错误
                r.favor_count += favored ? -1 : 1;
              }
              return r;
            });
          }
          return item;
        });
        _this9.setState({ list: list });
      }).catch(this.errorHandler).finally(function () {
        _this9.handleChangeLoading("sReplyFavor", false);
      });
    }

    /**
     * 获取 OSS 上传的参数
     */

  }, {
    key: "sOssSts",
    value: function sOssSts() {
      var _this10 = this;

      this.handleChangeLoading("sOssSts", true);
      var API = this.props.API;

      this.axios.get(API + "/oss/sts").then(function (response) {
        _this10.setState({ oss: _extends({}, response.data) });
      }).catch(this.errorHandler).finally(function () {
        _this10.handleChangeLoading("sOssSts", false);
      });
    }
  }, {
    key: "render",
    value: function render() {
      // 添加到 Context 的数据
      var value = _extends({}, this.state, this.props, {
        sCreateComment: this.sCreateComment,
        sGetComment: this.sGetComment,
        sCommentFavor: this.sCommentFavor,
        sReplyFavor: this.sReplyFavor,
        sCreateReply: this.sCreateReply,
        sGetReply: this.sGetReply,
        sOssSts: this.sOssSts,
        sDeleteComment: this.sDeleteComment,
        sDeleteReply: this.sDeleteReply
      });

      return _react2.default.createElement(
        _Comment.CommentContext.Provider,
        { value: value },
        _react2.default.createElement(
          "div",
          { className: "comment" },
          this.props.showEditor && _react2.default.createElement(_CommentInput2.default, { content: this.props.children }),
          this.props.showList && _react2.default.createElement(
            "div",
            { style: { marginTop: 20 } },
            _react2.default.createElement(_CommentList2.default, null)
          )
        )
      );
    }
  }]);

  return App;
}(_react.Component);

App.propTypes = {
  type: _propTypes2.default.number.isRequired, // 评论的 type
  businessId: _propTypes2.default.string.isRequired, // 评论的 business_id
  API: _propTypes2.default.string, // 评论的 API 前缀
  showList: _propTypes2.default.bool, // 是否显示评论列表
  showEditor: _propTypes2.default.bool, // 是否显示评论输入框
  showAlertComment: _propTypes2.default.bool, // 评论成功之后，是否通过 Antd 的 Message 组件进行提示
  showAlertReply: _propTypes2.default.bool, // 回复成功之后，是否通过 Antd 的 Message 组件进行提示
  showAlertFavor: _propTypes2.default.bool, // 点赞/取消点赞成功之后，是否通过 Antd 的 Message 组件进行提示
  showError: _propTypes2.default.bool, // 是否使用Antd的Message组件提示错误信息
  onError: _propTypes2.default.func, // 错误回调, 出错了会被调用
  userId: _propTypes2.default.number, // 用户id, comment内部不维护用户id, 调用组件时传递过来, 目前用于判断是否显示删除按钮
  pageType: _propTypes2.default.string, // 分页类型
  page: _propTypes2.default.number, // 页码
  onPageChange: _propTypes2.default.func, // 页码变化回调
  onDelete: _propTypes2.default.func
};

App.defaultProps = {
  API: "//api.links123.net/comment/v1",
  showList: true,
  showEditor: true,
  showAlertComment: false,
  showAlertReply: false,
  showAlertFavor: false,
  showError: true,
  pageType: "more",
  onPageChange: function onPageChange(page) {},
  onDelete: function onDelete() {}
};

exports.Editor = _Editor2.default;
exports.RenderText = _RenderText2.default;
exports.default = App;
//# sourceMappingURL=App.js.map