import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Form, Pagination, Card, Button, Icon, Tooltip, message,   notification, Modal, Table, Select, Input, DatePicker } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import className from 'classnames';
import Cell from '../../../components/Cell';
import styles from './style.less';
import { fetch, apis } from '../../../utils/request';
import request from '../../../utils/request';
import AuthButton from '@/components/AuthButton';

const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

function header(props) {
  // 获取初始化数据
  const [ data, setData ] = useState({})
  const [demandIdList, setDemandIdList] = useState([])

  useEffect(() => {
    getList({ pageNum: 1, pageSize: 10 });
  },[])

  // 查询列表
  const getList = (params) => {
    request({ ...apis.sample.list, params: { ...params } }).then((data) => {
        console.log(data)
        setData(data)
    })
  }

  
  // 提交事件
  const handleSubmit = (e, props) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        let {createDate, ...submitValue} = values
        if(null != createDate && createDate.length > 0){
          const [startCreateDate, endCreateDate] = createDate
          submitValue.startCreateDate = moment(startCreateDate).format('YYYY-MM-DD');
          submitValue.endCreateDate = moment(endCreateDate).format('YYYY-MM-DD');
        }else{
          submitValue.startCreateDate = null
          submitValue.endCreateDate = null
        }
        getList({ pageNum: 1, pageSize: 10, ...submitValue })
      }
    });
  }

  const changePageNum = (pageNumber) => {
    let {createDate, ...submitValue}  = props.form.getFieldsValue()
    if(null != createDate && createDate.length > 0){
      const [startCreateDate, endCreateDate] = createDate
      submitValue.startCreateDate = moment(startCreateDate).format('YYYY-MM-DD');
      submitValue.endCreateDate = moment(endCreateDate).format('YYYY-MM-DD');
    }else{
      submitValue.startCreateDate = null
      submitValue.endCreateDate = null
    }
    getList({ pageNum: pageNumber, pageSize: 10, ...submitValue })
  }

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log('selectedRowKeys:', selectedRowKeys, 'selectedRows: ', selectedRows);
      setDemandIdList(selectedRows)
    },
  };


  // 跳转到编辑资讯
  const toEditDemand = (id) => () => {
    router.push({
      pathname: '/sample/demand/edit',
      query: {
        id
      },
    });
  }

  
  const changeStatus = () => {
    if(demandIdList.length < 1){
      message.error('请先选择要删除的数据！')
      return
    }
    const title = '确认将所选的' + demandIdList.length + '条数据删除？可删除条件：需求单状态 为 作废。'
    Modal.confirm({
      title: title,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        request({ ...apis.sample.put, data: { ids: demandIdList.map(x => x.demandId) } }).then((data) => {
          const resultMessage = '操作成功，其中'+data.successNum+'条成功删除，'+data.failNum+'条非作废状态未删除。'
          message.info(resultMessage)
          getList({ pageNum: 1, pageSize: 10 });
        }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
        })
      }
    });
  }
  /**
   *
   *
   * @param {*} props
   * @returns
   */
  const columns = [
    {
      title: '样例名',
      dataIndex: 'sampleName',
      key: 'sampleName',
      align: 'center',
    },
    {
      title: '下单组织',
      dataIndex: 'orgName',
      key: 'orgName',
      align: 'center',
    },
    {
      title: '下单人',
      dataIndex: 'orderer',
      key: 'orderer',
      align: 'center',

    },
    {
      title: '联系方式',
      dataIndex: 'phone',
      key: 'phone',
      align: 'center',
    },
    {
      title: '下单时间',
      dataIndex: 'createDate',
      key: 'createDate',
      align: 'center',
      render: (x, row) => <><span>{`${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
    },
    {
      title: '需求单状态',
      dataIndex: 'demandStatus',
      key: 'demandStatus',
      align: 'center',
      render: (demandStatus) => <span>{demandStatus === 1 ? '已提交' : demandStatus === 2 ? '处理中' : demandStatus === 3 ? '已交付' : demandStatus === 4 ? '作废' : ''}</span>,
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      align: 'center',
      render: (x, row) => (
        <span style={{ color: '#FF925C', cursor: 'pointer' }} onClick={toEditDemand(row.demandId)}>
          查看详情<Icon type="form" className={styles.edit} />
        </span>
      ),
    },
  ];
  function handleReset() {
    props.form.resetFields();
    getList({ pageNum: 1, pageSize: 10 })
  }

  const { getFieldDecorator } = props.form
  return (

    <>
    <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
        <Form.Item>
          {getFieldDecorator('sampleName')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="样例名"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('orgName')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="下单组织"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('orderer')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="下单人"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('phone')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="联系方式"
            />,
          )}
        </Form.Item>
        <Form.Item>
            <span style={{marginRight:'10px'}}>下单时间段：</span>
                {getFieldDecorator('createDate')(
                  <RangePicker placeholder={['开始时间','结束时间']} />
                )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('demandStatus')(
            <Select style={{ width: '180px' }} placeholder="需求单状态">
              <Select.Option value="1">已提交</Select.Option>
              <Select.Option value="2">处理中</Select.Option>
              <Select.Option value="3">已交付</Select.Option>
              <Select.Option value="4">作废</Select.Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className={styles.searchBtn}>
            搜索
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
          </Button>
        </Form.Item>
      </Form>
      <AuthButton name="admin.taNewsType.post" noRight={null}>
        <Button type="danger" className={styles.addBtn} onClick={changeStatus}>删除</Button>
      </AuthButton>
      <Table rowSelection={rowSelection} rowKey="newsType" dataSource={data.records} columns={columns} pagination={false} />
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={changePageNum} current={data.current}/>
      </div>
    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader