import { MyBetaModalFormProps, MyButtons, MyModalFormProps } from '@/common';
import { Apis } from '@/gen/Apis';
import { HouseBillsBillStatusEnum } from '@/gen/Enums';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Form, QRCode, Tabs } from 'antd';
import { useState } from 'react';

export default function ShowQrCode(props: MyBetaModalFormProps) {
  const [form] = Form.useForm();
  const [activeTab, setActiveTab] = useState<string>('wechat');
  const [wechatQrCode, setWechatQrCode] = useState<string>('');
  const [alipayQrCode, setAlipayQrCode] = useState<string>('');
  const [orderInfo, setOrderInfo] = useState<any>(null);

  const fetchQrCode = (type: 'wechat' | 'alipay') => {
    if (props?.item?.amount && props?.item?.accept_amount) {
      const amount = parseFloat(props?.item?.total_payable_amount || '0');
      const params = {
        amount: amount,
        total_payable_amount: amount,
        bill_ids: [props?.item?.id],
      };

      if (type === 'wechat') {
        Apis.HouseOrder.HouseOrders.GetPayCode(params).then((res: any) => {
          setWechatQrCode(res?.data?.qr_code || '');
          setOrderInfo(res?.data?.order);
        });
      } else {
        Apis.HouseOrder.HouseOrders.AlipayQrCode(params).then((res: any) => {
          // 支付宝返回的 qr_code 是对象，实际链接在 payinfo 字段
          setAlipayQrCode(res?.data?.qr_code?.payinfo || '');
          setOrderInfo(res?.data?.order);
        });
      }
    }
  };

  return (
    <BetaSchemaForm<ApiTypes.Refund.Refunds.Complete>
      {...MyModalFormProps.props}
      title={props.title}
      width="500px"
      wrapperCol={{ span: 24 }}
      trigger={
        <MyButtons.Default
          type="primary"
          size="small"
          title={props.title}
          disabled={
            props?.item?.bill_status === HouseBillsBillStatusEnum.Paid.value ||
            props?.item?.bill_status ===
              HouseBillsBillStatusEnum.Cancelled.value
          }
        />
      }
      form={form}
      submitter={false}
      onOpenChange={(open: any) => {
        if (open) {
          setWechatQrCode('');
          setAlipayQrCode('');
          setOrderInfo(null);
          setActiveTab('wechat');
          fetchQrCode('wechat');
        }
      }}
      columns={[
        {
          title: '',
          colProps: { span: 24 },
          key: 'qrcode',
          renderFormItem() {
            return (
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: '16px', fontWeight: 'bold', marginBottom: '16px' }}>
                  {props?.item?.asset_house?.full_name}
                </div>
                <Tabs
                  activeKey={activeTab}
                  onChange={(key) => {
                    setActiveTab(key);
                    if (key === 'wechat' && !wechatQrCode) {
                      fetchQrCode('wechat');
                    } else if (key === 'alipay' && !alipayQrCode) {
                      fetchQrCode('alipay');
                    }
                  }}
                  items={[
                    {
                      key: 'wechat',
                      label: '微信支付',
                      children: (
                        <div
                          style={{
                            display: 'flex',
                            padding: '20px 0',
                            justifyContent: 'center',
                          }}
                        >
                          {wechatQrCode ? (
                            <img
                              style={{ width: '220px', height: '220px' }}
                              src={wechatQrCode}
                              alt="微信支付二维码"
                            />
                          ) : (
                            <div style={{ width: '220px', height: '220px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                              加载中...
                            </div>
                          )}
                        </div>
                      ),
                    },
                    {
                      key: 'alipay',
                      label: '支付宝支付',
                      children: (
                        <div
                          style={{
                            display: 'flex',
                            padding: '20px 0',
                            justifyContent: 'center',
                          }}
                        >
                          {alipayQrCode ? (
                            <QRCode value={alipayQrCode} size={220} />
                          ) : (
                            <div style={{ width: '220px', height: '220px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                              加载中...
                            </div>
                          )}
                        </div>
                      ),
                    },
                  ]}
                />
                <div style={{ fontSize: '16px', fontWeight: 'bold' }}>
                  支付金额：
                  <span style={{ color: '#f00' }}>
                    ¥
                    {(
                      parseFloat(orderInfo?.total_payable_amount || '0') || 0
                    ).toFixed(2)}
                    元
                  </span>
                </div>
                <div>收款单ID：{orderInfo?.id || ''}</div>
              </div>
            );
          },
        },
      ]}
    />
  );
}
