import React, { Component } from "react";
import PropTypes from "prop-types";
import { Avatar, Icon, Tooltip, Popconfirm } from "antd";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
// import 'dayjs/locale/es';
import relativeTime from "dayjs/plugin/relativeTime";
import intl from "react-intl-universal";
import Comment from "../../Comment";
import CommentInput from "../CommentInput";
import avatar from "../../avatar";
import { renderContent } from "../../helper";
import { IMAGE_SPLIT } from "../../constant";
import "./index.css";
import ImagePreviewer from "../ImagePreviewer/ImagePreviewer";

// dayjs.locale("zh-cn");
dayjs.extend(relativeTime);

const LOCALES = {
  "zh-CN": "zh-cn"
};

class CommentItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showInput: false,
      showPreviewer: false,
      previewerIndex: 0
    };
    this.handleToggleInput = this.handleToggleInput.bind(this);
    this.renderTextWithReply = this.renderTextWithReply.bind(this);
    this.showPreviewer = this.showPreviewer.bind(this);
    this.hidePreviewer = this.hidePreviewer.bind(this);
  }

  showPreviewer(index) {
    this.setState({
      showPreviewer: true,
      previewerIndex: index
    });
  }

  hidePreviewer() {
    this.setState({
      showPreviewer: false
    });
  }

  handleToggleInput() {
    this.setState({ showInput: !this.state.showInput });
  }

  renderTextWithReply(text, content) {
    let newText = text;
    const { reply } = content;
    if (reply) {
      // newText = `${newText} //@<a href="/${reply.user_id}">${
      //   reply.user_name
      // }</a> ${reply.content}`;
      newText = `${newText} //@${reply.user_name} ${reply.content}`;
      // newText = (
      //   <span>
      //     {newText}
      //     @<a href={`/${reply.user_id}`}>{reply.user_name}</a>{reply.content}
      //   </span>
      // )
      if (reply.reply) {
        return this.renderTextWithReply(newText, reply);
      }
    }
    return newText;
  }

  render() {
    const {
      commentId,
      replyId,
      content,
      action,
      showReply,
      onShowReply,
      app
    } = this.props;

    const { locale } = this.props.app;
    console.log("locale is", locale);
    const { showInput } = this.state;

    let newContent = content.content;
    let images = "";
    if (newContent.indexOf(IMAGE_SPLIT) !== -1) {
      newContent = newContent.split(IMAGE_SPLIT);
      images = newContent.pop();
      newContent = newContent.join("");
    }

    const imageList = images.split(",");

    // 在3, 7前需要换行
    const needClear =
      imageList.length === 5 ||
      imageList.length === 6 ||
      imageList.length === 9;
    const imgs = [...imageList];
    if (needClear) {
      if (imgs.length > 6) {
        imgs.splice(3, 0, { type: "divider" });
        imgs.splice(7, 0, { type: "divider" });
      } else {
        imgs.splice(3, 0, { type: "divider" });
      }
    }

    return (
      <div className="comment-item-box">
        <div className="comment-item-left">
          <Avatar src={content.user_avatar || avatar} size="large" />
        </div>
        <div className="comment-item-right">
          <div>
            {/* <a href={`/${content.user_id}`}>
              {content.user_name || "暂无昵称"}
            </a> */}
            <strong>{content.user_name || intl.get("comment.tourist")}</strong>
            <span style={{ marginLeft: 10 }}>
              <Tooltip
                placement="top"
                title={dayjs(content.created * 1000).format(
                  "YYYY-MM-DD HH:mm:ss"
                )}
              >
                {LOCALES[locale]
                  ? dayjs(content.created * 1000)
                      .locale(LOCALES[locale])
                      .fromNow()
                  : dayjs(content.created * 1000).fromNow()}
              </Tooltip>
            </span>
          </div>
          <div
            className="comment-item-content"
            dangerouslySetInnerHTML={{
              __html: renderContent(
                this.renderTextWithReply(newContent, content)
              )
            }}
          />
          {// image为空时不渲染comment-item-image
          imageList.length > 0 && imageList[0] !== "" && (
            <div className="comment-item-image">
              {!this.state.showPreviewer &&
                imgs.map((item, index) => {
                  if (item.type === "divider") {
                    return (
                      <div className="comment-item-image-wrapper" key={index}>
                        <div className="comment-img-divider" />
                        {/* <img src={item} alt={item} className="comment-img" /> */}
                      </div>
                    );
                  }
                  return (
                    <div
                      className="comment-item-image-wrapper"
                      key={index}
                      onClick={() => {
                        let i = index;
                        if (needClear) {
                          if (index > 3) {
                            i -= 1;
                          }
                          if (index > 7) {
                            i -= 1;
                          }
                        }
                        this.showPreviewer(i);
                      }}
                    >
                      <div
                        style={{ backgroundImage: `url(${item})` }}
                        className="comment-img-thumbnail"
                      />
                      {/* <img src={item} alt={item} className="comment-img" /> */}
                    </div>
                  );
                })}
              {this.state.showPreviewer && (
                <ImagePreviewer
                  list={imageList}
                  index={this.state.previewerIndex}
                  onFold={this.hidePreviewer}
                />
              )}
              <div className="clearfix" />
            </div>
          )}
          <div className="comment-item-bottom">
            {content.reply_count ? (
              <div>
                <a className="comment-item-bottom-left" onClick={onShowReply}>
                  {/* {content.reply_count} 条回复 */}
                  {intl.get("reply.totalReply", { total: content.reply_count })}
                  {showReply ? <Icon type="up" /> : <Icon type="down" />}
                </a>
              </div>
            ) : null}
            {app.userId === content.user_id && (
              <Popconfirm
                // title="确定要删除吗?"
                title={intl.get("popConfirm.title")}
                onConfirm={() => {
                  if (replyId) {
                    app.sDeleteReply(content.id, commentId);
                    return;
                  }
                  app.sDeleteComment(content.id);
                }}
                okText={intl.get("popConfirm.ok")}
                cancelText={intl.get("popConfirm.cancel")}
              >
                <a className="comment-item-bottom-right">
                  &nbsp; {intl.get("popConfirm.delete")}
                </a>
              </Popconfirm>
            )}
            <a
              onClick={this.handleToggleInput}
              className="comment-item-bottom-right"
            >
              &nbsp; {intl.get("comment.reply")}
            </a>
            <div
              className="comment-item-bottom-right"
              onClick={() => {
                if (replyId) {
                  // 如果有 replyId，则说明是评论的回复
                  app.sReplyFavor(content.id, commentId, content.favored);
                  return;
                }
                app.sCommentFavor(content.id, content.favored);
              }}
            >
              <Icon
                type="like-o"
                className={
                  content.favored
                    ? "comment-favor comment-favored"
                    : "comment-favor"
                }
              />
              &nbsp;{content.favor_count}
            </div>
          </div>
        </div>

        {showInput && (
          <CommentInput
            content={app.children}
            action={action}
            replyId={replyId}
            commentId={commentId}
            callback={this.handleToggleInput}
          />
        )}
      </div>
    );
  }
}

CommentItem.propTypes = {
  content: PropTypes.object.isRequired,
  // comment 评论
  // reply 评论的回复
  // replyToReply 回复的回复
  action: PropTypes.oneOf(["comment", "reply", "replyToReply"]),
  onShowReply: PropTypes.func
};

CommentItem.defaultProps = {
  action: "comment",
  onShowReply: () => {}
};

export default Comment(CommentItem);
