import React, { useEffect, useState, useCallback } from 'react';
import { Pagination, Modal, Input, DatePicker, Form } from 'antd';
import { Link } from "react-router-dom";
import moment from 'moment';
import Nodata from 'forge/Nodata';
import Loading from "src/Loading";
import { getImageUrl, formatDuring } from 'educoder';
import { taskStatusAllArr } from '../../static';
import { delayTask, closeTask } from '../../api';
import './index.scss';

const format = "YYYY-MM-DD";

const statusArr = [];
for (const item of taskStatusAllArr) {
  statusArr[item.dicItemCode] = item.dicItemName;
}

const classArr = ['', 'list-done', 'list-error', 'list-red', 'list-yellow', 'list-pay', '', 'list-pay', 'list-gray',];

function getSomeDayAfter(time, nDay) {
  return moment(new Date(time).setDate(new Date(time).getDate() + nDay)).format('YYYY-MM-DD HH:mm');
}

export default Form.create()((props) => {

  const { list, curPage, total, changePage, loading, showNotification, reloadList, form } = props;
  const { getFieldDecorator, validateFields } = form;

  const [checkedItem, setCheckedItem] = useState('');
  const [visible, setVisible] = useState(false);
  const pageSize = props.pageSize || 10;

  function closeClick(item) {
    Modal.confirm({
      title: '是否关闭?',
      content: <p class="font-14 lineh-25 mb10 edu-txt-center">关闭后该任务立即结束，无法重新打开</p>,
      onOk() {
        closeTask(item.id).then(res => {
          if (res && res.message === 'success') {
            showNotification('操作成功');
            reloadList();
          }
        })
      }
    });
  }

  function delayClick(item) {
    setCheckedItem(item);
    setVisible(true);
  }

  function delayTime() {
    validateFields((err, values) => {
      if (!err) {
        delayTask({
          taskId: checkedItem.id,
          params: {
            delayedTo: moment(values.delayedTo).format(format)
          },
        }).then(res => {
          if (res && res.message === 'success') {
            showNotification('操作成功');
            reloadList();
            setVisible(false);
          }
        });
      }
    });
  }

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

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

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

  const surplusTime = useCallback((item) => {
    let surplus;
    switch (item.currentStatus) {
      case 3:
        surplus = item.collectingDays * 24 * 3600 - (new Date() - new Date(item.publishedAt || item.createdAt)) / 1000;
        break;
      case 4:
        surplus = item.choosingDays * 24 * 3600 - (new Date() - new Date(item.collectingCompleteAt)) / 1000;
        break;
      case 5:
        surplus = item.makePublicDays * 24 * 3600 - (new Date() - new Date(item.makePublicAt)) / 1000;
        break;
      case 6:
        surplus = item.signingDays * 24 * 3600 - (new Date() - new Date(item.publicityCompleteAt)) / 1000;
        break;
      case 7:
        surplus = item.payingDays * 24 * 3600 - (new Date() - new Date(item.signingCompleteAt)) / 1000;
        break;
      default:
        surplus = 0;
    }
    let surplusTimetext = formatDuring(surplus);
    return surplus > 0 ? '剩余' + surplusTimetext : <span>延期 <span className="color-red">{surplusTimetext}</span></span>;
  }, []);

  const stopTime = useCallback((item) => {
    switch (item.currentStatus) {
      case 3:
        return getSomeDayAfter(item.publishedAt, item.collectingDays);
      case 4:
        return getSomeDayAfter(item.collectingCompleteAt, item.choosingDays);
      case 5:
        return getSomeDayAfter(item.makePublicAt, item.makePublicDays);
      case 6:
        return getSomeDayAfter(item.publicityCompleteAt, item.signingDays);
      case 7:
        return getSomeDayAfter(item.signingCompleteAt, item.payingDays);
      case 8:
        return item.payingCompleteAt;
      default:
        return item.expiredAt;
    }
  })

  function disabledDate(current) {
    return current && current < moment().endOf('day');
  }

  return (
    loading ? <Loading /> :
      <React.Fragment>
        {
          list.map(item => {
            return (
              <div className="list-box" key={item.id}>

                <img alt="" className="radius mr15" height="50px" src={item.user && getImageUrl(item.user.logo)} width="50px" onClick={() => { goUser(item.user.login) }} />
                <div className="flex1">

                  <div className="clearfix">
                    <span className="lineh-35" style={{ display: "inline-flex" }}>
                      <span className="color-grey-9 fl">任务编号:</span>
                      <span className="infos_item mr15">{item.number}</span>
                      <span className="fl lineh-35 ml5">
                        <Link className="primary-link" to={`/task/taskDetail/${item.id}`}>{item.name}</Link>
                      </span>
                      <span>{item.currentStatus > 0 && <span className={classArr[item.currentStatus] + ' status-tag'}>{statusArr[item.currentStatus]}</span>}</span>
                    </span>

                    <span className="fr">
                      {item.cancelStatus === 1 && <span className="spanTitle color-red  fl ml20">延期</span>}
                      {item.cancelStatus === 2 && <span className="spanTitle color-grey-6 fl ml20">关闭</span>}

                      {
                        item.cancelStatus === 0 && <React.Fragment>
                          <a className="edu-default-btn edu-orangeline-btn ml20 fl" onClick={() => { goUserMes(item.user.login) }}>私信</a>
                          <a className="edu-default-btn edu-blueline-btn ml20 fl" onClick={() => { delayClick(item) }}>延期</a>
                          <a className="edu-default-btn edu-greyline-btn ml20 fl" onClick={() => { closeClick(item) }}>关闭</a>
                        </React.Fragment>
                      }
                    </span>
                  </div>

                  <div className="clearfix">

                    <span className="with40 fl lineh-35">
                      <span className="color-grey-9 fl">主体名称:</span>
                      <span className="infos_item">{item.enterpriseName}</span>
                    </span>

                    <span className="with30 fl lineh-35">
                      <span className="color-grey-9 fl">发布方式:</span>
                      <span className="infos_item mr15 fl">{item.publishMode === 1 ? '统筹任务' : '自主提交'}</span>
                    </span>

                  </div>
                  <div className="clearfix">
                    <span className="with40 fl lineh-35">
                      <span className="color-grey-9 fl">联系手机:</span>
                      <span className="infos_item">{item.user.phone}（位置分析：{item.belongTo}）</span>
                    </span>

                    <span className="with40 fl lineh-35 color-orange">
                      {
                        item.status === 4 && item.papersCount > 0 && (!item.isProofBoolean) && '未上传佐证材料'
                      }

                      {item.status === 6 && item.agreementSigning === 0 && '未选择协议签订方式'}

                      {
                        item.status === 6 && item.agreementSigning === 2 && (item.contractStatus === null || item.contractStatus === 0) && '未上传委托协议'
                      }

                      {
                        item.status === 6 && item.agreementSigning === 2 && item.contractStatus === 2 && '已上传委托协议'
                      }

                      {
                        item.status === 7 && item.agreementSigning === 2 && '未上传支付报酬凭证'
                      }
                    </span>
                  </div>

                  <div className="clearfix">
                    <span className="with40 fl lineh-35">
                      <span className="color-grey-9 fl">截止时间:</span>
                      <span className="infos_item">{stopTime(item)}</span>

                      {[3, 4, 5, 6, 7].includes(item.currentStatus) && <span className="ml10">{surplusTime(item)}</span>}
                    </span>

                    {/* <span className="with40 lineh-35" style={{ display: "inline-flex" }}>
                      <span className="color-grey-9 fl">任务编号:</span>
                      <span className="infos_item mr15">{item.number}</span>
                      <span className="fl lineh-35 ml5">
                        <Link className="primary-link" to={`/task/taskDetail/${item.id}`}>{item.name}</Link>
                      </span>
                    </span> */}
                  </div>

                </div>
              </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="暂无数据" />}

        <Modal
          title="请输入延期截止的具体时间"
          visible={visible}
          onOk={delayTime}
          onCancel={() => { setVisible(false) }}
          className="time-edit-modal"
        >
          {helper(
            "",
            "delayedTo",
            [{ required: true, message: "请选择日期" }],
            <DatePicker
              format={format}
              placeholder="请选择日期"
              disabledDate={disabledDate}
            />,
            moment(new Date(), format)
          )}
        </Modal>
      </React.Fragment>

  )
}
)