import React, { useEffect, useState, useCallback } from 'react';
import { Pagination, Modal, Form, Input, Button } from 'antd';
import ReactWEditor from 'wangeditor-for-react';
import { timeAgo, getImageUrl } from 'educoder';
import Nodata from 'forge/Nodata';
import Loading from "src/Loading";
import { editorConfig } from 'military/components/config';
import AgreementModal from '../agreementModal';
import ComplainModal from '../complainModal';
import { reportPaper, thumbUpPaper, commentAdd, confirmReceipt } from '../../api';
import { paperCheckStatusArr } from '../../static';
import { httpUrl } from '../../fetch';
import winpng from '../../image/winner.png';
import win1 from '../../image/win1.svg';
import win2 from '../../image/win2.svg';
import win3 from '../../image/win3.svg';
import './index.scss';

const { TextArea } = Input;

const paperCheckStatus = [];
for (const item of paperCheckStatusArr) {
  paperCheckStatus[item.dicItemCode] = item.dicItemName;
}

export default Form.create()((props) => {
  const { list, curPage, total, changePage, loading, applyStatusAllNameArr, reloadList, showNotification, current_user, form, detailStatus, expertReview } = props;
  const { getFieldDecorator, validateFields, setFieldsValue } = form;
  const [page, setPage] = useState(1);
  const pageSize = props.pageSize || 10;
  const [checkedItem, setCheckedItem] = useState({});
  const [reportVisible, setReportVisible] = useState(false);
  const [commentHtml, setCommentHtml] = useState('');

  const [commentId, setCommentId] = useState(undefined);

  const [complainVisible, setComplainVisible] = useState(false);
  const [agreeVisible, setAgreeVisible] = useState(false);


  const [loadingChild, setLoadingChild] = useState(false);


  useEffect(() => {
    changePage(page);
  }, [page]);

  function downFile(item) {
    let url = httpUrl + '/busiAttachments/download/' + item.id;
    window.open(url);
  }

  function report() {
    validateFields((error, values) => {
      if (!error) {
        setLoadingChild(true);
        reportPaper({
          paperId: checkedItem.id,
          content: values.reportValue
        }).then(res => {
          if (res && res.message === 'success') {
            showNotification('举报成功');
            setReportVisible(false);
            setFieldsValue({
              reportValue: '',
              complainValue: '',
            });
          }
          setLoadingChild(false);
        });
      }
    });
  }

  function thumbUp(id) {
    setLoadingChild(true);
    thumbUpPaper(id).then(res => {
      reloadList();
      setLoadingChild(false);
    });
  }

  function commentPush(item) {
    if (!commentHtml) {
      showNotification("请输入评价");
      return;
    }
    if (commentHtml.length > 10000) {
      showNotification("评论过长，请减少评论内容或者简化评论格式");
      return;
    }
    commentAdd({
      content: commentHtml,
      paperId: item.id,
      taskId: item.taskId
    }).then(res => {
      if (res.message === 'success') {
        closeComment();
        reloadList();
      }
    });
  }

  function closeComment() {
    setCommentId(undefined);
    setCommentHtml('');
  }

  function commentEdit(id) {
    setCommentId(id);
    setCommentHtml('');
  }

  function goUser(login) {
    window.location.href = `/users/${login}`;
  }


  function confirmReceiptModal(paperId) {
    Modal.confirm({
      title: '确认收款',
      content: '确认已经收到任务报酬',
      onOk: () => {
        confirmReceipt(paperId).then(res => {
          if (res && res.message === "success") {
            showNotification("您已确认收款！");
            reloadList();
          }
        })
      }
    })
  }


  const helper = useCallback(
    (name, rules, widget) => (
      <Form.Item>
        {getFieldDecorator(name, { rules, validateFirst: true })(widget)}
      </Form.Item>
    ),
    []
  );


  return (
    <React.Fragment>
      {loading || loadingChild ? <Loading /> :
        <React.Fragment>
          {
            list.map((item,i) => {
              const winReview = [5,6,7,8].includes(detailStatus) && expertReview && item.reviewFinalGrades!==null;
              return (
                <div className="fileComments df" key={item.id}>
                  <img alt="头像加载失败" src={item.user && getImageUrl(item.user.logo)} width="50" height="50" className="bor-radius-all mr20" />
                  <div className="flex1">
                    <ul>
                      <li className="fl pr taskReview">
                        <span className={item.user.nickname === "******" ? "font-16 mr20 color-grey3" : "user-box font-16 mr20 color-grey3 clickable"} onClick={() => { item.user.nickname === "******" ? "" : goUser(item.user.login) }}>
                          {item.user.nickname || item.user.login}
                        </span>
                        <span className="color-grey9">{timeAgo(item.createdAt)}</span>
                        {item.status === 2 ? <img alt="胜出" className="mr5" src={winpng} /> : <span className="color-blue ml10">{item.checkStatus !== 1 ? paperCheckStatus[item.checkStatus] : applyStatusAllNameArr[item.status]}</span>}
                        {winReview && <span className='paper-grades'>评审得分：<span className='paper-grades-num'>{item.reviewFinalGrades}</span></span>}
                        {winReview && i ==0 && <span className='winReview'><img src={win1}/>第一名</span>}
                        {winReview && i ==1 && <span className='winReview'><img src={win2}/>第二名</span>}
                        {winReview && i ==2 && <span className='winReview'><img src={win3}/>第三名</span>}
                      </li>
                      <li className="fr">
                        {((item.needComplain && detailStatus === 3) || (detailStatus === 5 && item.publicTaskComplain && item.checkStatus === 1 && item.status !== 2)) && (current_user.login === item.user.login) &&
                          <a className="base_smallBtn blue_line_btn fl" onClick={() => { setComplainVisible(true); setCheckedItem(item) }}>申诉</a>}

                        {item.status === 2 && detailStatus === 6 && (current_user.login === item.user.login) && (!item.sign) && (item.canApplicantSign || item.canApplicantSignByPlatform) &&
                          <a className="base_smallBtn blue_line_btn fl" onClick={() => { setAgreeVisible(true); setCheckedItem(item) }}>签订协议</a>}

                        {item.status === 2 && detailStatus === 7 && (current_user.login === item.user.login) && (item.task && item.task.agreementSigning === 1) && (!item.isPay) &&
                          <a className="base_smallBtn blue_line_btn fl" onClick={() => { confirmReceiptModal(item.id) }}>确认收款</a>}
                      </li>
                    </ul>
                    <div className="paper-detail-content markdown-body editormd-html-preview editor-w-text" dangerouslySetInnerHTML={{ __html: item.paperDetail ? item.paperDetail.content : '' }}></div>

                    <div className="attachments" >
                      {
                        item.paperDetail && item.paperDetail.busiAttachments && item.paperDetail.busiAttachments.map(fileItem => {
                          return <div className="file-list-box" key={fileItem.id}>
                            <a onClick={() => { downFile(fileItem) }}><i className="iconfont icon-fujian color-green font-14 mr3"></i>
                              {fileItem.fileName} </a>
                            <span className="ml10 color-grey-9">({fileItem.fileSizeString})</span>
                          </div>
                        })
                      }
                    </div>


                    {item.comments && item.comments.length > 0 && <div className="padding20 fileCommentsList">
                      {item.comments.map(commentsItem => {
                        return <div className="comments-item" key={commentsItem.id}>
                          <div className="comments-author">
                            <span className="color-grey3 font-bd mr20">{commentsItem.user.nickname || commentsItem.user.login}</span>
                            <span className="color-grey9">{timeAgo(commentsItem.createdAt)}</span>
                          </div>
                          <div className="editor-w-text comments-content" dangerouslySetInnerHTML={{ __html: commentsItem.details && commentsItem.details.content }}>
                          </div>
                        </div>
                      })
                      }
                    </div>}


                    <li className="clearfix color-grey-6 mt10 mb20">
                      <span className="mr50 fl"><span className="color-grey9">成果编号：</span>#{item.number}</span>
                      <span className="mr50 fl"><span className="color-grey9">提交时间：</span>{item.createdAt}</span>
                      <span className="fl"><span className="color-grey9">稿件状态：</span>{item.read ? '雇主已浏览' : '雇主未浏览'}</span>
                      {
                        item.user.nickname !== "******" && <span className="fr">
                          {[4, 5].includes(detailStatus) && <a className="mr20" onClick={() => { setReportVisible(true); setCheckedItem(item) }}><i className="iconfont icon-jinggao font-15 mr3"></i>举报</a>}
                          <a className="mr20" onClick={() => { commentEdit(item.id) }}><i className="iconfont icon-huifu1 font-15 mr3"></i>{item.comments ? item.comments.length : 0}</a>
                          <a onClick={() => { thumbUp(item.id) }}><i className="iconfont icon-dianzan11 font-16 mr3"></i>{item.thumbsUp}</a>
                        </span>
                      }

                    </li>

                    {commentId === item.id && <React.Fragment>
                      <ReactWEditor
                        config={{
                          ...editorConfig,
                          placeholder: "请输入评论",
                        }}
                        onChange={(html) => { setCommentHtml(html) }}
                      />
                      <Button className="mt20 mr20 mb20 fr" type={"primary"} onClick={() => { commentPush(item) }}>发表</Button>
                      <Button className="mt20 mr20 mb20 fr" onClick={closeComment}>取消</Button>
                    </React.Fragment>}

                  </div>

                </div>

              )
            })
          }

          {list.length > 0 ?
            <div className="edu-txt-center mt20 mb20">
              {total > pageSize && <Pagination
                showQuickJumper
                onChange={(page) => { setPage(page) }}
                current={curPage}
                total={total}
                showTotal={total => `共 ${total} 条`}
              />}
            </div> :
            <Nodata _html="暂无数据" />}
        </React.Fragment>
      }


      <Modal
        title="举报"
        visible={reportVisible}
        onOk={report}
        onCancel={() => { setReportVisible(false) }}
        className="form-edit-modal"
      >
        <div className="task-popup-content">
          <p className="edu-txt-center lineh-20 mb10">你的举报信息将发送给平台管理员</p>
          <p className="edu-txt-center lineh-20">请如实填写有效的举报原由，我们将尽快完成审核</p>
          {
            helper('reportValue', [{ required: reportVisible, message: "(必填)请在此输入发起举报的原因，最大限制100个字符" },
            { max: 100, message: '长度不能超过100个字符' }],
              <TextArea
                placeholder="(必填)请在此输入发起举报的原因，最大限制100个字符"
                autoSize={{ minRows: 6 }}
                className="applyText"
              />
            )
          }
        </div>
      </Modal>

      <ComplainModal
        visible={complainVisible}
        setVisible={setComplainVisible}
        checkedItem={checkedItem}
        detailStatus={detailStatus}
        showNotification={showNotification}
        reloadList={reloadList}
      />

      {agreeVisible && <AgreementModal
        paperId={checkedItem.id}
        checkedItem={checkedItem}
        visible={agreeVisible}
        setVisible={setAgreeVisible}
        showNotification={showNotification}
        reloadList={reloadList}
      />}

    </React.Fragment>

  )
}
)

