import React, { PureComponent } from 'react';
import './post.css'
import Item from '../Comments/CommentsItem'
import ItemImg from '../Comments/CommentsItemImg'
import axios from 'axios';

import CommentsSend from '../Comments/CommentsSend';



class CommentsIndex extends PureComponent{

  // 调用父组件的刷新方法
  refreshReply=()=>{
    let { refresh , page} = this.props;
    refresh(page);
  }

  // 删除评论
  deleteReplyEvent=(id)=>{
    const url = `/memos/${id}/destroy.json`
    axios.post(url).then((result)=>{
      if(result){
        this.props.showNotification(result.data.message);
        this.refreshReply();
      }
    }).catch((error)=>{

    })
  }

  commentReplyEvent=(index,flag)=>{
    console.log("1",flag);
    this.props.showCommentEvent(index,true);
  }

  

  // 点赞评论
  praiseEvent=(id)=>{
    const url = `/discusses/${id}/plus.json`;
    axios.post(url,{
      container_type:'Memo',
      type:1
    }).then(result=>{
      if(result){
        this.refreshReply();
      }
    }).catch(error=>{

    })
  }

  parseCommentContent = (oldContent) => {
		if (oldContent && oldContent.startsWith('<') && oldContent.endsWith('>')) {
		} else if (window.$('#md_div').length) {	// 有这个临时处理md内容的dom
			window.$('#md_div').html('')
			// markdown to html
			try {	
				var markdwonParser = window.editormd.markdownToHTML("md_div", {
          markdown: oldContent,
          emoji: true,
          htmlDecode: "style,script,iframe",  // you can filter tags decode
          taskList: true,
          tex: true,  // 默认不解析
          flowChart: true,  // 默认不解析
          sequenceDiagram: true // 默认不解析
        });
				oldContent = window.$('#md_div').html()
			} catch (e) {
				// TODO 可能公式parse时报错了
				console.error(e)
			}
		}
		return oldContent;
	}

  render(){
    // 评论列表，当前用户信息 
    const { repliesData , current_user , page } = this.props;
    const renderNum = (arrs,flag) =>{
      return(<p>展开其余1条评论</p>)
    }

    //二级评论
    const renderChild = (arrs) => {
      return(
        <div className="">
        {
          arrs.map((child)=>{
            return(
              <div className="commentsItem_infos">
                <ItemImg image_url={child.image_url} ></ItemImg>
                <div className="flex1">
                  <Item image_url={child.image_url} username={child.username} time={child.time} content={child.content} id={child.id}></Item>
                </div>
              </div>
            )
          })
        }
        </div>
      )
    }

    const replyInfoWrap = (i,index)=> (
      <React.Fragment>
        <p className="edu-txt-right color-grey-6">
          <span className={ i.user_praise ? "ml30":"ml30 c_point"} onClick={ i.user_praise ? undefined : ()=>this.praiseEvent(i.id)}>
            <i className={ i.user_praise ? "iconfont icon-dianzan color-grey-9 font-16 mr5" : "iconfont icon-dianzan-xian color-grey3 font-16 mr5"}></i>
            <span>{i.praise_count}</span>
          </span>
          {
            current_user && (current_user.is_banned === false || current_user.admin) && 
            <span className="ml30 c_point" onClick={()=>this.commentReplyEvent(index,i.commentsFlag)}>
              <i className="iconfont icon-pinglun color-grey-9 font-16 mr5"></i><span>{i.replies_count}</span>
            </span>
          }
        </p>
        {
          i.commentsFlag && 
          <CommentsSend unique={`sub_${i.id}`} id={i.id} image_url={current_user && current_user.image_url} refresh={this.refreshReply}/>
        }
      </React.Fragment>
    )

    // 判断是否是管理员或者版主
    const manage = current_user && (current_user.admin || current_user.banned_permission);
    const itemMap = repliesData && repliesData.map((i,index)=>{
      let _content = this.parseCommentContent(i.content);
      return(
        <div className="pre_stage" key={index}>
          <div className="commentsItem_infos">
            <ItemImg image_url={i.image_url} ></ItemImg>
            <div className="flex1">
              <Item username={i.username} time={i.time} content={_content} id={i.id} admin={manage} deleteReplyEvent={this.deleteReplyEvent}></Item>
              {
                i.children && i.children.length > 0 &&
                <div className="sub_stage">
                  {renderChild(i.children)}
                  {/* { i.children.length > 1 && renderNum(i.children)} */}
                </div>
              }

              {replyInfoWrap(i,index)}
            </div>
          </div>
        </div>
      )
    })

    return( itemMap )
  }
}

export default CommentsIndex;