import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Form, Modal, Input, Pagination, Radio, Table } from 'antd';
import { Link } from "react-router-dom";
import Nodata from 'forge/Nodata';
import Loading from "src/Loading";
import Upload from 'military/components/Upload';
import ProofModal from '../proofModal';
import { publishModeArr, taskStatusAllArr, myPaperStatusArr } from '../../static';
import { signMethod, uploadAgreeRequire, downAgreement } from "../../api";
import { httpUrl } from '../../fetch';
import '../../index.scss';
import './index.scss';

const statusArr = [];
for (const item of taskStatusAllArr) {
  statusArr[item.dicItemCode] = item.dicItemName;
}
export default Form.create()((props) => {
  const { form, list, curPage, total, changePage, taskCategoryValueArr, loading, publish, showNotification, reloadList, joinTask } = props;
  const { getFieldDecorator, validateFields, setFieldsValue, } = form;

  const [visibleProofs, setVisibleProofs] = useState(false);
  const [taskId, setTaskId] = useState();
  const [checkItem, setCheckItem] = useState({});
  const [taskModeId, setTaskModeId] = useState('');
  const pageSize = props.pageSize || 10;

  const [visibleMethod, setVisibleMethod] = useState(false);
  const [visibleAgree, setVisibleAgree] = useState(false);
  const [fileList, setFileList] = useState(null);

  const [dowloadTaskId, setDowloadTaskId] = useState('');
  const [visibleDownload, setVisibleDownload] = useState(false);
  const [uploadList, setUploadList] = useState([]);



  useEffect(() => {
    visibleDownload && downAgreement({ taskId: dowloadTaskId }).then(res => {
      if (res && res.message === "success") {
        setUploadList(res.data);
      }
    })
  }, [visibleDownload])

  function uploadProofs(item) {
    setVisibleProofs(true);
    setTaskId(item.id);
    setTaskModeId(item.taskModeId);
  }

  function adviceModal(advice) {
    Modal.info({
      title: '审核意见',
      content: advice
    })
  }

  function signMethodModal(item) {
    setVisibleMethod(true);
    setTaskId(item.id);
  }

  function uploadAgree(item) {
    setVisibleAgree(true);
    setTaskId(item.id);
    setCheckItem(item);
  }

  function chooseMethod() {
    validateFields((err, values) => {
      if (!err) {
        signMethod({
          taskId,
          method: values.method,
        }).then(res => {
          if (res && res.message === 'success') {
            showNotification('选择协议签订方式成功');
            setVisibleMethod(false);
            setFieldsValue({
              method: ''
            });
            reloadList();
          } else {
            showNotification((res && res.message) || '操作失败');
          }
        })
      }
    })
  }

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


  function uploadAgreeList() {
    validateFields((err, values) => {
      if (!err) {
        uploadAgreeRequire({
          taskId,
          params: {
            files: values.files
          }
        }).then(res => {
          if (res && res.message === "success") {
            setFieldsValue({
              files: ''
            });
            reloadList();
            setVisibleAgree(false);
            showNotification('上传协议成功');
          } else {
            showNotification((res && res.message) || '上传协议失败');
          }
        })
      }
    });
  }

  function uploadFunc(fileList, files) {
    setFileList(fileList);
    setFieldsValue({
      files,
    })
  }


  const columns = useMemo(() => {
    return [
      {
        title: '成果物编号',
        dataIndex: 'paperNumber',
      },
      {
        title: '凭证文件',
        dataIndex: 'fileName',
        render: (text, record) => {
          return <a className="line_1 color-grey3" onClick={() => { download(record.winnerContracts[0].id) }}> {record.winnerContracts && record.winnerContracts[0].fileName}</a >
        }
      },
      {
        title: '操作',
        dataIndex: 'action',
        render: (text, record) => {
          return <a className="line_1 color-grey3" onClick={(e) => { download(record.winnerContracts[0].id) }}> 下载凭证</a >
        }
      }
    ];
  }, []);

  function download(id) {
    window.open(httpUrl + '/busiAttachments/download/' + id);
  }

  return (
    <React.Fragment>
      <ul className="df mt10 needs_condition_content_nav">
        <li key={1} className="with35 edu-txt-left">任务</li>
        <li key={2} className="with15">类型</li>
        {publish && <li key={3} className="with10 draft_only">应征投稿</li>}
        <li key={4} className="with10">金额</li>
        <li key={5} className="flex1">任务状态</li>
        <li key={6} className="with15">操作</li>
      </ul>

      {loading ? <Loading /> : <React.Fragment>
        {
          list.map(item => {
            return (
              <div key={item.id} className="needs_condition_content">
                <p className="needs_condition_content_t color-dark-grey">
                  任务编号：{item.number}
                  <i className="ml20 mr5 iconfont icon-shijian color-grey9 font-16"></i>
                  {item.createdAt}
                </p>
                <ul className="df">
                  <li key={1} className="mytask-title with35 edu-txt-left font-16 font-bd" >
                    <Link className="color-grey3 font-16 font-bd" to={`/task/taskDetail/${item.id}`}>{item.name}</Link>
                    {
                      joinTask ? <React.Fragment>
                        {item.myPaperStatus === 0 && <span className="list_status s_orange ml10">{myPaperStatusArr[item.myPaperStatus]}</span>}
                        {item.myPaperStatus === 1 && <span className="list_status s_grey ml10">{myPaperStatusArr[item.myPaperStatus]}</span>}
                        {item.myPaperStatus === 2 && <span className="list_status s_red ml10">{myPaperStatusArr[item.myPaperStatus]}</span>}

                        {item.status === 6 && (item.agreementSigning === 1 || (item.agreementSigning === 2 && item.contractStatus === 1)) && <span className="list_status s_orange ml10">待签订协议</span>}

                        {item.status !== 8 && item.delayTime < 0 &&<span className="list_status list-yellow">延期中</span>}
                        {item.status !== 8 && item.cancelStatus === 1 && item.delayTime > 0 && <span className="list_status list-yellow">手动延期中</span>}
                        {item.status !== 8 && item.delayed && item.cancelStatus === 0 && item.delayTime > 0 && item.delayCount>0 &&<span className="list_status list-yellow">系统自动延期中</span>}

                      </React.Fragment> : <React.Fragment>
                        {item.status === 6 && (item.agreementSigning === 1 || (item.agreementSigning === 2 && item.auditing && item.auditing.pass === 1)) && <span className="list_status s_orange ml10">待签订协议</span>}

                        {item.status !== 8 && item.delayTime < 0 &&<span className="list_status list-yellow">延期中</span>}
                        {item.status !== 8 && item.cancelStatus === 1 && item.delayTime > 0 &&<span className="list_status list-yellow">手动延期中</span>}
                        {item.status !== 8 && item.delayed && item.cancelStatus === 0 && item.delayTime > 0 && item.delayCount>0 && <span className="list_status list-yellow">系统自动延期中</span>}
                      </React.Fragment>
                    }
                  </li>
                  <li key={2} className="with15 flex-column">
                    <span className="line_1">{taskCategoryValueArr[item.categoryId]}</span>
                    <span className="line_1">{publishModeArr[item.publishMode]}</span>
                  </li>

                  {publish && <li key={3} className="with10 draft_only">{item.papersCount || 0}</li>}

                  <li key={4} className="with10 color-orange">￥{item.bounty}</li>
                  <li className="flex1">
                    <span>
                      <span className="line_1">{item.exceptClosedBoolean ? '已关闭' : statusArr[item.status]}</span>
                    </span>
                  </li>
                  <li key={5} className="with15 flex-column">
                    {
                      joinTask ? <Link className="line_1 color-grey3" to={`/task/taskDetail/${item.id}`}>查看详情</Link>
                        :
                        <React.Fragment>
                          {
                            item.status === 0 || item.status === 9 ?
                              <Link className="line_1 color-grey3" to={`/task/taskEdit/${item.id}`}>编辑草稿</Link> :
                              <Link className="line_1 color-grey3" to={`/task/taskDetail/${item.id}`}>查看详情</Link>
                          }

                          {
                            item.status === 4 && item.papersCount > 0 && (!item.isProofBoolean) && (!item.isProofBoolean) &&
                            <a onClick={() => { uploadProofs(item) }} className="line_1 color-blue">上传佐证材料</a>
                          }

                          {
                            (!item.isProofBoolean) && (item.taskResultProof && item.taskResultProof.status === 0) &&
                            <a onClick={() => { adviceModal(item.advice) }} className="line_1 color-blue">佐证被拒原因</a>
                          }

                          {(item.status === 2 || item.status === 9) && <a onClick={() => { adviceModal(item.repairAdvice) }} className="line_1 color-blue">审核意见</a>}

                          {item.status === 6 && item.agreementSigning === 0 && <a className="line_1 color-blue" onClick={() => { signMethodModal(item) }}>选择协议签订方式</a>}

                          {item.status === 6 && item.agreementSigning === 2 && (item.contractStatus === null || item.contractStatus === 0) && <a className="line_1 color-blue" onClick={() => { uploadAgree(item) }}>上传委托协议</a>}

                          {item.status === 6 && item.agreementSigning === 2 && [1, 2].includes(item.contractStatus) && <a className="line_1 color-grey-9" >已上传委托协议</a>}

                          {item.status === 6 && item.agreementSigning === 1 && <span className="line_1 color-grey-9">已选择自主签订协议</span>}

                          {item.status === 7 && <span className="line_1 color-grey-9">{item.agreementSigning === 1 ? '待胜出者确认收款' : '待平台上传支付凭证'}</span>}

                          {item.status === 7 && <a className="line_1 color-blue" onClick={() => { setDowloadTaskId(item.id); setVisibleDownload(true); }}>下载协议签订凭证</a>}

                        </React.Fragment>
                    }


                  </li>
                </ul>
              </div>
            )
          })
        }

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

      {visibleProofs && <ProofModal
        taskId={taskId}
        taskModeId={taskModeId}
        visible={visibleProofs}
        changeVisible={setVisibleProofs}
        showNotification={showNotification}
        reloadList={reloadList}
      />}


      <Modal
        title="选择签订协议方式"
        visible={visibleMethod}
        onOk={chooseMethod}
        onCancel={() => { setVisibleMethod(false) }}
        className="form-edit-modal"
      >
        {
          helper('method', [{ required: visibleMethod, message: '请选择签订协议的方式' }],
            <Radio.Group className="vertical-radio">
              <Radio value={2}>
                <p>委托平台签订</p>
                <p className="color-grey-9">以平台名义与评选胜出者签订协议，需要经平台管理员审批需要发布方将奖励经费划归平台，在审核通过后平台自动发送电子协议</p>
              </Radio>
              <Radio value={1}>
                <p>自主签订</p>
                <p className="color-grey-9">通过线下的方式，以发布方名义与评选胜出者签订协议</p>
              </Radio>
            </Radio.Group>)
        }
      </Modal>


      <Modal
        title="上传委托协议"
        visible={visibleAgree}
        onOk={uploadAgreeList}
        onCancel={() => { setVisibleAgree(false) }}
        className="form-edit-modal"
      >
        {checkItem.auditing && <p className="color-orange mb10 task_tip">
          审核意见：{checkItem.auditing.message}
        </p>}
        <Form.Item className="upload-form" label="协议上传" required={true}>
          <Upload
            load={uploadFunc}
            size={50}
            showNotification={showNotification}
            fileList={fileList}
          />
          {/* 用一个隐藏的input实现上传文件的必填校验 */}
          {getFieldDecorator('files', {
            rules: [{ required: visibleAgree, message: "请上传文件" }],
            validateFirst: true
          })(<Input style={{ display: 'none' }} />)}
        </Form.Item>
      </Modal>

      <Modal
        title="下载协议签订凭证"
        visible={visibleDownload}
        onOk={() => { setVisibleDownload(false) }}
        onCancel={() => { setVisibleDownload(false) }}
        className="form-edit-modal"
      >
        <Table
          loading={loading}
          rowKey={(row) => row.id}
          dataSource={uploadList}
          columns={columns}
          pagination={false}
        />

      </Modal>

    </React.Fragment>

  )
}
)