import './payment.css';
import {
    Button,
    ConfigProvider,
    DatePicker,
    Divider, Flex,
    Form, GetProp, Image,
    Input,
    InputNumber,
    message,
    Radio,
    Spin,
    Upload, UploadProps,
    Tag
} from "antd";
import {
    ReloadOutlined
} from '@ant-design/icons'
import { useEffect, useRef, useState } from "react";
import locale from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { DevUserId, get, post, uploadImageUrl } from "../../util/AjaxUtils.ts";
import { UploadOutlined } from "@ant-design/icons";
import useMessage from "antd/es/message/useMessage";
import { errorImage } from "../../util/CommonUtil.ts";

dayjs.locale('zh-cn');

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

type FormFieldType = {
    thirdParty: string;
    rechargeMoney: number;
    orgName: string;
    orgBank: string;
    orgNumber: string;
    rechargeFinalTime: string;
    rechargeVoucher: string;
}

type PayType = {
    accountRechargeId: string;
    thirdPartyPayUrl: string;
}

type PaySystemBank = {
    bankAccountName: string;
    bankName: string;
    bankNumber: string;
    bankRemark: string;
    bankUnionpayNumber: string;
}

enum ThirdPartyEnum {
    WX = '微信',
    ZFB = '支付宝',
    DGZZ = '对公转账'
}

interface IPaymentProps {
    handleConfirm(): void;

    handleCancel(): void;
}

