import React, { Component } from "react";
import { Link } from "react-router-dom";

import axios from "axios";
import { getImageUrl } from "educoder";
import { List, Popconfirm, Pagination, Button } from "antd";
import Attachments from "../Upload/attachment";
import RenderHtml from "../../components/render-html";
import "../Order/order.css";

class children_comments extends Component {
  constructor(props) {
    super(props);
    this.state = {
      journalsdata: undefined,
      limit: 10,
      page: 1,
      journal_spin: false,
      search_count: 0,
      isSpin: false,
    };
  }

  componentDidMount() {
    this.getChildrenJournals();
  }
  componentDidUpdate(prevProps, prevState) {
    if (this.props.children_comment_id) {
      if (prevProps.children_comment_id !== this.props.children_comment_id)
        this.getChildrenJournals();
    }
  }
  //获取评论信息
  getChildrenJournals = (i_order_id, i_parentId) => {
    const { order_id, parent_id } = this.props;
    const { page, limit } = this.state;
    let new_order_id = i_order_id ? i_order_id : order_id;
    let new_parent_id = i_parentId ? i_parentId : parent_id;
    const url = `/issues/${new_order_id}/journals/${new_parent_id}/get_children_journals.json`;
    axios
      .get(url, {
        params: {
          page,
          limit,
        },
      })
      .then((result) => {
        if (result) {
          this.setState({
            journalsdata: result.data,
            search_count: result.data.journals_count,
            isSpin: false,
          });
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  //删除评论
  deleteorder = (id) => {
    const { order_id } = this.props;
    const url = `/issues/${order_id}/journals/${id}.json`;
    axios
      .delete(url, {
        data: {
          issue_id: order_id,
          id: id,
        },
      })
      .then((result) => {
        if (result) {
          this.getChildrenJournals();
          // 删除回复后，如果需手动调用父组件查询评论列表的接口，以保持角标（评论数量）的一致（合并请求页面），
          // 否则直接查顶级评论列表，否则只查询当前子评论列表（易修页面）
          this.props.refreshCommentList && this.props.refreshCommentList();
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // 翻页
  ChangePage = (page) => {
    // this.state.page = page;
    // this.state.isSpin = true;
    // 使用回调的写法，这样在getChildrenJournals中使用的就是最新的state
    this.setState({
      page,
      isSpin: true
    }, () => {
      this.getChildrenJournals();
    });
  };

  commentCtx = (v) => {
    return <RenderHtml className="break_word_comments imageLayerParent" value={v} url={this.props.history.location}/>;
  };

  Paginations =()=> {
    const { page, limit, search_count } = this.state;
    if(search_count > limit){
      return(
        <div className="pt30 mb50 edu-txt-center btp1">
          <Pagination
            simple
            defaultCurrent={page}
            total={search_count}
            pageSize={limit}
            onChange={this.ChangePage}
          ></Pagination>
        </div>
      )
    }
  }

  renderList = (item) => {
    const { current_user } = this.props;

    return (
      <div className="width100">
        <div className="grid-item pb5">
          <Link
            to={`/${item && item.user_login}`}
            className="show-user-link"
          >
            <img
              className="radius"
              src={getImageUrl(`/${item && item.user_picture}`)}
              alt=""
              width="30"
              height="30"
            />
          </Link>
          <Link
            to={`/${item && item.user_login}`}
            className="show-user-link color-black ml10 fwb"
          >
            {item && item.user_name}
          </Link>
        </div>
        <div className="ml40">
          {this.commentCtx(item.content)}
          {item && item.attachments && item.attachments.length > 0 ? (
            <Attachments
              attachments={item.attachments}
              showNotification={this.props.showNotification}
              canDelete={
                current_user &&
                (current_user.admin || current_user.login === item.user_login)
              }
            />
          ) : (
            ""
          )}
          <div className="mt5">
              <span className="color-grey-8">{item.created_at}</span>
              <span className="ml20">
                {current_user &&
                (current_user.admin ||
                  current_user.login === item.user_login) ? (
                  <Popconfirm
                    placement="bottom"
                    title={"确定要删除当前评论吗?"}
                    okText="是"
                    cancelText="否"
                    onConfirm={() => this.deleteorder(item.id)}
                  >
                    <Button type="link">
                    <i className="iconfont icon-shanchu3 font-15 color-grey-6 mr5 ver-middle"></i>
                    <span className="font-12 color-grey-6">删除</span>
                    </Button>
                  </Popconfirm>
                ) : (
                  ""
                )}
              </span>
            </div>
        </div>
      </div>
    );
  }

  render() {
    const { journalsdata , search_count , isSpin } = this.state;
    return (
      <div>
        {search_count > 0 && (
          <div className="children-comment-bg mt10">
            <List
              size="large"
              loading={isSpin}
              dataSource={journalsdata.issue_journals}
              renderItem={(item) => <List.Item key={item.id}>{this.renderList(item)}</List.Item>}
            />
            {this.Paginations()}
          </div>
        )}
      </div>
    );
  }
}

export default children_comments;
