import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, message, Table, Divider, Tag, Pagination, Modal, DatePicker } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import router from 'umi/router';
import moment from 'moment';
import styles from '../../style/GoodsList.less';
import SelectCity from '../../../components/SelectButton/CitySelect'
import BuildSelect from '../../../components/SelectButton/BuildSelect'
import apis from '../../../services/apis';
import request from '../../../utils/request';
import BatchDel from './components/BatchDel';
import AddDemand from './components/AddDemand';
import AuthButton from '@/components/AuthButton';
import withActions from '@/components/ActionList';
import EditIcon from '@/components/EditIcon';
import Navigate from '@/components/Navigate';

const { Option } = Select;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

const header = props => {
  const sampleId  = props.location.query.id;
  const sampleName = props.location.query.sampleName;
  const [data, setData] = useState({})
  const [demend, setDemend] = useState({})
  const [demandIds, setDemandIds] = useState([])
  const [batchDel, setBatchDel] = useState({visable:false,demandIds:''})
  const [addDemand, setAddDemand] = useState({visable:false})

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

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

  // 跳转到编辑
  const toDetail = rowData => () => {
    if(rowData) {
      router.push({
      pathname: '/h5SampleManager/h5Demand/detail',
      query: {
        id: rowData.demandId,
      },
    });
      return
    }
  }

  /**
   *
   *
   * @param {*} props
   * @returns
   */

  const columns = [
    {
      title: '样例名',
      dataIndex: 'sampleName',
      key: 'sampleName',
      align: 'center',
      render:  (x, row) => <Navigate onClick={toDetail(row)}>{row.sampleName}</Navigate>,
    },
    {
      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: (text, records) => {
        if (records.demandStatus === 1) { return '已提交' }
        if (records.demandStatus === 2) { return '处理中' }
        if (records.demandStatus === 3) { return '已交付' }
        if (records.demandStatus === 4) { return '作废' }
      },
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      align: 'center',
      render: withActions((text, record) =>[ (
        <AuthButton name="admin.h5Demand.detail.get" noRight={null}>
          <EditIcon type="look" text="查看详情" onClick={toDetail(record)}></EditIcon>
        </AuthButton>
      )]
      ),
    },
  ];
  
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log('selectedRowKeys:', selectedRowKeys, 'selectedRows: ', selectedRows);
      setDemandIds(selectedRows)
    },
  };

  const changePageNum = pageNumber => {
    getList({ pageNum: pageNumber, pageSize: 10, ...props.form.getFieldsValue() })
  }

  // 提交事件
  const handleSubmit = (e, props) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        
        if (values.startCreateDate != null){
          values.startCreateDate = moment(values.startCreateDate).format('YYYY-MM-DD HH:mm:ss')
        }
        if (values.endCreateDate != null){
          values.endCreateDate = moment(values.endCreateDate).format('YYYY-MM-DD HH:mm:ss')
        }
        getList({ pageNum: 1, pageSize: 10, ...values })
      }
    });
  }

  //重置搜索
  function handleReset () {
    props.form.resetFields();
    getList({ pageNum: 1, pageSize: 10 })
  }

  function showBatchDel(e){
  
    if (demandIds.length <= 0){
      message.info("请选择数据");
      return;
    }
    setBatchDel(e);
    if(!e.visable){
      getList()
    }
  }

  function addDemandInfo(e){
    setAddDemand(e);
  }

  const { getFieldDecorator } = props.form
  return (

    <>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
        <Form.Item>
          {getFieldDecorator('sampleName',{
            initialValue: sampleName
          })(
            <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>
          {getFieldDecorator('startCreateDate')(
            <DatePicker showTime={{ format: 'HH:mm:ss' }} placeholder="下单时间开始时间"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('endCreateDate')(
            <DatePicker showTime={{ format: 'HH:mm:ss' }} placeholder="下单时间结束时间"/>,
          )}
        </Form.Item>  
        <Form.Item>
          {getFieldDecorator('demandStatus')(
            <Select style={{ width: '180px' }} placeholder="需求单状态">
                <option value="">全部</option>
                <option value="1">已提交</option>
                <option value="2">处理中</option>
                <option value="3">已交付</option>
                <option value="4">作废</option>
            </Select>
          )}
        </Form.Item>
        <Form.Item>
            <AuthButton name="admin.taShareActivity.search" noRight={null}>
                <Button type="primary" htmlType="submit" className={styles.searchBtn}>
                    搜索
                </Button>
            </AuthButton>
            <AuthButton name="admin.taShareActivity.search" noRight={null}>
                <Button style={{ marginLeft: 8 }} onClick={handleReset}>
                        重置
                </Button>
            </AuthButton>
        </Form.Item>
      </Form>
      <AuthButton name="admin.h5Demand.add.post" noRight={null}>
        <Button type="danger" onClick={() => addDemandInfo({visable:true})} className={styles.addBtn}>新增</Button>
      </AuthButton>
      <AuthButton name="admin.h5Demand.del" noRight={null}>
        <Button type="primary" onClick={() => showBatchDel({visable:true, demandIds: demandIds})} className={styles.addBtn} style={{marginLeft:'30px'}}>删除</Button>
      </AuthButton>
      <AddDemand visible={addDemand.visable} onCancel={() => addDemandInfo({visable:false})}></AddDemand>
      <BatchDel visible={batchDel.visable} demandIds={batchDel.demandIds} onCancel={() => showBatchDel({visable:false, demandIds: ''})} onSuccess={() => showBatchDel({visable:false, demandIds:'' })}/>
      <Table rowSelection={rowSelection}
        style={{marginTop:'30px'}} dataSource={data.records} columns={columns} pagination={false} rowKey="activityList" />
      <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
