import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, message, Table, Divider, Tag, Pagination, Modal, Breadcrumb, DatePicker } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import withActions from '@/components/ActionList';
import EditIcon from '@/components/EditIcon';
import apis from '../../../../services/apis';
import AuthButton from '@/components/AuthButton';
import request from '../../../../utils/request';
import Navigate from '@/components/Navigate'
import ShowVoucher from './ShowVoucher';

const { Option } = Select

const { RangePicker } = DatePicker

function RechargeOrder(props) {

    // const [taNoticeList, setTaNoticeList] = useState([])
    const [data, setData] = useState({})

    const [showVoucher, setShowVoucher] = useState({})

    useEffect(() => {
        getList({ pageNum: 1, pageSize: 10 });
    }, [])
    // 查询列表

    const getList = params => {

        const { LocalDate, ...values } = params
        if (LocalDate != null && LocalDate.length > 0) {
            const [refundStartTime, refundEndTime] = LocalDate
            values.refundStartTime = `${moment(refundStartTime).format('YYYY-MM-DDT00:00:00')}Z`;
            values.refundEndTime = `${moment(refundEndTime).format('YYYY-MM-DDT23:59:59')}Z`;
        } else {
            values.refundStartTime = null
            values.refundEndTime = null
        }
        // if (params.refundStartTime) {
        //     params.refundStartTime = `${moment(params.refundStartTime).format('YYYY-MM-DDT00:00:00')}Z`;
        // }
        // if (params.refundEndTime) {
        //     params.refundEndTime = `${moment(params.refundEndTime).format('YYYY-MM-DDT23:59:59')}Z`;
        // }
        request({ ...apis.funds.refundlist, params: { ...values } }).then(data => {
            setData(data)
        })
    }

    function handleSubmit(e) {
        e.preventDefault();
        props.form.validateFields((err, values) => {
            if (!err) {
                // eslint-disable-next-line no-console
                console.log('提交数据: ', values)
                getList({ pageNum: 1, pageSize: 10, ...values })
            }
        });
    }

    const openImg = data => {
        setShowVoucher(
            {
                visible: true,
                bannerList: data,
            },
        )
    }

    function handleReset() {
        props.form.resetFields();

        getList({ pageNum: 1, pageSize: 10 })
    }

    const changePageNum = e => {
        props.form.validateFields((err, values) => {
            if (!err) {
                // eslint-disable-next-line no-console
                console.log('提交数据: ', values)
                getList({ pageNum: e, pageSize: 10, ...values })
            }
        });

    }

    const columns = [
        {
            title: '订单编号',
            dataIndex: 'tradeNo',
            key: 'tradeNo',
            align: 'center',
        },
        {
            title: '退款金额（元）',
            dataIndex: 'amount',
            key: 'amount',
            align: 'center',
            render: (x, row) => <><span>{`${row.amount / 100}`}</span></>,
        },
        {
            title: '退款创建时间',
            dataIndex: 'createDate',
            key: 'createDate',
            align: 'center',
            render: (x, row) => <><span>{`${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
        },
        {
            title: '退款状态',
            dataIndex: 'auditStatus',
            key: 'auditStatus',
            align: 'center',
            // width: '20%',
            render: (x, row) => <><span>{row.auditStatus == 'checking' ? '已申请' : (row.auditStatus == 'agree' ? '已退款' : '已驳回')}</span></>,
        },
        {
            title: '驳回原因',
            dataIndex: 'auditResult',
            key: 'auditResult',
            align: 'center',
            width: '20%',
        },

        {
            title: '退款凭证',
            dataIndex: 'certificateUrlList',
            key: 'certificateUrlList',
            align: 'center',
            render: (x, row) => <>{row.certificateUrlList == null ? '' : <Navigate onClick={() => openImg(x)}>查看</Navigate>}</>,
        },
        {
            title: '操作',
            dataIndex: 'num',
            key: 'num',
            align: 'center',
            render: withActions((text, row) => [

                <EditIcon type="look" text="查看联系人" onClick={() => router.push({
                    pathname: '/funds/financialContact',
                })}> </EditIcon>,


            ]),
        },
    ]

    function download(data) {
        // if (!data) {
        //     console.log('234')
        //     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()
    }

    const exportReport = () => {
        const requestParams = props.form.getFieldsValue();
        const { LocalDate, ...values } = requestParams
        if (LocalDate != null && LocalDate.length > 0) {
            const [refundStartTime, refundEndTime] = LocalDate
            values.refundStartTime = `${moment(refundStartTime).format('YYYY-MM-DDT00:00:00')}Z`;
            values.refundEndTime = `${moment(refundEndTime).format('YYYY-MM-DDT23:59:59')}Z`;
        } else {
            values.refundStartTime = null
            values.refundEndTime = null
        }
        // if (requestParams.refundStartTime) {
        //     requestParams.refundStartTime = `${moment(requestParams.refundStartTime).format('YYYY-MM-DDT00:00:00')}Z`;
        // }
        // if (requestParams.refundEndTime) {
        //     requestParams.refundEndTime = `${moment(requestParams.refundEndTime).format('YYYY-MM-DDT23:59:59')}Z`;
        // }
        request({ ...apis.funds.refundexportList, responseType: 'blob', params: { ...values } }).then(data => {
            download(data)
        }).catch()
    }

    const { getFieldDecorator } = props.form

    return (

        <>
            <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
                <Form.Item>
                    {getFieldDecorator('tradeNo')(
                        <Input
                            placeholder="订单编号"
                        />,
                    )}
                </Form.Item>

                <Form.Item>
                    {getFieldDecorator('LocalDate')(
                        <RangePicker placeholder={['退款开始时间', '退款结束时间']} />,
                    )}
                </Form.Item>
                {/* <Form.Item>
                    {getFieldDecorator('refundStartTime')(
                        <DatePicker placeholder="退款开始时间" />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('refundEndTime')(
                        <DatePicker placeholder="退款结束时间" />,
                    )}
                </Form.Item> */}
                <Form.Item>
                    {getFieldDecorator('auditStatus')(
                        <Select style={{ width: '180px' }} placeholder="退款状态">
                            <Option value="">全部</Option>
                            <Option value="checking">已申请</Option>
                            <Option value="unagree">已驳回</Option>
                            <Option value="agree">已退款</Option>
                        </Select>,
                    )}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit"> 搜索</Button>
                    <Button style={{ marginLeft: 8 }} onClick={handleReset}>重置</Button>
                </Form.Item>
            </Form>
            <div style={{ marginTop: '20px' }}>
                <AuthButton name="admin.funds.account.export" noRight={null}>
                    <Button type="primary" onClick={() => exportReport()} style={{ float: 'right', marginBottom: '20px', zIndex: 1 }} >导出</Button>
                </AuthButton>
            </div>
            <Table dataSource={data.records} columns={columns} pagination={false} style={{ marginTop: '20px' }} />
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
                <Pagination
                    showQuickJumper
                    defaultCurrent={1}
                    total={data.total} onChange={e => changePageNum(e)} current={data.current} />
            </div>
            {showVoucher.visible && <ShowVoucher bannerList={showVoucher.bannerList} closeSwiper={() => setShowVoucher({ visible: false })} />}
        </>

    )
}


const WrappedRechargeOrder = Form.create({ name: 'RechargeOrder' })(RechargeOrder);

export default WrappedRechargeOrder

