import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Modal, Table, Form, Input, Button, Pagination } from 'antd';
import Upload from 'military/components/Upload';
import { readyCheckPapers, proofAdd } from "../../api";
import { httpUrl } from '../../fetch';
import '../../index.scss';
import './index.scss';

export default Form.create()(props => {
  const { changeVisible, taskId, taskModeId, visible, form, showNotification, reloadList } = props;
  const { getFieldDecorator, validateFields, setFieldsValue, getFieldsValue } = form;

  const pageSize = props.pageSize || 10;
  const [searchObj, setSearchObj] = useState({});
  const [loading, setLoading] = useState(false);
  const [curPage, setCurPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [dataList, setDataList] = useState([]);

  const [fileList, setFileList] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);

  // 获取成果列表
  useEffect(() => {
    setLoading(true);
    let params = {
      ...searchObj,
      taskId,
      checkStatus: '1',
      pageSize,
      curPage,
      status: '',
      parentId:0,
    }
    taskId && readyCheckPapers(params).then(data => {
      if (data && Array.isArray(data.rows)) {
        for (const item of data.rows) {
          item.detail = item.paperDetail && item.paperDetail.content;
        }
      }
      setDataList(data.rows || []);
      setLoading(false);
      setTotal(data.total);
    });
  }, [taskId, curPage, searchObj]);


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

  function onSearch() {
    let values = getFieldsValue(['number', 'userName']);
    setSearchObj(values);
    setCurPage(1);
  }

  function clearSearch() {
    setFieldsValue({
      number: '',
      userName: '',
    });
    setSearchObj({});
    setCurPage(1);
  }

  // 上传附件后得到的文件数组
  function UploadFunc(fileList, files) {
    setFileList(fileList);
    setFieldsValue({
      files
    })
  }


  const columns = useMemo(() => {
    return [{
      title: '作者',
      dataIndex: 'name',
      render: (text, record) => {
        return record.user ? record.user.nickname || record.user.login : ''
      }
    },
    {
      title: '成果物编号',
      dataIndex: 'number',
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (text, record) => {
        // return <Link className="line_1 color-grey3" to={`/task/taskDetail/${record.task.id}`}>查看详情</Link>
        return <a className="line_1 color-grey3" onClick={(e) => { goToDeatil(e, record.task.id) }}> 查看详情</a >
      }
    }];
  }, [taskId]);

  const rowSelection = useMemo(() => {
    return {
      type: taskModeId === 1 ? 'radio' : 'checkbox',
      onChange: (selectedRowKeys, selectedRows) => {
        setSelectedRows(selectedRows);
      },
    }
  }, [taskModeId]);

  function goToDeatil(e, taskId) {
    e.stopPropagation();
    window.location.href = `/task/taskDetail/${taskId}`;
  }

  const handleRow = record => {
    return {
      onClick: event => {
        let chooseDom = event.currentTarget.getElementsByClassName("ant-checkbox-wrapper")[0] || event.currentTarget.getElementsByClassName("ant-radio-wrapper")[0];
        chooseDom && chooseDom.click();
      },
    };
  };

  function proofItem() {
    if (!selectedRows.length) {
      showNotification("请至少选择一条数据！");
      return;
    }

    validateFields((err, values) => {
      if (!err) {
        let paperNumber = [];
        let winnerIds = [];
        let winnerName = [];

        for (const item of selectedRows) {
          paperNumber.push(item.number);
          winnerIds.push(item.user.id);
          winnerName.push(item.user.nickname || item.user.login);
        }

        let params = {
          paperNumber: paperNumber.join(),
          winnerIds: winnerIds.join(),
          winnerName: winnerName.join(),
          proofFileNumbers: values.files,
          status: 2,
          taskId,
        };
        proofAdd(params).then(res => {
          if (res && res.message === 'success') {
            changeVisible(false);
            reloadList();
          } else {
            showNotification((res && res.message) || "评选提交失败");
          }
        });
      }
    });

  }

  return (
    <Modal
      title="上传评选佐证材料"
      visible={visible}
      onOk={proofItem}
      onCancel={() => { changeVisible(false) }}
      className="proof-modal"
      draggable={true}
    >
      <h3 className="margin10">选出胜出者<span className="color-red">*</span></h3>
      <div className="center-right-but">
        {helper(
          "number",
          [{ max: 20, message: '长度不能超过20个字符' }],
          <Input
            placeholder="请输入成果编号进行检索"
          />
        )}

        {helper(
          "userName",
          [{ max: 20, message: '长度不能超过20个字符' }],
          <Input
            placeholder="请输入作者名称进行检索"
          />
        )}
        <Button className="mr10" type="primary" onClick={onSearch}>搜索</Button>
        <Button className="mr10" type="" onClick={clearSearch}>清除</Button>
      </div>
      <Table
        loading={loading}
        rowKey={(row) => row.id}
        dataSource={dataList}
        columns={columns}
        pagination={false}
        rowSelection={rowSelection}
        onRow={handleRow}
      />
      {total > 10 &&
        <Pagination
          onChange={(page) => { setCurPage(page) }}
          current={curPage}
          total={total}
        />}

      <Form.Item className="upload-form" label="上传附件" required={true} >
        <Upload
          className="commentStyle"
          load={UploadFunc}
          size={50}
          showNotification={showNotification}
          actionUrl={httpUrl}
          fileList={fileList}
        />
        {getFieldDecorator('files', {
          rules: [{ required: visible, message: "请上传文件" }],
          validateFirst: true
        })(<Input style={{ display: 'none' }} />)}
      </Form.Item>
    </Modal>

  )
}
)