import React, { useState, useEffect } from "react";
import RenderHtml from "../../components/render-html";
import { Popconfirm, Button, message } from "antd";
import { Link } from "react-router-dom";
import NewComment from "./new_comment";
import { getImageUrl } from "educoder";
import axios from "axios";
import ChildrenJournals from "./children_journals";
function comment_list({
  item,
  user_image,
  current_login,
  is_children,
  target_type,
  commet_destroy,
  props
}) {
  const [is_reply, setIsReply] = useState(false);
  const [is_delete, setIsDelete] = useState(false);
  const [deleteSpin, setDeleteSpin] = useState(false);
  const [subComments, setSubComments] = useState([]);
  const [subCommentsCount, setSubCommentsCount] = useState(0);
  const [page, setChangePage] = useState(1);
  const [is_praise, setIsPraise] = useState(false);
  const [praisesCont, setPraisesCount] = useState(0);
  const [isSpin, setIsSpin] = useState(false);
  const [limit, setLimit] = useState(5);
  useEffect(() => {
    setSubComments(item.children);
    if (item.children) {
      setSubCommentsCount(item.children.length);
    }else{
      setSubCommentsCount(0);
    }
    setIsPraise(item.user_praise);
    setPraisesCount(item.praise_count);
  }, [item]);
  const is_reply_click = (reply_boolean) => {
    if (current_login) {
      setIsReply(reply_boolean);
    } else {
      props.showLoginDialog();
      return;
    }
  };

  const praise_reply = (id) => {
    if (current_login) {
      axios
        .post(`/memos/${id}/plus.json`, {
          container_type: "Memo",
          id: id,
          type: is_praise ? 0 : 1,
        })
        .then((result) => {
          setPraisesCount(result.data.praise_count);
          setIsPraise(!is_praise);
          message.success(is_praise ? "取消点赞" : "已点赞")
        })
        .catch((error) => {
          message.error(error);
        });
    } else {
      props.showLoginDialog();
      return;
      // window.open("/login", "_blank");
    }
  };

  function deleteorder(id) {
    setDeleteSpin(true);
    let url = `/memos/${id}.json`;
    axios
      .delete(url)
      .then((result) => {
        if (result) {
          if (result.data.status === 0) {
            setIsDelete(true);
            if (is_children) {
              setSubCommentsCount(subCommentsCount - 1);
            } else {
              commet_destroy();
            }
            message.success(result.data.message);
          } else {
            message.error(result.data.message);
          }
        }
        setDeleteSpin(false);
      })
      .catch((e) => {
        setDeleteSpin(false);
        message.error(e);
      });
  }
  const create_new_children = (reply) => {
    if (subComments && subComments.length > 0) {
      setSubComments([reply, ...subComments]);
    } else {
      setSubComments([reply]);
    }
    setSubCommentsCount(subCommentsCount + 1);
    setIsReply(false);
  };

  function get_more_reply(id) {
    let new_page = page;
    if (subCommentsCount < limit) {
      setChangePage(1);
      new_page = 1;
    } else {
      new_page = page + 1;
      setChangePage(new_page);
    }
    setIsSpin(true);
    let url = `/${target_type}/${id}/more_reply.json`;
    axios
      .get(url, {
        params: { page: new_page, limit },
      })
      .then((result) => {
        if (result && result.data.memo_replies) {
          setSubComments(subComments.concat(result.data.memo_replies));
        }
        setIsSpin(false);
      })
      .catch((e) => {
        setIsSpin(false);
        message.error(e);
      });
  }

  return (
    <div className="width100">
      {is_delete ? (
        <div className="pd20 edu-text-center">已删除</div>
      ) : (
        <div>
          <div className="pb5">
            <Link
              to={`/accounts/${item && item.user_login}`}
              className="show-user-link"
            >
              <img className="user-image" src={getImageUrl(item.image_url)} />
            </Link>
            <Link
              to={`/accounts/${item && item.user_login}`}
              className="show-user-link color-black ml10 fwb"
            >
              {item && item.username}
            </Link>
          </div>
          <div className="ml40">
            {item.content && (
              <RenderHtml className="tipsContent" value={item.content} />
            )}
            <div className="grid-item-left mt5">
              <span className="color-grey-8">{item.time}</span>
              <div className="text-right grid-item-3">
                {item.admin || current_login === item.user_login ? (
                  <Popconfirm
                    placement="bottom"
                    title={"确定要删除当前评论吗?"}
                    okText="是"
                    cancelText="否"
                    onConfirm={() => deleteorder(item.id)}
                  >
                    <Button type="link" loading={deleteSpin}>
                      <i className="iconfont icon-shanchu font-14 color-grey-8 mr5 ver-middle"></i>
                      <span className="font-14 color-grey-8 ver-middle">删除</span>
                    </Button>
                  </Popconfirm>
                ) : (
                  ""
                )}
                {!is_children && (
                  <Button
                    type="link"
                    className="ml-10"
                    onClick={() => {
                      praise_reply(item.id);
                    }}
                  >
                    {is_praise ? (
                      <i class="iconfont icon-dianzan color-green font-14 mr5 ver-middle"></i>
                    ) : (
                      <i class="iconfont icon-dianzan-xian font-14 color-grey-8 mr5 ver-middle"></i>
                    )}
                    <span className="font-14 color-grey-8 ver-middle">
                      {praisesCont}
                    </span>
                  </Button>
                )}
                {!is_children && (
                  <Button
                    type="link"
                    className="ml-10"
                    onClick={() => {
                      is_reply_click(true);
                    }}
                  >
                    <i className="iconfont icon-pinglun1 font-14 color-grey-8 mr5 ver-middle"></i>
                    <span className="font-14 color-grey-8 ver-middle">
                      {subCommentsCount}
                    </span>
                  </Button>
                )}
              </div>
            </div>
            {is_reply && !is_children && (
              <NewComment
                memo_id={item.id}
                user_image={user_image}
                click_button={is_reply_click}
                new_reply={create_new_children}
              ></NewComment>
            )}
            {subComments && subCommentsCount > 0 && (
              <ChildrenJournals
                replies={subComments}
                user_image={user_image}
                current_login={current_login}
              ></ChildrenJournals>
            )}
            {item &&
              subComments &&
              item.replies_count > subCommentsCount &&
              item.replies_count >= page * limit && (
                <div className="mt10 edu-text-center">
                  <Button
                    loading={isSpin}
                    type="success"
                    onClick={() => get_more_reply(item.id)}
                  >
                    查看更多回复
                  </Button>
                </div>
              )}
          </div>
        </div>
      )}
    </div>
  );
}
export default comment_list;
