import React, { Component } from "react";
import PropTypes from "prop-types";
import { IMAGE_SPLIT } from "../../constant";
import Comment from "../../Comment";

class CommentInput extends Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  /**
   * 提交评论
   * @param {object} { text<string>, files<array> } 需要提交的评论的文本和图片
   * @param {function} cb 提交成功后的回掉
   */
  handleSubmit({ text, files }, cb) {
    let value = text;
    if (files && files.length) {
      value += IMAGE_SPLIT;
      files.forEach(file => {
        value += `${file},`;
      });
    }
    if (value.substr(-1) === ",") {
      value = value.slice(0, -1);
    }

    const { action, commentId, replyId, callback } = this.props;
    if (action === "comment") {
      this.props.app.sCreateComment(
        {
          content: value
        },
        cb
      );
    } else if (action === "reply") {
      this.props.app.sCreateReply(
        {
          comment_id: commentId,
          content: value
        },
        () => callback && callback()
      );
    } else if (action === "replyToReply") {
      this.props.app.sCreateReply(
        {
          comment_id: commentId,
          content: value,
          reply_id: replyId
        },
        () => callback && callback()
      );
    }
  }

  render() {
    const childrenWithProps = React.Children.map(this.props.content, child => {
      return React.cloneElement(child, {
        // 编辑器本身不提交值，但 CommentInput 会提交
        // CommentInput 主要是负责评论的业务逻辑，提交评论和回复
        // 默认使用 CommentInput 的 onSubmit 来提交评论
        // 但也可以使用 Editor 的 props 来覆盖 onSubmit
        onSubmit: this.handleSubmit,
        ...child.props,
        // 如果当前的编辑器不是“评论”，则编辑器高度减小一些
        rows:
          this.props.action === "comment"
            ? child.props.rows
            : child.props.rows - 1
      });
    });

    return <div>{childrenWithProps}</div>;
  }
}

CommentInput.propTypes = {
  // comment 评论
  // reply 评论的回复
  // replyToReply 回复的回复
  action: PropTypes.oneOf(["comment", "reply", "replyToReply"])
};

CommentInput.defaultProps = {
  action: "comment"
};

export default Comment(CommentInput);
