"use client"; import Image from "next/image"; import { type Ref, useEffect, useImperativeHandle } from "react"; import { useForm, get } from "react-hook-form"; import {useConfig} from "@/utils/hooks/useConfig"; import {getPaymentMethodLogo,getPaymentDescription} from "@/utils/paymentTools"; import type { CheckoutPaymentMethod } from "@/types/checkout/type"; import AirwallexCardInput from "./PaymentMethodAdditional/AirwallexCardInput"; import {useAirwallexCardState} from "@/lib/Airwallex/useAirwallexCard"; /** * 关于如何确定默认选中哪个支付方式: * 从购物车详情中获取支付方式 A,支付方式列表中有A,那么把A标记为默认选中;如果支付方式列表中没有A,把paypal标记为默认选中; */ export interface RefPaymentMethodsHandle { getSelectPaymentMethod: () => string; getSelectPaymentTitle: () => string; validatePaymentMethod: () => Promise; } export function PaymentMethodCheckout({ ref, paymentMethods, selectedPaymentMethod, grandTotal, onPaymentMethodChange, }: { ref: Ref; paymentMethods: CheckoutPaymentMethod[]; selectedPaymentMethod: string; grandTotal: number; onPaymentMethodChange: (value: string) => Promise; }) { const {getCurrentCurrencyItem} = useConfig(); const currentCurrency = getCurrentCurrencyItem(); const currencySymbol = currentCurrency.symbol; const airwallexCardState = useAirwallexCardState(); const { register, getValues, trigger, reset, formState: { errors } } = useForm({ mode: "onChange", reValidateMode: "onChange", // defaultValues: { // paymentMethod: defaultValue, // } }); // 参考 https://github.com/react-hook-form/error-message/blob/master/src/ErrorMessage.tsx const paymentMethodError = get(errors, "paymentMethod"); const paymentMethodOnChange = async (event: React.ChangeEvent) => { onPaymentMethodChange(event.target.value); }; useEffect(() => { let defaultValue = ''; const findItem = paymentMethods.find((item) => item.method === selectedPaymentMethod); if(findItem !== undefined) { defaultValue = selectedPaymentMethod; } else { paymentMethods.forEach((item) => { if(item.method === 'paypal_smart_button') { defaultValue = item.method; } }); } reset({ paymentMethod: defaultValue }); },[paymentMethods,selectedPaymentMethod]); useImperativeHandle(ref, () => { return { // 获取用户选择的支付方式 getSelectPaymentMethod: () => { return getValues('paymentMethod'); }, getSelectPaymentTitle: () => { const nowValue = getValues('paymentMethod'); const findItem = paymentMethods.find((item) => item.method === nowValue); return findItem?.title ?? ''; }, // 触发校验 validatePaymentMethod: () => { return trigger(); } } },[paymentMethods]); const airwallexOtherInfoShow = selectedPaymentMethod === 'airwallex' && airwallexCardState.cardNumberReady && airwallexCardState.expiryReady && airwallexCardState.cvcReady; const genetePaymentTips = (payment: string) => { return getPaymentDescription({ payment: payment, grandTotal: grandTotal, symble: currencySymbol }) }; return (<>
    { paymentMethods.map((item) => { return (
  • { item.method === "airwallex" &&
    }
  • ) }) }
{paymentMethodError &&

{paymentMethodError.message}

}
); }