
import React, { Component } from 'react';
import { Pagination , Spin } from 'antd';

import '../exchange.css'
import './post.css'

import Nav from '../NavComponent/Index'
import Parse from './Parse';
import ExchangeItem from '../ExchangeItem'

import CommentsIndex from './CommentsIndex';
import CommentsSend from '../Comments/CommentsSend';
import RenderHtml from "../../components/render-html";

import FileList from '../../common/FileList';

import update from 'immutability-helper'

import axios from 'axios';

class Index extends Component{
  constructor(props){
    super(props);
    this.state={
      // 当前用户是否点赞
      judge:true,
      parseNum:0,
      // 帖子用户信息
      author_info:undefined,
      // 当前用户信息
      current_user:undefined,
      // 面包屑
      bread_crumb:undefined,
      // 当前帖子详情
      memos:undefined,
      // 帖子评论
      repliesData:undefined,
      //  帖子评论分页相关
      replyPage:1,
      replyPageSize:10,
      replyCount:0,
      is_Spin:true
    }
  }

  componentDidMount = () =>{
    this.getInfo();
  }

  getInfo=()=>{
    this.InitDetailInfo();
    this.getReply(1);
  }
  
  InitDetailInfo = ()=>{
    let postid = this.props.match.params.postid;
    const url = `/memos/${postid}.json`;
    axios.get(url).then((result)=>{
      if(result.data && result.data.status === -1){
        this.props.history.push("/forums");
      }
      if(result){
        this.setState({
          judge:result.data.memo.user_praise,
          parseNum:result.data.memo && result.data.memo.praises_count,
          author_info:result.data.author_info,
          current_user:result.data.current_user,
          bread_crumb:result.data.bread_crumb,
          memos:result.data.memo,
          is_Spin:false
        })
      }
    }).catch((error)=>{

    })
  }

  getReply = (replyPage) =>{
    let postid = this.props.match.params.postid;
    const url = `/memos/${postid}/more_reply.json`;
    axios.get(url,{params:{
      page:replyPage
    }}).then((result)=>{
      if(result){
        this.setState({
          repliesData:result.data.memo_replies,
          replyCount:result.data.memos_count,
          is_Spin:false
        })
      }
    }).catch((error)=>{

    })
  }

  // 点赞
  thumbForum = () =>{
    let postid = this.props.match.params.postid;
    const url = `/discusses/${postid}/plus.json`
    axios.post(url,{
      container_type:'Memo',
      type:1
    }).then((result)=>{
      if(result){
        this.InitDetailInfo();
      }
    }).catch((error)=>{

    })
  }

  //  切换评论分页
  changeReplyEvent=(pageNumber)=>{
    this.setState({
      replyPage:pageNumber
    })
    this.getReply(pageNumber);
  }

  // 点击显示评论输入框
  commentReplyEvent=(index,flag)=>{
    console.log("2",flag);

    this.setState(
      (prevState) => ({ 
        repliesData : update(prevState.repliesData, {[index]: { commentsFlag: {$set: flag} }}),
      })
    )
  }

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

    })
  }

  render(){
    let { 
      judge , parseNum , author_info , current_user , bread_crumb , memos , repliesData ,
      replyPage,
      replyPageSize,
      replyCount,
      is_Spin
    } = this.state;
    let postid = this.props.match.params.postid;

    const NavMap=[
      {
        url:`/users/${current_user && current_user.login}`,
        name:current_user && current_user.username
      },
      {
        url:"/forums",
        name:bread_crumb && bread_crumb.forum && bread_crumb.forum.title
      },
      {
        url:`/forums/theme/${bread_crumb && bread_crumb.forum_tag && bread_crumb.forum_tag.id}`,
        name:bread_crumb && bread_crumb.forum_tag && bread_crumb.forum_tag.title
      },
      {
        name:"帖子详情"
      }
    ]

  //插入字段从author_info表内选取
    const memos_list = [{
      ...memos,
      image_url:author_info && author_info.image_url,
      username:author_info && author_info.username,
      user_login:author_info && author_info.login
    }]; 

    // 评论列表
    const memo_replies = repliesData;
    const repliesList = (
      memo_replies && memo_replies.length > 0 &&
      <div className="commentsForm">
        <p className="replyTitle">
          <span className="font-24 color-grey-3 mr20">全部回复</span>
          <span className="color-grey9 font-20">{replyCount}</span>
        </p>
        <CommentsIndex {...this.props} {...this.state} refresh={this.getReply} page={replyPage} showCommentEvent={this.commentReplyEvent}></CommentsIndex>
      </div>
    )

    // 附件显示
    const fileListCom = ( memos && memos.attachment_url && <FileList list = { memos.attachment_url } className="fileTeam"></FileList> )

    return(
      <Spin spinning={is_Spin}>
        <div className="educontent">
          <Nav className="mt20 mb20" NavMap = {NavMap}></Nav>

          <div className="educontent-min bc-white mb30">

            {/* 调用和首页共用的列表item，传了enshine就代表底部右侧操作按钮只有收藏或者取消收藏，否则就是置顶、推荐等 */}
            <ExchangeItem 
              {...this.props} 
              {...this.state} 
              memos={memos_list} 
              current_user = { current_user }
              detail={true}
              refresh={this.getInfo}
            ></ExchangeItem>

            <div className="postContent">
              {/* 帖子详情 */}
              <RenderHtml className="postDetail" value={memos && memos.content} />
              {/* 文件列表 */}
              { fileListCom }

              {/* 点赞 */}
              <div className="edu-txt-center pb40">
                <Parse judge={!judge}  current_user = { current_user }  num = {parseNum} clickEvent = { this.thumbForum }></Parse>
              </div>

              {/* 发送评论部分 */}
              {
                current_user && (current_user.is_banned === false || current_user.admin) &&
                <CommentsSend unique={`main_Send`} id={postid} refresh={()=>this.getReply(replyPage)}/>
              }
              {/* 评论列表 */}
              { repliesList }
            </div>
          </div>
          {
            replyCount && replyCount > replyPageSize ? 
            <div className="edu-txt-center mb50">
              <Pagination showQuickJumper current={replyPage} pageSize={replyPageSize} total={replyCount} onChange={this.changeReplyEvent}></Pagination>
            </div>:""
          }
          
        </div>
      </Spin>
    )
  }
}

export default Index;