import React, { useState, useCallback, useMemo, useEffect } from "react";
import { Input, Select, Button, Form, DatePicker, Table, Pagination, Upload, Modal } from 'antd';
import { Link } from "react-router-dom";
import { formatDuring } from 'educoder';
import Paginationtable from "../../../components/paginationTable";
import { getExpertTasks } from "../../api";
import { taskType, expertTaskStatus } from "../../static";
import { main_web_site_url } from '../../fetch';

import './index.scss';
import '../../index.scss';
const Option = Select.Option;

function ReviewTasks({ form, showNotification, match, history }) {
  const { getFieldDecorator, setFieldsValue, getFieldsValue } = form;

  const [reload, setReload] = useState();
  const [loading, setLoading] = useState(false);
  const [curPage, setCurPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [dataList, setDataList] = useState([]);
  const [total, setTotal] = useState(0);

  let initSearchObj = sessionStorage.expertTask ? JSON.parse(sessionStorage.expertTask) : {
    containerName: '',
    containerType: 1,
    statusString: -1,
  };
  const [searchObj, setSearchObj] = useState(initSearchObj);

  useEffect(() => {
    setFieldsValue(initSearchObj);
  }, []);

  const columns = useMemo(() => {
    return [
      {
        title: '序号',
        dataIndex: 'index',
        render: (text, record, index) => {
          return index + 1
        }
      },
      {
        title: '任务名称',
        dataIndex: 'containerName',
        key: 'containerName',
        render: (text, record) => {
          return record.containerType===1?<Link to={`/task/taskDetail/${record.containerId}`}>{text}</Link>:
          <a className="taskLink ml10" target="_blank" href={`${main_web_site_url}/competitions/${record.containerIdentifier}/home`} >{text}</a>
        }
      },
      {
        title: '评审截止时间',
        dataIndex: 'reviewEndOn',
        key: 'reviewEndOn',
      },
      {
        title: '剩余评审时间',
        dataIndex: 'surplus',
        key: 'surplus',
      },
      {
        title: '评审状态',
        dataIndex: 'status',
        key: 'status',
        render: (text, record) => {
          return text === -1 ? '未评审' : record.commitReview ? '已评审' : '已过期'
        }
      },
      {
        title: '操作',
        dataIndex: 'status',
        key: 'action',
        render: (text, record) => {
          return <Link to={`/expert/user/tasks/${record.containerType}/${record.containerId}`} className="toReview">{text === -1 ? '评审' : '查看结果'}</Link>
        }
      }
    ];
  }, []);

  // 获取列表
  useEffect(() => {
    setLoading(true);
    let params = {
      ...searchObj,
      pageSize,
      curPage,
    };
    getExpertTasks(params).then(res => {
      for (const item of res.data.rows) {
        if (new Date(item.reviewEndOn) > new Date()) {
          item.surplus = formatDuring((new Date(item.reviewEndOn) - new Date()) / 1000);
        } else {
          item.surplus = '- -';
        }
      }
      setDataList(res.data.rows || []);
      setLoading(false);
      setTotal(res.data.total);
    });
  }, [searchObj, curPage, reload, pageSize]);


  function onSearch() {
    let values = getFieldsValue(['containerName', 'containerType', 'statusString']);
    sessionStorage.setItem('expertTask', JSON.stringify(values));
    setSearchObj(values);
  }

  function clearSearch() {
    let initSearchObj={
      containerName: '',
      containerType: 1,
      statusString: -1,
    };
    setFieldsValue(initSearchObj);
    setSearchObj(initSearchObj);
    sessionStorage.setItem('expertTask', JSON.stringify(initSearchObj));
    setCurPage(1);
  }


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

  
    function onShowSizeChange(current, pageSize) {
      setCurPage(current);
      setPageSize(pageSize);
    }

  return (
    <div className='register_right task_right'>
      <p className="task-head">
        我的评审任务
      </p>
      <div className="search-list" >
        {helper(
          "任务名称",
          "containerName",
          [{ max: 20, message: '长度不能超过20个字符' }],
          <Input
            style={{ width: "250px" }}
            placeholder="输入任务名称进行检索"
          />
        )}

        {helper(
          "任务类型",
          "containerType",
          [],
          <Select
            style={{ width: "250px" }}
            placeholder="所有领域"
            dropdownClassName="expert_register"
          >
            {taskType.map(item => {
              return <Option key={item.value} value={item.value}>{item.label}</Option>
            })}
          </Select>,
          1
        )}

        {helper(
          "评审状态",
          "statusString",
          [],
          <Select
            style={{ width: "250px" }}
            placeholder="所有领域"
            dropdownClassName="expert_register"
          >
            {expertTaskStatus.map(item => {
              return <Option key={item.value} value={item.value}>{item.label}</Option>
            })}
          </Select>,
          -1
        )}

        <div className="button-div">
          <Button className="mr10" type="primary" onClick={onSearch}>搜索</Button>
          <Button className="mr10" onClick={clearSearch}>清除</Button>
        </div>
      </div>

      <Paginationtable
        loading={loading}
        dataSource={dataList}
        columns={columns}
        total={total}
        setCurPage={setCurPage}
        current={curPage}
        onShowSizeChange={onShowSizeChange}
      />
    </div>
  )
}
export default Form.create()(ReviewTasks);