import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Form, Pagination, Button, Icon, message, 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';
import { regFenToYuan } from '@/utils/money';

const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

function header(props) {
    // 获取初始化数据
    const [data, setData] = useState({})
    const [visible, setVisible] = useState(false)
    const [demandIdList, setDemandIdList] = useState([])
    const [personInfo, setPersonInfo] = useState({})
    const orgId = props.orgId || ''
    useEffect(() => {
        getList({ pageNum: 1, pageSize: 10, orderType: 'RedPacket' });
    }, [])

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


    // 提交事件
    const handleSubmit = (e, props) => {
        e.preventDefault();
        props.form.validateFields((err, values) => {
            if (!err) {
                let { LocalDate, ...submitValue } = values
                if (null != LocalDate && LocalDate.length > 0) {
                    const [startDate, endDate] = LocalDate
                    submitValue.startDate = `${moment(startDate).format('YYYY-MM-DDT00:00:00')}Z`;
                    submitValue.endDate = `${moment(endDate).format('YYYY-MM-DDT23:59:59')}Z`;
                } else {
                    submitValue.startDate = null
                    submitValue.endDate = null
                }
                getList({ pageNum: 1, pageSize: 10, orderType: 'RedPacket', ...submitValue })
            }
        });
    }

    const changePageNum = (pageNumber) => {
        let { LocalDate, ...submitValue } = props.form.getFieldsValue()
        if (null != LocalDate && LocalDate.length > 0) {
            const [startDate, endDate] = LocalDate
            submitValue.startDate = `${moment(startDate).format('YYYY-MM-DDT00:00:00')}Z`;
            submitValue.endDate = `${moment(endDate).format('YYYY-MM-DDT23:59:59')}Z`;
        } else {
            submitValue.startDate = null
            submitValue.endDate = null
        }
        getList({ pageNum: pageNumber, pageSize: 10, orderType: 'RedPacket', ...submitValue })
    }

    /**
     *
     * @param {*} props
     * @returns
     */
    const columns = [
        {
            title: '订单编号',
            dataIndex: 'tradeNo',
            key: 'tradeNo',
            align: 'center',
        },
        {
            title: '消费组织',
            dataIndex: 'miniAppName',
            key: 'miniAppName',
            align: 'center',
        },
        {
            title: '消费金额',
            dataIndex: 'amount',
            key: 'amount',
            align: 'center',
            render: (x, row) => <span>{regFenToYuan(x)}</span>
        },
        {
            title: '消费方式',
            dataIndex: 'consumeType',
            key: 'consumeType',
            align: 'center',
            render: (x, row) => <><span>{row.consumeType == 'RedPacket' ? '红包' : ''}</span></>
        },
        {
            title: '活动名称',
            dataIndex: 'activityName',
            key: 'activityName',
            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: 'phone',
            key: 'phone',
            align: 'center',
            render: (x, row) => <><span className={styles.blue} onClick={() => Info(row)}>{row.phone || '13160056114'}</span></>
        },
        {
            title: '消费状态',
            dataIndex: 'tradingStatus',
            key: 'tradingStatus',
            align: 'center',
            render: (x, row) => <><span>{row.tradingStatus == 'success' ? '成功' : '失败'}</span></>
        },

    ];
    const Info = (row) => {
        request({ ...apis.fund.receiveInfo, params: { phone: row.phone, orgId: row.orgId } }).then((data) => {
            setPersonInfo(data)
            setVisible(true)
        })
    }

    function handleReset() {
        props.form.resetFields();
        getList({ pageNum: 1, pageSize: 10, orderType: 'RedPacket' })
    }
    // 导出
    const exportList = () => {
        let { LocalDate, ...submitValue } = props.form.getFieldsValue()
        if (null != LocalDate && LocalDate.length > 0) {
            const [startDate, endDate] = LocalDate
            submitValue.startDate = `${moment(startDate).format('YYYY-MM-DDT00:00:00')}Z`;
            submitValue.endDate = `${moment(endDate).format('YYYY-MM-DDT23:59:59')}Z`;
        } else {
            submitValue.startDate = null
            submitValue.endDate = null
        }
        request({ ...apis.fund.consumeOrderExport, params: { orderType: 'RedPacket', orgId, ...submitValue } }).then(data => {
            if (!data) {
                return
            }
            const url = window.URL.createObjectURL(new Blob([data]))
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '消费订单表.xlsx')
            document.body.append(link)
            link.click()
        }).catch()
    }
    const { getFieldDecorator } = props.form

    const lastColumns = props.organize == 'hidden' ? columns.filter(x => x.title != '消费组织') : columns
    return (

        <>
            <Modal
                visible={visible}
                title="接收人消息"
                onCancel={() => setVisible(false)}
                footer={null}
            >
                <div style={{ paddingLeft: '36%' }}>
                    <p>昵称：{personInfo.nickname || ''}</p>
                    <p>头像：<img src={personInfo.avatarurl || ''} className={styles.touxiang} /></p>
                    <p>姓名：{personInfo.name || personInfo.nickname}</p>
                    <p>手机号：{personInfo.phone || ''}</p>
                </div>

            </Modal>
            <Form layout="inline" onSubmit={e => handleSubmit(e, props)} style={{ marginBottom: '16px' }}>
                <Form.Item>
                    {getFieldDecorator('tradeNo')(
                        <Input
                            prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="订单编号"
                        />,
                    )}
                </Form.Item>
                {
                    props.organize != 'hidden' &&
                    <Form.Item>
                        {getFieldDecorator('miniAppName')(
                            <Input
                                prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                placeholder="消费组织"
                            />,
                        )}
                    </Form.Item>
                }
                <Form.Item>
                    <span style={{ marginRight: '10px' }}>消费时间段：</span>
                    {getFieldDecorator('LocalDate')(
                        <RangePicker placeholder={['开始时间', '结束时间']} />
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('itemType')(
                        <Select style={{ width: '180px' }} placeholder="消费方式">
                            <Select.Option value="">全部</Select.Option>
                            <Select.Option value="RedPacket">红包</Select.Option>
                        </Select>,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('tradingStatus')(
                        <Select style={{ width: '180px' }} placeholder="消费状态">
                            <Select.Option value="">全部</Select.Option>
                            <Select.Option value="success">成功</Select.Option>
                            <Select.Option value="fail">失败</Select.Option>
                        </Select>,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('receivePhone')(
                        <Input
                            prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
                            placeholder="接收人手机号"
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit" className={styles.searchBtn}>
                        搜索
          </Button>
                    <Button style={{ marginLeft: 8 }} onClick={handleReset}>
                        重置
          </Button>
                </Form.Item>
            </Form>
            <div>
                <Button type="danger" style={{ float: 'right', marginBottom: '20px', zIndex: 1 }} onClick={() => exportList()} >导出</Button>
            </div>
            <Table rowKey={r => r.tradeNo} dataSource={data.records} columns={lastColumns} 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