"use strict";

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

var _tag = require("antd/es/tag");

var _tag2 = _interopRequireDefault(_tag);

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/tag/style/css");

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

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.sGetComment = _this.sGetComment.bind(_this);
    _this.sGetReply = _this.sGetReply.bind(_this);
    _this.sCreateComment = _this.sCreateComment.bind(_this);
    _this.sCreateReply = _this.sCreateReply.bind(_this);
    _this.sCommentFavor = _this.sCommentFavor.bind(_this);
    _this.sReplyFavor = _this.sReplyFavor.bind(_this);
    _this.sOssSts = _this.sOssSts.bind(_this);
    return _this;
  }

  _createClass(App, [{
    key: "componentDidMount",
    value: function componentDidMount() {}

    /**
     * 改变 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;

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

      _axios2.default.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;
          if (page > 1) {
            var oldList = _this2.state.list;
            // 删除临时数据

            oldList = oldList.filter(function (o) {
              return !o.isTemporary;
            });
            newList = oldList.concat(newList);
          }
          _this2.setState({
            list: newList,
            page: page,
            total: total
          });
        } else {
          _message3.default.info("没有更多评论了");
          _this2.setState({
            isNoMoreComment: true
          });
        }
      }).catch(function (error) {
        if (error.response && error.response.data && error.response.data.msg) {
          _message3.default.error(_lang2.default[error.response.data.msg] || _constant.ERROR_DEFAULT);
          return;
        }
        _message3.default.error(_lang2.default[error.message] || _constant.ERROR_DEFAULT);
      }).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;

      _axios2.default.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(function (error) {
        if (error.response && error.response.data && error.response.data.msg) {
          _message3.default.error(_lang2.default[error.response.data.msg] || _constant.ERROR_DEFAULT);
          return;
        }
        _message3.default.error(_lang2.default[error.message] || _constant.ERROR_DEFAULT);
      }).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;

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

      (0, _axios2.default)(API + "/comments", {
        method: "post",
        data: {
          type: type,
          business_id: businessId,
          content: content
        },
        withCredentials: true
      }).then(function (response) {
        _message3.default.success("评论成功!");
        // 将数据写入到 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(function (error) {
        if (error.response && error.response.data && error.response.data.msg) {
          _message3.default.error(_lang2.default[error.response.data.msg] || _constant.ERROR_DEFAULT);
          return;
        }
        _message3.default.error(_lang2.default[error.message] || _constant.ERROR_DEFAULT);
      }).finally(function () {
        _this4.handleChangeLoading("sCreateComment", false);
      });
    }

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

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

      console.log("list: ", this.state.list);

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

      (0, _axios2.default)(API + "/replies", {
        method: "post",
        data: data,
        withCredentials: true
      }).then(function (response) {
        _message3.default.success("回复成功!");
        if ((0, _helper.isFunction)(cb)) cb();
        // 将数据写入到 list 中
        // 临时插入
        // 等到获取数据之后,删除临时数据
        var list = _this5.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;
        });
        _this5.setState({ list: list });
      }).catch(function (error) {
        if (error.response && error.response.data && error.response.data.msg) {
          _message3.default.error(_lang2.default[error.response.data.msg] || _constant.ERROR_DEFAULT);
          return;
        }
        _message3.default.error(_lang2.default[error.message] || _constant.ERROR_DEFAULT);
      }).finally(function () {
        _this5.handleChangeLoading("sCreateReply", false);
      });
    }

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

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

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

      (0, _axios2.default)(API + "/comments/" + commentId + "/favor", {
        method: favored ? "delete" : "put",
        withCredentials: true
      }).then(function (response) {
        _message3.default.success(favored ? "取消点赞成功!" : "点赞成功!");
        // 更新 list 中的该项数据的 favored
        var list = _this6.state.list.map(function (item) {
          if (item.id === commentId) {
            item.favored = !favored;
            item.favor_count += favored ? -1 : 1;
          }
          return item;
        });
        _this6.setState({ list: list });
      }).catch(function (error) {
        if (error.response && error.response.data && error.response.data.msg) {
          _message3.default.error(_lang2.default[error.response.data.msg] || _constant.ERROR_DEFAULT);
          return;
        }
        _message3.default.error(_lang2.default[error.message] || _constant.ERROR_DEFAULT);
      }).finally(function () {
        _this6.handleChangeLoading("sCommentFavor", false);
      });
    }

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

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

      this.handleChangeLoading("sReplyFavor", true);
      console.log("replyId, commentId ", replyId, commentId);

      var API = this.props.API;

      (0, _axios2.default)(API + "/replies/" + replyId + "/favor", {
        method: favored ? "delete" : "put",
        withCredentials: true
      }).then(function (response) {
        console.log("response: ", response);

        _message3.default.success(favored ? "取消点赞成功!" : "点赞成功!");
        // TODO: (2018.07.20 node) 对评论的回复点赞,报错
        // // 更新 list 中的该项数据的 favored
        // const list = this.state.list.map(item => {
        //   if (item.id === replyId) {
        //     item.favored = !favored;
        //     item.favor_count += favored ? -1 : 1;
        //   }
        //   return item;
        // });
        // this.setState({ list });
      }).catch(function (error) {
        if (error.response && error.response.data && error.response.data.msg) {
          _message3.default.error(_lang2.default[error.response.data.msg] || _constant.ERROR_DEFAULT);
          return;
        }
        _message3.default.error(_lang2.default[error.message] || _constant.ERROR_DEFAULT);
      }).finally(function () {
        _this7.handleChangeLoading("sReplyFavor", false);
      });
    }

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

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

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

      _axios2.default.get(API + "/oss/sts").then(function (response) {
        _this8.setState({ oss: _extends({}, response.data) });
      }).catch(function (error) {
        if (error.response && error.response.data && error.response.data.msg) {
          _message3.default.error(_lang2.default[error.response.data.msg] || _constant.ERROR_DEFAULT);
          return;
        }
        _message3.default.error(_lang2.default[error.message] || _constant.ERROR_DEFAULT);
      }).finally(function () {
        _this8.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
      });

      return _react2.default.createElement(
        _Comment.CommentContext.Provider,
        { value: value },
        _react2.default.createElement(
          "div",
          { className: "comment" },
          this.props.showHeader && _react2.default.createElement(
            "div",
            { style: { marginBottom: 15 } },
            _react2.default.createElement(
              _tag2.default,
              { className: "comment-header-tag" },
              "\u7559\u8A00"
            ),
            _react2.default.createElement(
              "span",
              { className: "comment-header-tip" },
              "\u53E3\u7891"
            ),
            _react2.default.createElement(
              "span",
              { className: "comment-header-text" },
              "(\u5168\u7AD9\u6311\u51FA\u6BDB\u75C5\u6216\u63D0\u51FA\u5408\u7406\u5EFA\u8BAE\uFF0C\u5956\u52B110\u5230100\u5143\u7EA2\u5305)"
            )
          ),
          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, // 是否显示评论输入框
  showHeader: _propTypes2.default.bool // 是否显示评论顶部的提示
};

App.defaultProps = {
  API: "http://api.links123.net/comment/v1",
  showList: true,
  showEditor: true,
  showHeader: true
};

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