"use client"; import {useMemo,useEffect, useState} from "react"; import { useQuery } from "@apollo/client/react"; import { useFormContext, useWatch, Controller } from "react-hook-form"; import { formatFinalPhoneValue, getPhoneCodeBycountryCode } from "@/components/theme/ui/PhoneNumberInput/phoneCodeMetaData"; import { GET_COUNTRY_STATES } from "@/graphql"; import { EMAIL_REGEX, IS_VALID_INPUT, IS_VALID_FULL_PHONE, IS_VALID_PHONECODE } from "@utils/constants"; import InputText from "@/components/theme/ui/InputText"; import Select from "@/components/theme/ui/Select"; import PhoneNumberInput from "@/components/theme/ui/PhoneNumberInput/PhoneNumberInput"; import { LoadingSpinner } from "@components/common/LoadingSpinner"; import { useConfig } from "@utils/hooks/useConfig"; export default function ShippingAddressCheckout () { const {countries} = useConfig(); const { getValues, setValue, register, formState: { errors }, control } = useFormContext() // retrieve all hook methods const countriesOptions = useMemo(() => { return countries.map((country) => ({ value: country.code, label: country.name, id: String(country._id), })) },[countries]); const selectedCountryCode = useWatch({ control, name: 'shippingCountry', }); const selectedCountry = useMemo(() => { return countries.find( (country) => country.code === selectedCountryCode) }, [countries, selectedCountryCode]); const { data: statesData, loading: statesLoading } = useQuery(GET_COUNTRY_STATES, { variables: { countryId: selectedCountry?._id }, skip: !selectedCountryCode, }); let statesOptions: { value: string; label: string, id: string }[] = []; if(statesData) { statesOptions = statesData.countryStates.map((state) => ({ value: state.code, label: state.defaultName, id: String(state._id), })); } // 是否用户手动选择过区号 const [hasUserSelectedPhoneCode, setHasUserSelectedPhoneCode] = useState(false); // 国家变更后 state字段的值需要清空 // 选择国家时同步电话区号 useEffect(() => { const preShippingPhoneNum = getValues('shippingPhoneNumber'); const regPhoneCode = IS_VALID_PHONECODE; if(preShippingPhoneNum && !hasUserSelectedPhoneCode) { const newPhoneCode = getPhoneCodeBycountryCode(selectedCountryCode); const codePart = regPhoneCode.exec(preShippingPhoneNum); let phone = preShippingPhoneNum; if(codePart) { phone = preShippingPhoneNum.replace(codePart[0], ''); } if(codePart && newPhoneCode !== codePart[0].trim()) { return; } setValue('shippingPhoneNumber',formatFinalPhoneValue(newPhoneCode, phone)) } },[selectedCountryCode,hasUserSelectedPhoneCode,getValues,setValue]); return (
) : ( )}
{ return ( setHasUserSelectedPhoneCode(true)} /> ); }} />
); };