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 Swiper from './components/Swiper';
import { regFenToYuan } from '@/utils/money';
import Refund from './components/Refund'

const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

function header(props) {
    // 获取初始化数据
    const [data, setData] = useState({})
    const [row, setRow] = useState({})
    const [demandIdList, setDemandIdList] = useState([])
    const [visible, setVisible] = useState(false)
    const [refundVisible, setRefundVisible] = useState(false)
    const [inputValue, setValue] = useState('')
    const [swiperList, setSwiperList] = useState([])

    const orgId = props.orgId || ''

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

    // 查询列表
    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: 'refund', ...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: 'refund', ...submitValue })
    }
    const look = (list) => {
        setSwiperList(list)
    }
    /**
     *
     *
     * @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: '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',
            render: (x, row) => <><span>{row.auditStatus == 'checking' ? '已申请' : row.auditStatus == 'agree' ? '已退款' : '已驳回'}</span></>
        },
        {
            title: '驳回原因',
            dataIndex: 'auditResult',
            key: 'auditResult',
            align: 'center',
            render: (x, row) => <>{row.tradingStatus == 'fail' && <span>{row.auditResult}</span>}</>
        },
        {
            title: '退款凭证',
            dataIndex: 'certificateUrlList',
            key: 'certificateUrlList',
            align: 'center',
            render: (x, row) => (
                <>
                    {
                        (x || []).length > 0 &&
                        <>

                            <span className={styles.blue} onClick={() => look(row.certificateUrlList)}>
                                查看
                         </span></>
                    }
                </>
            ),
        },
        {
            title: '操作',
            dataIndex: 'handle',
            key: 'handle',
            align: 'center',
            width: '120px',
            render: (x, row) => (
                <>
                    {
                        row.auditStatus == 'checking' &&
                        <>
                            <span style={{ color: '#FF925C', cursor: 'pointer', marginRight: '16px' }} onClick={() => refund(row)}>
                                退款
                    </span>
                            <span style={{ color: '#FF925C', cursor: 'pointer' }} onClick={() => reject(row)}>
                                驳回
                    </span></>
                    }

                </>
            ),
        },

    ];
    function handleReset() {
        props.form.resetFields();
        getList({ pageNum: 1, pageSize: 10, orderType: 'refund' })
    }
    const handleOk = () => {
        if (inputValue) {
            request({
                ...apis.fund.reject, urlData: { id: row.orderId }, data: {
                    auditResult: inputValue,
                    orgId: row.orgId,
                }
            }).then((data) => {
                console.log(data)
                getList({ pageNum: 1, pageSize: 10, orderType: 'refund' });

            })

            setVisible(false)
            setValue('')
        } else {
            message.warning('驳回原因不能为空');
        }

    }

    const handleCancel = () => {
        setVisible(false)
        setRefundVisible(false)
    }
    const reject = row => {
        setVisible(true)
        setRow(row)
    }
    const refund = (row) => {
        setRefundVisible(true)
        console.log(row, 'row')
        setRow(row)
    }

    const toDeatil = () => {
        if (orgId) {
            props.onToDetail()
        } else {
            router.push({
                pathname: '/fundManagement/AccountDetail',
                query: {
                    orgId: row.orgId,
                },
            });
        }
    }
    const bohui = () => {
        setRefundVisible(false)
        setVisible(true)
    }

    const orderRefund = () => {

        getList({ pageNum: 1, pageSize: 10, orderType: 'refund' });

        setRefundVisible(false)
    }
    // 导出
    const exportList = () => {
        const { 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.refundOrderExport, params: { orderType: 'refund', 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="驳回退款"
                onOk={() => handleOk()}
                onCancel={() => handleCancel()}
                footer={[
                    <Button key="back" size="large" onClick={() => handleCancel()}>取消</Button>,
                    <Button key="submit" type="primary" size="large" onClick={() => handleOk()}>确认</Button>,
                ]}
            >
                <div style={{ display: 'flex', alignItems: 'center', margin: '30px 0' }}>驳回原因
                <span style={{ color: 'red' }}>*</span><Input value={inputValue} onChange={e => setValue(e.target.value)} style={{ marginLeft: '10px', width: '80%' }} placeholder="请输入驳回原因" />
                </div>
            </Modal>
            <Modal
                visible={refundVisible}
                title="退款审核"
                onOk={() => orderRefund()}
                onCancel={() => handleCancel()}
                footer={[
                    <Refund key="back" size="large" orgId={row.orgId} accountId={row.accountId} amount={row.amount || '0'} onClick={() => orderRefund()} orderId={row.orderId} />,
                    <Button key="submit" type="primary" size="large" onClick={() => bohui()}>驳回</Button>,
                ]}
            ><div>
                    <p>1.请核对账户余额等是否正常，且预留了足够的活动余额。异常请核对企业账单后与企业相关人员沟通并确认点击驳回申请</p>
                    <p className={styles.flexRow}>
                        <span>退款金额: <span className={styles.red}>{regFenToYuan(row.amount) || '0'}元</span></span>
                        <span>账户余额：<span className={styles.red}>{regFenToYuan(row.availableBalance) || '0'}元</span></span>
                        <span className={styles.blue} onClick={() => toDeatil()}>查看账户详情</span>
                    </p>
                    <p>2.请到微信商户平台使用企业付款或充值订单退款等方式退款，或使用微信转账/银行卡转账/企业对公转账等方式退款</p>
                    <p>3.退款完成后，截图保留凭证并点击确认退款</p>
                </div>
            </Modal>
            < Swiper list={swiperList} onClose={() => setSwiperList([])} />
            <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>
                    {getFieldDecorator('auditStatus')(
                        <Select style={{ width: '180px' }} placeholder="退款状态">
                            <Select.Option value="">全部</Select.Option>
                            <Select.Option value="checking">已申请</Select.Option>
                            <Select.Option value="agree">已退款</Select.Option>
                            <Select.Option value="unAgree">已驳回</Select.Option>
                        </Select>,
                    )}
                </Form.Item>
                <Form.Item>
                    <span style={{ marginRight: '10px' }}>退款时间段：</span>
                    {getFieldDecorator('LocalDate')(
                        <RangePicker 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