import React, { useCallback, useMemo, useEffect, useState } from 'react';
import { Input, Button, Form, Table, Pagination, Modal } from 'antd';
import { Link } from "react-router-dom";

import StatusNav from '../../components/statusNav';
import { complainPaperList, checkComplain } from '../api';
import { paperComplainStatusArr } from '../static';
import { httpUrl } from '../fetch';

import '../index.scss';

const TextArea = Input.TextArea;

const paperComplainStatus = [];
for (const item of paperComplainStatusArr) {
  paperComplainStatus[item.dicItemCode] = item.dicItemName;
}
const paperComplain = paperComplainStatusArr.slice(0, 2);

export default Form.create()(({  form, showNotification, history}) => {

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

  const [approve, setApprove] = useState(1);
  const [loading, setLoading] = useState(false);
  // const [searchObj, setSearchObj] = useState({});
  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('');
  const [status, setStatus] = useState('2');

  useEffect(() => {
    const params = {
      // ...searchObj,
      status,
      curPage,
      pageSize: 10,
    };
    setLoading(true);
    complainPaperList(params).then(data => {
      if (data) {
        setTaskList(data.rows);
        setTotal(data.total);
      }
      setLoading(false);
    })

  }, [reload, status, curPage]);



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


  // function onSearch() {
  //   validateFields((err, values) => {
  //     if (!err) {
  //       setSearchObj({ numberInput: values.numberInput });
  //     }
  //   });
  // }

  // function clearSearch() {
  //   setFieldsValue({
  //     numberInput: '',
  //   });
  //   setSearchObj({});
  // }


  function changeApprove(approve) {
    setApprove(approve);
    setCurPage(1);
    if (approve === 1) {
      setStatus('2');
    } else {
      setStatus('0,1');
    }
  }

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

  const columns = useMemo(() => {
    return [
      {
        title: '成果编号',
        dataIndex: 'paperNumber',
        render: (text, record) => {
          return text ? <Link className="line_1 color-grey3" to={`/task/taskDetail/${record.taskId}`}>{text}</Link> : '--'
        }
      },
      {
        title: '申诉内容',
        dataIndex: 'content',
        width: "26%",
      },
      {
        title: '申诉文件',
        dataIndex: 'materials',
        width: "20%",
        render: (text, record) => {
          return <div>
            {
              Array.isArray(record.materials) && record.materials.map(item => {
                return <div className="file-list-box" key={item.id}>
                  <a onClick={() => { downFile(item) }}><i className="iconfont icon-fujian color-green font-14 mr3"></i>
                    {item.fileName} </a>
                  <span className="ml10 color-grey-9">({item.fileSizeString})</span>
                </div>
              })
            }
          </div>
        }

      },
      {
        title: '提交者',
        dataIndex: 'user',
        render: (text, record) => {
          return record.user.nickname || record.user.login
        }
      },
      {
        title: '提交时间',
        dataIndex: 'createdAt',
      },
      {
        title: '审核状态',
        dataIndex: 'status',
        render: (text, record) => {
          return text !== 2 ? paperComplainStatus[text] : <React.Fragment>
            <Button className="mr5 font-12" type="primary" size="small" onClick={() => { checkPaperItem(record.id, 1) }}>通过</Button>
            <Button className="mr5 font-12" type="info" size="small" onClick={() => { setActiveId(record.id); setVisible(true) }}>不通过</Button>
          </React.Fragment>
        }
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <Link className="line_1 color-grey3" to={`/task/taskDetail/${record.taskId}`}>查看详情</Link>
        ),
      },
    ]
  }, []);

  function checkPaperItem(paperId, pass, message) {
    setLoading(true);
    checkComplain({
      paperId,
      auditingVo: {
        pass,
        message,
      }
    }).then(res => {
      if (res && res.message === 'success') {
        setReload(Math.random());
        setVisible(false);
      }
      setLoading(false);
    });
  }

  function refuse() {
    validateFields((err, values) => {
      if (!err) {
        checkPaperItem(activeId, 0, values.message);
      }
    });
  }

  const changeOptionId = useCallback((option) => {
    setStatus(option.dicItemCode.toString() || '0,1');
    setCurPage(1);
  }, []);

  return (
    <div className="centerbox task-manage">
      

      <div className="center-screen" >
        <div className="center-left-but">
          <Button className="circle-button" type={approve === 1 ? 'primary' : ''} onClick={() => { changeApprove(1) }}>待审批</Button>
          <Button className="circle-button" type={approve === 2 ? 'primary' : ''} onClick={() => { changeApprove(2) }}>已审批</Button>
        </div>

        {/* <div className="center-right-but">
          {helper(
            "numberInput",
            [{ max: 20, message: '长度不能超过20个字符' }],
            <Input
              placeholder="输入任务编号进行检索"
            />
          )}

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

        </div> */}
      </div>


      <div className="center-content">
        {
          approve === 2 && <StatusNav
            key={'status'}
            type={'status'}
            options={paperComplain}
            changeOptionId={changeOptionId}
          />
        }

        <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={refuse}
        onCancel={() => { setVisible(false) }}
        className="form-edit-modal"
      >
        {helper(
          "message",
          [{ required: visible, message: '请给出不通过的原因' }],
          <TextArea
            placeholder="(必填)我想给点什么意见呢，200字以内"
            autoSize={{ minRows: 6 }}
            className="applyText"
            maxLength={200}
          />
        )}
      </Modal>
    </div>
  )
}
)