import React, { useEffect, useState } from 'react';
import { Button, Popconfirm, Radio, Input, message, Tooltip, Spin, Pagination } from 'antd';
import axios from 'axios';
import { getImageUrl, timeAgo } from 'educoder';
import RenderHtml from '../../../../components/render-html';
import Attachment from '../../../Upload/attachment';
import EditComment from './editComment';
import Nodata from '../../../Nodata';
import CheckProfile from '../../../Component/ProfileModal/Profile';
import './list.scss';
import { Link } from 'react-router-dom';

function IssueCommentList(props){
  const{history, history: {location}, reload, reloadComment, showNotification, current_user:{login, admin, image_url, user_id}, isManager, showLoginDialog, issueInfo:{author}} = props;
  const {owner, projectsId, index} = props.match.params;
  const [category, setCategory] = useState('comment');
  const [journals, setJournals] = useState(undefined);
  // 是否展示新建/编辑评论markdown部分新建评论1 编辑父级评论2 回复评论3 编辑回复内容4 回复子机评论5
  const [showEdit, setShowEdit] = useState(false);
  const [parentId, setParentId] = useState(undefined);
  const [replyId, setReplyId] = useState(undefined);
  // 修改评论id
  const [updateId, setUpdateId] = useState(undefined);
  // 操作日志展开效果
  const [open, setOpen] = useState(undefined);
  // 加载中效果（缓冲css 线条效果）
  const [spin, setSpin] = useState(false);
  // issue 评论总数
  const [journalsCount, setJournalsCount] = useState(undefined);
  // 分页
  const limit = 50;
  const [page, setPage] = useState(1);
  const [totalCount, setTotalCount] = useState(undefined);
  // 操作记录 icon
  const journalsIcon ={
    'issue': 'icon-chuangjianqianbao',
    'branch_name': 'icon-fenzhi3',
    'assigner': 'icon-chengyuan2',
    'status_id': 'icon-xiugaibaobiaomoban',
    'fixed_version_id': 'icon-lichengbeiicon2',
    'due_date': 'icon-riqi',
    'issue_tag': 'icon-biaoji2',
    'description': 'icon-xiugaibaobiaomoban',
    'subject': 'icon-xiugaibaobiaomoban',
    'start_date': 'icon-riqi',
    'priority_id': 'icon-youxian',
    'attachment': 'icon-xiugaibaobiaomoban'
  }

  useEffect(()=>{
    setSpin(true);
    axios.get(`/v1/${owner}/${projectsId}/issues/${index}/journals`,{params:{
      category,
      page,
      limit
    }}).then(res=>{
      if(res && res.data){
        const {journals, total_comment_journals_count, total_count} = res.data;
        if(category === 'all'){
          const array = [];
          let start = undefined;
          let isJournalCount = 0;
          journals.map((item, index)=>{
            !isJournalCount && (start = index)
            item.is_journal_detail && (isJournalCount++)
            if(!item.is_journal_detail && isJournalCount < 10){
              isJournalCount = 0;
              return
            }
            if(isJournalCount >= 10 && (!item.is_journal_detail || journals.length-1 === index)){
              array.push({start, count: isJournalCount});
              isJournalCount = 0;
            }
          })
          array.map((item, i)=>{
            journals[item.start].numCount = item.count-1;
            for (let index = 0; index < item.count; index++) {
              journals[item.start+index].start = journals[item.start].id;
              journals[item.start+index].closeAndSpan = true;
            }
          })
        }
        setTotalCount(total_count);
        setJournalsCount(total_comment_journals_count);
        setJournals(journals);
        setSpin(false)
      }
    })
  }, [reload, category, page])

  function commentCtx(v){
    return <RenderHtml owner={owner} projectsId={projectsId} className="break_word_comments imageLayerParent commentRenderHtml" value={v} url={location}/>;
  };

  // 删除评论内容
  function deleteComment(id){
    axios.delete(`/v1/${owner}/${projectsId}/issues/${index}/journals/${id}`).then(res=>{
      if(res && res.data && !res.data.status){
        reloadComment();
        message.success('删除成功');
      }
    })
  }

  // markdown 取消操作
  function cancelMd(){
    setShowEdit(false);
  }

  return(
    <div className="commentListBox">
      {/* 全部 / 评论 / 操作日志 */}
      <div className={`${!login && journalsCount > 0 && 'pb15'}`}>
        <div className='typeActionBox mt30 mb20'>
          <Radio.Group onChange={(e)=>{setSpin(true);setPage(1);setCategory(e.target.value);history.push(history.pathname)}} value={category}>
            <Radio value={'comment'} className='typeActionRadio font-14'>评论<span className='journalsCount font-13 ml5'>{journalsCount}</span></Radio>
            <Radio value={'operate'} className='typeActionRadio font-14'>操作日志</Radio>
            <Radio value={'all'} className='typeActionRadio font-14'>全部</Radio>
          </Radio.Group>
        </div>
      </div>
      {/* 评论快速入口-仅有评论且登录时展示 */}
      {login && category !== 'operate' && journalsCount > 0 && <div className={`pb30 ${journalsCount > 0 && 'pt15'}`}><div className='gotoComment'>点击<a className='ml5' href='#addComments'>添加评论</a></div></div>}
      {/* 评论/操作日志 展示列表 */}
      <Spin spinning={spin}>
        <div className={`issueCommentsBox ${category === 'comment' && !spin && 'justComment'}`}>
          {journals && (journals.length > 0 && journals.map(item=>{return item.is_journal_detail ? (!item.closeAndSpan || item.id === item.start || open === item.start) ? <div key={item.id} className='operationLog'>
            {/* 操作日志 */}
            <div className='operationCommentBor'></div>
            <div className='flexCenter font-14' style={{width: '100%'}}>
              <div className='flexCenter opBox'>
                <span className='iconBackBox mr10'><i className={`iconfont font-12 ${journalsIcon[item.operate_category]}`}></i></span>
                <div className='task-hide' style={{maxWidth: item.closeAndSpan && item.id === item.start? '550px' : '700px'}}>
                  <Link to={`/${item.user.login}`}><img src={getImageUrl(item.user.image_url)} alt="" className='commentUserImg mr5'/></Link>
                  <Link to={`/${item.user.login}`}>{item.user.name}&nbsp;</Link>
                  {(item.user.name.length + item.operate_content.length) > 62 ? <Tooltip title={<div><span>{item.user.name} </span><span dangerouslySetInnerHTML={{__html:item.operate_content}}></span></div>}><span dangerouslySetInnerHTML={{__html:item.operate_content}}></span></Tooltip> : <span dangerouslySetInnerHTML={{__html:item.operate_content}}></span>}
                </div>
                <span className='ml15 timeAgo font-14'>{timeAgo(item.created_at)}</span>
              </div>
              {(item.closeAndSpan && item.id === item.start) && <a className='primaryColor' onClick={()=>{setOpen(open === item.id ? undefined : item.id)}}>{open === item.id ? `点击收起操作日志` : `已折叠${item.numCount}条, 点击查看`}<i className={`iconfont ${open === item.id ? `icon-sanjiaoxing-up` : 'icon-sanjiaoxing-down'} font-15`}></i></a>}
            </div>
          </div> : '' : <div key={item.id} className='commentContentBox pb30'>
            {/* 评论 */}
            <div className='commentOperationBor'></div>
            <Link to={`/${item.user.login}`}><img src={getImageUrl(item.user.image_url)} alt="" className='commentUserImg mr15'/></Link>
            <div className='commentContentRight'>
              {/* 判断是否是编辑状态 */}
              {(showEdit === 2 && updateId === item.id) ? <div className='mt15 mr20'><EditComment {...props} cancelMd={cancelMd} updateId={updateId} reloadComment={reloadComment} content={item.notes} defaultFileList={item.attachments} showUserImg={false}/></div> : <div>
                <div className='commentContent'>
                  <div className='flexCenter font-14'>
                    <div>
                      <Link to={`/${item.user.login}`}>{item.user.name}</Link>
                      <span className='ml15 timeAgo font-14'>{timeAgo(item.created_at)}</span>
                    </div>
                    {login && <div>
                      {/* 平台管理员/仓库管理员/发布评论者/issue创建者 */}
                      {(admin || isManager || login === item.user.login || user_id === author.id) && <Popconfirm
                        placement="bottom"
                        title={`确定要删除此条评论吗？${item.children_journals.length > 0 ? '子评论也将被一起删除。' : ''}`}
                        okText="是"
                        cancelText="否"
                        onConfirm={() => deleteComment(item.id)}
                      >
                        <Button type='link' className='color-grey-89'><i className='iconfont icon-fuzhi-shanchu font-14 mr8'></i>删除</Button>
                      </Popconfirm>}
                      {/* 仅评论者可修改 */}
                      {login === item.user.login && <Button type='link' className='color-grey-89' onClick={()=>{setUpdateId(item.id); setShowEdit(2)}}><i className='iconfont icon-a-bianji12 font-14 mr8'></i>修改</Button>}
                      <CheckProfile {...props} sureFunc={()=>{setParentId(item.id); setReplyId(item.id); setShowEdit(3)}}><Button type='link' className='color-grey-89'><i className='iconfont icon-a-xiaoxi1 font-14 mr8'></i>回复</Button></CheckProfile>
                    </div>}
                  </div>
                  <div className='contentHtml mb5'>{commentCtx(item.notes)}</div>
                  {item && item.attachments && item.attachments.length > 0 && <div className='attachmentBox mb5'><Attachment
                    attachments={item.attachments}
                    showNotification={showNotification}
                    canDelete={false}
                  /></div>}
                </div>
              </div>}
              {showEdit === 3 && replyId === item.id && <div className='contentHtml mr20'><EditComment {...props} cancelMd={cancelMd} parentId={parentId} replyId={replyId} reloadComment={reloadComment}/></div>}
              {/* 评论回复部分 */}
              {item.children_journals.map(i =>{return <div className='commentReply' key={i.id}>
                {(showEdit === 4 && updateId === i.id) ? <div className='mr20'><EditComment {...props} cancelMd={cancelMd} updateId={updateId} reloadComment={reloadComment} content={i.notes} defaultFileList={i.attachments}/></div> : <div>
                  <div className='flexCenter'>
                    <div>
                      <Link to={`/${i.user.login}`}><img src={getImageUrl(i.user.image_url)} alt="" className='commentUserImg mr8'/></Link>
                      <Link to={`/${i.user.login}`}>{i.user.name}</Link>
                      {i.reply_user && <span className='ml5 timeAgo mr3'>回复</span>}
                      <span>{i.reply_user && i.reply_user.name}</span>
                      <span className='ml15 timeAgo font-14'>{timeAgo(i.created_at)}</span>
                    </div>
                    {login && <div>
                      {/* 平台管理员/仓库管理员/发布评论者/回复评论者/issue创建者 */}
                      {(admin || isManager || login === i.user.login || (i.reply_user && login === i.reply_user.login) || user_id === author.id) && <Popconfirm
                        placement="bottom"
                        title={"确定要删除当前回复吗?"}
                        okText="是"
                        cancelText="否"
                        onConfirm={() => deleteComment(i.id)}
                      >
                        <Button type='link' className='color-grey-89'><i className='iconfont icon-fuzhi-shanchu font-14 mr8'></i>删除</Button>
                      </Popconfirm>}
                      {/* 仅回复评论者可修改 */}
                      {login === i.user.login && <Button type='link' className='color-grey-89' onClick={()=>{setUpdateId(i.id); setShowEdit(4)}}><i className='iconfont icon-a-bianji12 font-14 mr8'></i>修改</Button>}
                      <CheckProfile {...props} sureFunc={()=>{setParentId(item.id);setReplyId(i.id); setShowEdit(5)}}>
                        <Button type='link' className='color-grey-89'><i className='iconfont icon-a-xiaoxi1 font-14 mr8'></i>回复</Button>
                      </CheckProfile>
                    </div>}
                  </div>
                  <div className='contentHtml mt5 mb10'>{commentCtx(i.notes)}</div>
                  {i && i.attachments && i.attachments.length > 0 && <div className='attachmentBox'><Attachment
                    attachments={i.attachments}
                    showNotification={showNotification}
                    canDelete={false}
                  /></div>}
                </div>}
                {showEdit === 5 && replyId === i.id && <div className='contentHtml mr20'><EditComment {...props} cancelMd={cancelMd} parentId={parentId} replyId={replyId} reloadComment={reloadComment}/></div>}
              </div>})}
            </div>
          </div>}))}
        </div>
      </Spin>
      {totalCount>limit && <div className='mt20 paginationIssueComment mb20'>
        <Pagination simple current={page} pageSize={limit} total={totalCount} onChange={(page)=>setPage(page)}/>
      </div>}
      {/* 添加评论 */}
      {category !== 'operate' && <div className="pb30" style={{marginTop: journalsCount ? '-5px' : '30px'}}>
        {login ? showEdit === 1 ? <EditComment {...props} cancelMd={cancelMd}/> : <div className="addComments" id='addComments'>
          <img src={getImageUrl(image_url)} alt="" />
          <div style={{flex:1}}>
            <CheckProfile {...props} sureFunc={()=>{setShowEdit(1)}}>
              <Input className='addCommentBox' placeholder="添加评论"/>
            </CheckProfile>
          </div>
        </div> : <div className='unLoginComment font-15 pl20'>
          {/* 未登录用户 */}
          <a className='mr5 loginBtn' onClick={()=>{showLoginDialog()}}>登录</a>并参与评论与回复
        </div>}
      </div>}
    </div>
  )
}
export default IssueCommentList;