import React, { useCallback, useEffect, useState } from 'react';
import { Input, Button, Form, Select } from 'antd';

import ItemAgreementManage from '../components/itemAgreementManage';
import StatusNav from '../../components/statusNav';
import { agreementArr } from '../static';
import { agreementList } from '../api';
import '../index.scss';
const Option = Select.Option;

const agreementOptionArr = agreementArr.slice(0, 2);
export default Form.create()(({ form, showNotification, match, history }) => {


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

  const [approve, setApprove] = useState(1);
  const [loading, setLoading] = useState(false);
  const [searchObj, setSearchObj] = useState({});
  const [status, setStatus] = useState('2');
  const [curPage, setCurPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [taskList, setTaskList] = useState([]);
  const [type, setType] = useState('1');

  const [reload, setReload] = useState(0);

  const [loadPaper, setLoadPaper] = useState(0);

  // 加载审核协议列表
  useEffect(() => {
    const params = {
      ...searchObj,
      status,
      type,
      currentPage: curPage,
      pageSize: 10,
    };
    setLoading(true);
    agreementList(params).then(data => {
      if (data) {
        if (loadPaper === 0 && data.rows.length === 0) {
          setLoadPaper(1);
        } else {
          setLoadPaper(2);
        }
        setTaskList(data.rows);
        setTotal(data.total);
      }
      setLoading(false);
    });
  }, [reload, status, curPage, searchObj, type]);

  // 如果第一次加载任务协议审核发现没有数据，那么切换成审核成果协议列表
  useEffect(() => {
    if (loadPaper === 1) {
      const params = {
        status: '2',
        type: '2',
        currentPage: 1,
        pageSize: 10,
      };
      setLoading(true);
      agreementList(params).then(data => {
        if (data && data.rows.length > 0) {
          setTaskList(data.rows);
          setTotal(data.total);
          setType('2');
          setLoadPaper(2);
        }
        setLoading(false);
      });
    }
  }, [loadPaper]);

  // form表单公共处理函数
  const helper = useCallback(
    (name, rules, widget, initialValue) => (
      <Form.Item>
        {getFieldDecorator(name, { rules, initialValue, validateFirst: true, })(widget)}
      </Form.Item>
    ), []);


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

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

  // 修改状态
  function changeApprove(approve) {
    setApprove(approve);
    setCurPage(1);
    if (approve === 1) {
      setStatus('2');
    } else {
      setStatus('0,1');
    }
  }

  // 清除查询内容
  function clearSearch() {
    setFieldsValue({
      taskNumber: '',
      taskName: '',
      userName: ''
    });
    setSearchObj({});
  }

  // 刷新数据
  const reloadList = useCallback(() => {
    setReload(Math.random());
  }, []);


  return (
    <div className="centerbox task-manage">
      
      <div className="center-screen" >
        <div className="center-left-but">
          {helper(
            "type",
            [],
            <Select
              showArrow
              placeholder="请选择协议"
              onChange={(type) => { setType(type) }}
            >
              <Option key={'1'}>委托协议</Option>
              <Option key={'2'}>成果协议</Option>
            </Select>,
            type
          )}
          <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(
            "taskNumber",
            [{ max: 20, message: '长度不能超过20个字符' }],
            <Input
              placeholder="输入任务编号进行检索"
            />
          )}

          {helper(
            "taskName",
            [{ 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>
      </div>


      <div className="center-content">

        {
          approve === 2 && <StatusNav
            key={'status'}
            type={'status'}
            options={agreementOptionArr}
            changeOptionId={changeOptionId}
          />
        }
        <ItemAgreementManage
          list={taskList}
          curPage={curPage}
          total={total}
          changePage={(page) => { setCurPage(page) }}
          loading={loading}
          showNotification={showNotification}
          reloadList={reloadList}
        />

      </div>


    </div>
  )
}
)