export default function Payment(props: IPaymentProps) {
    const [mask, setMask] = useState(false)
    const [form] = Form.useForm<FormFieldType>();
    const [messageApi, messageApiContext] = useMessage();
    const [isRechargeMoneyEdit, setIsRechargeMoneyEdit] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [rechargeVoucherArray, setRechargeVoucherArray] = useState<string[]>([]);
    const [thirdParty, setThirdParty] = useState<ThirdPartyEnum | null>();
    const [accountRechargeId, setAccountRechargeId] = useState('');
    const [thirdPartyPayUrl, setThirdPartyPayUrl] = useState('');
    const [paySystemBank, setPaySystemBank] = useState<PaySystemBank>({
        bankAccountName: '',
        bankName: '',
        bankNumber: '',
        bankRemark: '',
        bankUnionpayNumber: ''
    });
    const [countdownTime, setCountdownTime] = useState('');
    // const [isCountdownTimeout, setIsCountdownTimeout] = useState(false);
    const moneyRange: number[] = [0.01, 2000];
    const countdownIntervalRef = useRef<number | undefined>();
    const [refreshQrCodeCount, setRefreshQrCodeCount] = useState(0);

    /**
     * 倒计时
     */
    const countdown = () => {
        if (countdownIntervalRef.current) {
            clearInterval(countdownIntervalRef.current);
        }
        // if (thirdParty == ThirdPartyEnum.DGZZ) {
        //     return;
        // }
        const Time = new Date().getTime();
        // 设定计时器的时间为60秒
        const countDownDate = new Date(Time + 270 * 1000).getTime();
        // const countDownDate = new Date(Time + 5 * 1000).getTime();
        // 更新计时器的秒数
        const updateCountdown = () => {
            const now = new Date().getTime();
            const distance = countDownDate - now;
            // 将毫秒数转换为分钟和秒数
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);
            // 渲染计时器
            setCountdownTime(minutes + ":" + (seconds < 10 ? "0" : "") + seconds);
            if (distance <= 0) {
                setCountdownTime('已失效');
                // setIsCountdownTimeout(true);
                clearInterval(countdownIntervalRef.current);
                setMask(true)
            }
        }
        // 每秒更新一次计时器
        countdownIntervalRef.current = setInterval(() => {
            updateCountdown();
        }, 1000);
    }

    const getPay = () => {
        post<PayType>({
            messageApi,
            url: '/api/pay/get-pay',
            body: {
                rechargeMoney: form.getFieldValue('rechargeMoney'),
                thirdParty: form.getFieldValue('thirdParty')
            },
            onBefore() {
                setIsLoading(true);
            },
            onSuccess({ data }) {
                // console.log('用户id',data.accountRechargeId);
                
                setAccountRechargeId(data.accountRechargeId);
                setThirdPartyPayUrl(data.thirdPartyPayUrl);
                countdown();
            },
            onFinally() {
                setIsLoading(false);
            }
        })
    }

    const getPaySystemBank = () => {
        get<PaySystemBank>({
            messageApi,
            url: '/api/pay/get-pay-system-bank',
            onSuccess({ data }) {
                setPaySystemBank(data);
            }
        })
    }

    useEffect(() => {
        if (!thirdParty) {
            getPaySystemBank();
            form.setFieldsValue({
                thirdParty: ThirdPartyEnum.DGZZ,
                rechargeMoney: 280
            })
            setThirdParty(ThirdPartyEnum.DGZZ)
            return;
        }
        getPay();
        // countdown()
    }, [thirdParty, refreshQrCodeCount]);


    const renderMoney = () => {
        if (isRechargeMoneyEdit) {
            return (
                <div>
                    <div>
                        <InputNumber min={0.01} max={2000} defaultValue={form.getFieldValue('rechargeMoney')} />
                        <Button type="link" onClick={() => {
                            const money = form.getFieldValue('rechargeMoney');
                            if (money < moneyRange[0]) {
                                form.setFieldValue('rechargeMoney', moneyRange[0]);
                                messageApi.error(`金额最小为${moneyRange[0]}`)
                            } else if (money > moneyRange[1]) {
                                form.setFieldValue('rechargeMoney', moneyRange[1]);
                                messageApi.error(`金额最大为${moneyRange[1]}`)
                            }
                            setIsRechargeMoneyEdit(false);
                            getPay()
                        }}>确定</Button>
                        <span style={{ color: '#1677ff', cursor: 'pointer' }}
                            onClick={() => {
                                setIsRechargeMoneyEdit(false)
                            }}
                        >取消</span>
                    </div>

                </div>
            )
        }
        return (
            <div>
                <div>
                    <span>￥</span>
                    <span style={{ fontWeight: 'bold', fontSize: '16px' }}>{form.getFieldValue('rechargeMoney')}</span>
                    <Button type="link" onClick={() => {
                        setIsRechargeMoneyEdit(true);
                    }}>修改</Button>
                </div>
                <div className='moneyBox' >
                    <Tag style={{ cursor: 'pointer' }} onClick={() => {
                        form.setFieldValue('rechargeMoney', 100);
                        setIsRechargeMoneyEdit(false)
                        getPay()
                    }} color="volcano">100</Tag>
                    <Tag style={{ cursor: 'pointer' }} onClick={() => {
                        form.setFieldValue('rechargeMoney', 200);
                        setIsRechargeMoneyEdit(false)
                        getPay()
                    }} color="volcano">200</Tag>
                    <Tag style={{ cursor: 'pointer' }} onClick={() => {
                        form.setFieldValue('rechargeMoney', 300);
                        setIsRechargeMoneyEdit(false)
                        getPay()
                    }} color="volcano">300</Tag>
                    <Tag style={{ cursor: 'pointer' }} onClick={() => {
                        form.setFieldValue('rechargeMoney', 400);
                        setIsRechargeMoneyEdit(false)
                        getPay()
                    }} color="volcano">400</Tag>
                      <Tag style={{ cursor: 'pointer' }} onClick={() => {
                        form.setFieldValue('rechargeMoney', 500);
                        setIsRechargeMoneyEdit(false)
                        getPay()
                    }} color="volcano">500</Tag>
                </div>
            </div>
        )
    }

    const renderPayBody = () => {
        if (thirdParty == '对公转账') {
            return (
                <div >

                    <div>倒计时:{countdownTime}</div>
                    <div>
                        <Divider orientation="left" plain>收款方信息</Divider>
                        <table className="pay-table">
                            <colgroup>
                                <col width="100" />
                                <col />
                            </colgroup>
                            <tbody>
                                <tr>
                                    <td className="table-label">公司名称</td>
                                    <td>
                                        <span id="bankAccountName">{paySystemBank.bankAccountName}</span>
                                    </td>
                                </tr>
                                <tr>
                                    <td className="table-label">开户银行</td>
                                    <td>
                                        <span id="bankName">{paySystemBank.bankName}</span>
                                    </td>
                                </tr>
                                <tr>
                                    <td className="table-label">银行账号</td>
                                    <td>
                                        <span id="bankNumber">{paySystemBank.bankNumber}</span>
                                    </td>
                                </tr>
                                <tr>
                                    <td className="table-label">银行联行号</td>
                                    <td>
                                        <span id="bankUnionpayNumber">{paySystemBank.bankUnionpayNumber}</span>
                                    </td>
                                </tr>
                                <tr>
                                    <td className="table-label">打款备注</td>
                                    <td>
                                        <div id="bankRemark">{paySystemBank.bankRemark}</div>
                                    </td>
                                </tr>
                                <tr>
                                    <td className="table-label">说明</td>
                                    <td>
                                        <div className="mark">请打款时必须按照以上备注填写</div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div>
                        <Divider orientation="left" plain>付款方信息</Divider>
                        <table className="pay-table">
                            <colgroup>
                                <col width="100" />
                                <col />
                            </colgroup>
                            <tbody>
                                <tr>
                                    <td className="table-label">公司名称 *</td>
                                    <td>
                                        <Form.Item
                                            name="orgName"
                                            style={{ marginBottom: '0' }}
                                            rules={[{ required: true, message: '请输入公司名称' }]}
                                        >
                                            <Input placeholder="请输入公司名称" />
                                        </Form.Item>
                                    </td>
                                </tr>
                                <tr>
                                    <td className="table-label">开户银行 *</td>
                                    <td>
                                        <Form.Item
                                            name="orgBank"
                                            style={{ marginBottom: '0' }}
                                            rules={[{ required: true, message: '请输入开户行' }]}
                                        >
                                            <Input placeholder="请输入开户行" />
                                        </Form.Item>
                                    </td>
                                </tr>
                                <tr>
                                    <td className="table-label">银行账号 *</td>
                                    <td>
                                        <Form.Item
                                            name="orgNumber"
                                            style={{ marginBottom: '0' }}
                                            rules={[{ required: true, message: '请输入银行账号' }]}
                                        >
                                            <Input placeholder="请输入银行账号" />
                                        </Form.Item>
                                    </td>
                                </tr>
                                <tr>
                                    <td className="table-label">打款时间 *</td>
                                    <td>
                                        <Form.Item
                                            name="rechargeFinalTime"
                                            style={{ marginBottom: '0' }}
                                            rules={[{ required: true, message: '请选择打款时间' }]}
                                        >
                                            <ConfigProvider locale={locale}>
                                                <DatePicker showTime placeholder="请选择打款时间"
                                                    onChange={(_date, dateString) => {
                                                        form.setFieldValue('rechargeFinalTime', dateString);
                                                    }} />
                                            </ConfigProvider>
                                        </Form.Item>
                                    </td>
                                </tr>
                                <tr>
                                    <td className="table-label">打款凭证 *</td>
                                    <td>
                                        <Form.Item
                                            name="rechargeVoucher"
                                            style={{ marginBottom: '0' }}
                                            valuePropName="fileList"
                                            getValueFromEvent={(e: any) => {
                                                if (e.file.status === 'done') {
                                                    rechargeVoucherArray.push(e.file.response.data.fileId);
                                                    setRechargeVoucherArray(rechargeVoucherArray);
                                                }
                                                if (e.file.status === 'removed') {
                                                    const idArray = rechargeVoucherArray.filter(item => item != e.file.response.data.fileId);
                                                    setRechargeVoucherArray(idArray);
                                                }
                                                return e.fileList;
                                            }}
                                            rules={[{ required: true, message: '请上传打款凭证' }]}
                                        >
                                            <Upload name="image"
                                                maxCount={2}
                                                action={uploadImageUrl()}
                                                headers={{ 'X-USER-ID': DevUserId }}
                                                beforeUpload={(file: FileType) => {
                                                    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                                                    if (!isJpgOrPng) {
                                                        message.error('只能上传 JPG/PNG 格式文件!');
                                                    }
                                                    return isJpgOrPng;
                                                }}
                                            >
                                                <Button icon={<UploadOutlined />}>上传凭证图片</Button>
                                            </Upload>
                                        </Form.Item>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            )
        }
        return <>
            <Flex gap="middle" align="center" justify="center" vertical>
                <div className="qr-code" style={{ position: 'relative' }}>
                    <div style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', background: "rgba(0,0,0,0.6)", backdropFilter: 'blur(10px)', zIndex: 99, display: isRechargeMoneyEdit ? 'block' : 'none' }}>
                        <div style={{ color: '#fff', width: '100%', height: '100%', fontSize: 30, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                            正在修改,请稍后...
                        </div>
                    </div>
                    <Image src={thirdPartyPayUrl} fallback={errorImage} preview={false} />
                    {/* {
                        isCountdownTimeout ? (
                            <div className="qr-timeout" onClick={() => {
                                setRefreshQrCodeCount(refreshQrCodeCount + 1);
                            }}>
                                <ReloadOutlined />
                                <span className="label">点击刷新</span>
                            </div>
                        ) : <></>
                    } */}
                </div>
                <div>{countdownTime}</div>
            </Flex>
        </>
    }

    return (
        <div style={{ position: 'relative' }}>
            <div style={{ position: 'absolute', width: '100%', height: '100%', top: 0, left: 0, background: 'rgba(0,0,0,0.6)', zIndex: 99, display: mask ? 'block' : 'none' }}>
                <div style={{ color: '#FFF', fontSize: 16, width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }} >
                    <div style={{ cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }} onClick={() => {
                        setMask(false)
                        setRefreshQrCodeCount(refreshQrCodeCount + 1);
                    }}>
                        <div style={{ fontSize: 70 }}><ReloadOutlined /></div>
                        已失效,点击刷新
                    </div>
                </div>
            </div>
            <Spin tip="正在提交..." spinning={isLoading}>
                <Form
                    name="basic"
                    form={form}
                    onFinish={() => {
                        post<any>({
                            messageApi,
                            url: `/api/pay/pay-account-recharge/${accountRechargeId}`,
                            body: {
                                thirdParty: form.getFieldValue('thirdParty'),
                                rechargeMoney: form.getFieldValue('rechargeMoney'),
                                orgName: thirdParty == ThirdPartyEnum.DGZZ ? form.getFieldValue('orgName') : '',
                                orgBank: thirdParty == ThirdPartyEnum.DGZZ ? form.getFieldValue('orgBank') : '',
                                orgNumber: thirdParty == ThirdPartyEnum.DGZZ ? form.getFieldValue('orgNumber') : '',
                                rechargeFinalTime: thirdParty == ThirdPartyEnum.DGZZ ? form.getFieldValue('rechargeFinalTime') : '',
                                rechargeVoucher: thirdParty == ThirdPartyEnum.DGZZ ? rechargeVoucherArray.join(',') : '',
                            },
                            onBefore() {
                                setIsLoading(true);
                            },
                            onSuccess() {
                                props.handleConfirm();
                            },
                            onFinally() {
                                setIsLoading(false);
                            }
                        });
                    }}
                    autoComplete="off"
                >
                    <Form.Item
                        label="支付方式"
                        name="thirdParty"
                        rules={[{ required: true }]}
                    >
                        <Radio.Group onChange={(e) => {
                            form.setFieldValue('thirdParty', e.target.value);
                            setThirdParty(e.target.value);
                            setIsRechargeMoneyEdit(false)
                        }}>
                            <Radio value="微信">微信</Radio>
                            <Radio value="支付宝">支付宝</Radio>
                            {/*<Radio value="银联">银联</Radio>*/}
                            <Radio value="对公转账">对公转账</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="充值金额"
                        name="rechargeMoney"
                        rules={[{ required: true, message: '请输入金额' }]}
                    >
                        {renderMoney()}
                    </Form.Item>
                    {renderPayBody()}
                    <div style={{ marginTop: '15px', textAlign: 'center' }}>
                        <Button type="primary" htmlType="submit" style={{ backgroundColor: 'var(--color-primary)' }}>
                            完成付款
                        </Button>
                        <Button type="default" style={{ marginLeft: '15px' }} onClick={() => {
                            props.handleCancel();
                        }}>关闭窗口</Button>
                    </div>
                </Form>
            </Spin>
            {messageApiContext}
        </div>
    )
}