import React, { useCallback, useEffect, useState, useMemo } from 'react';
import { Input, Radio, Select, Button, Form, DatePicker, Table, Pagination, Modal } from 'antd';
import { Link } from "react-router-dom";
import { paperCheckStatusArr } from '../static';
import { readyCheckPapers, checkPaper, } from '../api';
import '../index.scss';
const format = "YYYY-MM-DD HH:mm:ss";
const Option = Select.Option;
const TextArea = Input.TextArea;


const checkStatusArr = [];
for (const item of paperCheckStatusArr) {
  checkStatusArr[item.dicItemCode] = item.dicItemName;
}
export default Form.create()(({ current_user, form, showNotification, match, history }) => {


  const { getFieldDecorator, validateFields, setFieldsValue, getFieldsValue } = form;

  const [loading, setLoading] = useState(false);
  const [searchObj, setSearchObj] = useState({
    checkStatus: '0',
    parentId: 0,
  });
  const [curPage, setCurPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [taskList, setTaskList] = useState([]);

  const [reload, setReload] = useState(0);
  const [visible, setVisible] = useState(false);
  const [activeId, setActiveId] = useState('');


  useEffect(() => {
    const params = {
      curPage,
      pageSize: 10,
      ...searchObj,
    };
    setLoading(true);
    readyCheckPapers(params).then(data => {
      if (data) {
        setTaskList(data.rows);
        setTotal(data.total);
      }
      setLoading(false);
    })
  }, [reload, curPage, searchObj]);


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


  function onSearch() {
    let values = getFieldsValue(['checkStatus', 'endCreatedAt', 'startCreatedAt', 'parentId']);
    if (values.startCreatedAt) values.startCreatedAt = values.startCreatedAt.format(format);
    if (values.endCreatedAt) values.endCreatedAt = values.endCreatedAt.format(format);
    if (values.checkStatus === '0,1,2') values.checkStatus = '';
    setSearchObj(values);
  }

  function clearSearch() {
    setFieldsValue({
      startCreatedAt: '',
      endCreatedAt: '',
      checkStatus: '0,1,2'
    });
    setSearchObj({});
  }

  function checkPaperItem(paperId, passStatus) {
    validateFields((err, values) => {
      if (!err) {
        setLoading(true);
        checkPaper({
          paperId,
          auditingVo: {
            pass: passStatus ? 1 : values.pass,
            message: values.message,
          }
        }).then(res => {
          setLoading(false);
          if (res && res.message === 'success') {
            setReload(Math.random());
            setVisible(false);
            setFieldsValue({
              pass: '',
              message: '',
            })
          }
        });
      }
    });
  }

  const columns = useMemo(() => {
    return [
      {
        title: '序号',
        dataIndex: 'index',
        render: (text, record, index) => {
          return <div style={{ textAlign: 'center' }}>{index + 1}</div>
        }
      },
      {
        title: '来源任务',
        dataIndex: 'name',
        width: "20%",
        render: (text, record) => (
          <span>
            <Link className="line_1 color-grey3" to={`/task/taskDetail/${record.taskId}`}>{record.task && record.task.name}</Link>
          </span >
        ),
      },
      {
        title: '评论/成果内容',
        dataIndex: 'content',
        width: "30%",
        render: (text, record) => {
          return record.paperDetail ? <div dangerouslySetInnerHTML={{ __html: record.paperDetail.content }}></div> : ''
        }
      },
      {
        title: '提交者',
        dataIndex: 'user',
        render: (text, record) => {
          return record.user.nickname || record.user.login
        }
      },
      {
        title: '提交时间',
        dataIndex: 'createdAt',
      },
      {
        title: '审核状态',
        dataIndex: 'checkStatus',
        render: (text, record) => {
          return text === 0 ? <React.Fragment>
            <Button className="mr5 font-12" type="primary" size="small" onClick={() => { checkPaperItem(record.id, true) }}>通过</Button>
            <Button className="mr5 font-12" type="info" size="small" onClick={() => { disagree(record) }}>不通过</Button>
          </React.Fragment> : checkStatusArr[text]
        }
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <React.Fragment>
            <Link className="line_1 color-grey3" to={`/task/taskDetail/${record.taskId}`}>查看</Link>
          </React.Fragment>
        ),
      },
    ]
  }, []);

  // 不通过评论或者成果
  function disagree(item) {
    if (!item.parentId) {
      setActiveId(item.id); setVisible(true);
    } else {
      Modal.confirm({
        title: '此条评论不通过?',
        onOk() {
          setLoading(true);
          checkPaper({
            paperId: item.id,
            auditingVo: {
              pass: 0,
              message: '不通过',
            }
          }).then(res => {
            setLoading(false);
            if (res && res.message === 'success') {
              setReload(Math.random());
            }
          });
        }
      });
    }
  }


  function changeStatus(e) {
    setSearchObj({
      ...searchObj,
      checkStatus: e,
    });
    setCurPage(1);
  }

  function changeType(e) {
    setSearchObj({
      ...searchObj,
      parentId: e,
    });
    setCurPage(1);
  }

  return (
    <div className="centerbox task-manage">
      <div className="center-screen" >
        <div className="center-left-but">
          {helper(
            "",
            "checkStatus",
            [],
            <Select
              showArrow
              placeholder="请选择审核状态"
              onChange={changeStatus}
            >
              <Option key={'0,1,2'}>{'所有状态'}</Option>
              {
                paperCheckStatusArr.map(item => {
                  return <Option key={item.dicItemCode}>{item.dicItemName}</Option>
                })
              }
            </Select>,
            '0'
          )}

          {helper(
            "",
            "parentId",
            [],
            <Select
              showArrow
              placeholder="请选择需要审核的类型"
              onChange={changeType}
            >
              <Option key={0} value={0}>成果</Option>
              <Option key={1} value={1}>评论</Option>
            </Select>,
            0
          )}
        </div>

        <div className="center-right-but">

          {helper(
            "发布时间:",
            "startCreatedAt",
            [],
            <DatePicker
              showTime
              format={format}
              placeholder="请选择开始时间"
            />
          )}

          {helper(
            "",
            "endCreatedAt",
            [],
            <DatePicker
              showTime
              format={format}
              placeholder="请选择结束时间"
            />
          )}

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

        </div>
      </div>


      <div className="center-content">

        <Table
          loading={loading}
          rowKey={(row) => row.id}
          dataSource={taskList}
          columns={columns}
          pagination={false}
          className="mt10"
        />
        {total > 10 &&
          <Pagination
            onChange={(page) => { setCurPage(page) }}
            current={curPage}
            total={total}
          />}

      </div>

      <Modal
        title="不通过的原因"
        visible={visible}
        onOk={() => { checkPaperItem(activeId, false) }}
        onCancel={() => { setVisible(false); setFieldsValue({ pass: 2, message: '' }); }}
        className="form-edit-modal"
      >
        {helper(
          "",
          "pass",
          [{ required: visible, message: '请选择是否允许申诉' }],
          <Radio.Group
            className="mb10"
          >
            <Radio value={2}>允许申诉</Radio>
            <Radio value={0}>不允许申诉</Radio>
          </Radio.Group>,
          2
        )
        }

        {helper(
          "",
          "message",
          [{ required: visible, message: '请输入拒绝的原因' }],
          <TextArea
            placeholder="(必填)我想说点什么呢,200字以内"
            autoSize={{ minRows: 6 }}
            className="applyText"
            maxLength={200}
          />
        )
        }
      </Modal>
    </div>
  )
}
)