CheckoutModal.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. import { Image } from "expo-image";
  2. import Alipay from "expo-native-alipay";
  3. import { useRouter } from "expo-router";
  4. import React, { useEffect, useState } from "react";
  5. import {
  6. ActivityIndicator,
  7. Alert,
  8. AppState,
  9. ImageBackground,
  10. Modal,
  11. Platform,
  12. ScrollView,
  13. StyleSheet,
  14. Text,
  15. TouchableOpacity,
  16. View,
  17. } from "react-native";
  18. import { useSafeAreaInsets } from "react-native-safe-area-context";
  19. import { Images } from "@/constants/images";
  20. import { Address, getDefaultAddress } from "@/services/address";
  21. import { takeApply, takePreview } from "@/services/award";
  22. interface GroupedGoods {
  23. total: number;
  24. data: {
  25. id: string;
  26. cover: string;
  27. spuId: string;
  28. level: string;
  29. name?: string;
  30. };
  31. }
  32. interface CheckoutModalProps {
  33. visible: boolean;
  34. selectedItems: Array<{
  35. id: string;
  36. spu: { id: string; name: string; cover: string };
  37. level: string;
  38. }>;
  39. onClose: () => void;
  40. onSuccess: () => void;
  41. }
  42. export default function CheckoutModal({
  43. visible,
  44. selectedItems,
  45. onClose,
  46. onSuccess,
  47. }: CheckoutModalProps) {
  48. const router = useRouter();
  49. const insets = useSafeAreaInsets();
  50. const [loading, setLoading] = useState(false);
  51. const [verifyLoading, setVerifyLoading] = useState(false);
  52. const [submitting, setSubmitting] = useState(false);
  53. const [address, setAddress] = useState<Address | null>(null);
  54. const [expressAmount, setExpressAmount] = useState(0);
  55. const [goodsList, setGoodsList] = useState<GroupedGoods[]>([]);
  56. const showAlert = (msg: string) => {
  57. if (Platform.OS === "web") window.alert(msg);
  58. else Alert.alert("提示", msg);
  59. };
  60. useEffect(() => {
  61. if (visible && selectedItems.length > 0) {
  62. loadData();
  63. }
  64. }, [visible, selectedItems]);
  65. const loadData = async () => {
  66. setLoading(true);
  67. try {
  68. // 获取默认地址
  69. const addr = await getDefaultAddress();
  70. setAddress(addr);
  71. // 获取提货预览
  72. const ids = selectedItems.map((item) => item.id);
  73. const res = await takePreview(ids, addr?.id || "");
  74. if (res) {
  75. setExpressAmount(res.expressAmount || 0);
  76. }
  77. // 合并相同商品
  78. const goodsMap: Record<string, GroupedGoods> = {};
  79. selectedItems.forEach((item) => {
  80. const key = `${item.spu.id}_${item.level}`;
  81. if (goodsMap[key]) {
  82. goodsMap[key].total += 1;
  83. } else {
  84. goodsMap[key] = {
  85. total: 1,
  86. data: {
  87. id: item.id,
  88. cover: item.spu.cover,
  89. spuId: item.spu.id,
  90. level: item.level,
  91. name: item.spu.name,
  92. },
  93. };
  94. }
  95. });
  96. setGoodsList(Object.values(goodsMap));
  97. } catch (e) {
  98. console.error("加载提货信息失败:", e);
  99. }
  100. setLoading(false);
  101. };
  102. const goToAddress = () => {
  103. onClose();
  104. router.push("/address?type=1" as any);
  105. };
  106. /*
  107. * Handle Submit with Payment Choice
  108. */
  109. const handleSubmit = async () => {
  110. if (!address) {
  111. showAlert("请选择收货地址");
  112. return;
  113. }
  114. if (expressAmount > 0) {
  115. Alert.alert("支付运费", `需支付运费 ¥${expressAmount}`, [
  116. { text: "取消", style: "cancel" },
  117. { text: "钱包支付", onPress: () => processTakeApply("WALLET") },
  118. { text: "支付宝支付", onPress: () => processTakeApply("ALIPAY_APP") },
  119. ]);
  120. } else {
  121. processTakeApply("WALLET");
  122. }
  123. };
  124. const processTakeApply = async (paymentType: string) => {
  125. if (submitting) return;
  126. setSubmitting(true);
  127. try {
  128. const ids = selectedItems.map((item) => item.id);
  129. const res: any = await takeApply(ids, address!.id, paymentType);
  130. console.log("Take Apply Res:", res, paymentType);
  131. if (paymentType === "ALIPAY_APP" && res?.payInfo) {
  132. let appStateSub: any = null;
  133. let isResolved = false;
  134. try {
  135. Alipay.setAlipayScheme("alipay2021005175632205");
  136. appStateSub = AppState.addEventListener(
  137. "change",
  138. async (nextAppState) => {
  139. if (nextAppState === "active" && !isResolved) {
  140. setTimeout(async () => {
  141. if (!isResolved) {
  142. console.log(
  143. "Alipay SDK did not resolve, assuming success or checking...",
  144. );
  145. // Store doesn't have an easy getApplyResult by tradeNo in this scope,
  146. // but if they returned to the app we can just assume success and
  147. // refresh the page to let the backend state reflect.
  148. isResolved = true;
  149. setVerifyLoading(false);
  150. showAlert("支付完成正在核实");
  151. onSuccess();
  152. }
  153. }, 500); // 瞬间回退没有拿到原生支付结果时,0.5秒后默认成功并刷新列表验证
  154. }
  155. },
  156. );
  157. const result = await Alipay.pay(res.payInfo);
  158. if (isResolved) return;
  159. isResolved = true;
  160. setVerifyLoading(false);
  161. console.log("Alipay Result:", result);
  162. if (result?.resultStatus === "9000") {
  163. showAlert("提货成功");
  164. onSuccess();
  165. } else if (result?.resultStatus === "6001") {
  166. showAlert("用户取消支付");
  167. } else {
  168. showAlert("支付未完成");
  169. }
  170. } catch (e: any) {
  171. isResolved = true;
  172. setVerifyLoading(false);
  173. console.error("Alipay Error:", e);
  174. showAlert("调用支付宝失败");
  175. } finally {
  176. setVerifyLoading(false);
  177. if (appStateSub) {
  178. appStateSub.remove();
  179. }
  180. }
  181. } else if (res) {
  182. // Wallet payment or free success
  183. showAlert("提货成功");
  184. onSuccess();
  185. }
  186. } catch (e) {
  187. console.error("提货失败:", e);
  188. // Usually axios interceptor handles error alerts, but just in case
  189. // showAlert('提货失败');
  190. }
  191. setSubmitting(false);
  192. };
  193. return (
  194. <Modal
  195. visible={visible}
  196. transparent
  197. animationType="slide"
  198. onRequestClose={onClose}
  199. >
  200. <View style={styles.overlay}>
  201. <TouchableOpacity
  202. style={styles.overlayBg}
  203. onPress={onClose}
  204. activeOpacity={1}
  205. />
  206. <View style={[styles.container, { paddingBottom: insets.bottom + 20 }]}>
  207. {/* 标题 */}
  208. <View style={styles.header}>
  209. <Text style={styles.title}>提货</Text>
  210. <TouchableOpacity style={styles.closeBtn} onPress={onClose}>
  211. <Text style={styles.closeBtnText}>×</Text>
  212. </TouchableOpacity>
  213. </View>
  214. {loading ? (
  215. <View style={styles.loadingBox}>
  216. <ActivityIndicator size="large" color="#FC7D2E" />
  217. </View>
  218. ) : (
  219. <>
  220. {/* 商品列表 */}
  221. <View style={styles.goodsSection}>
  222. <ScrollView horizontal showsHorizontalScrollIndicator={false}>
  223. {goodsList.map((goods, idx) => (
  224. <View key={idx} style={styles.goodsItem}>
  225. <Image
  226. source={{ uri: goods.data.cover }}
  227. style={styles.goodsImg}
  228. contentFit="contain"
  229. />
  230. <View style={styles.goodsCount}>
  231. <Text style={styles.goodsCountText}>
  232. x{goods.total}
  233. </Text>
  234. </View>
  235. </View>
  236. ))}
  237. </ScrollView>
  238. </View>
  239. {/* 运费 */}
  240. {expressAmount > 0 && (
  241. <View style={styles.feeRow}>
  242. <Text style={styles.feeLabel}>运费</Text>
  243. <Text style={styles.feeValue}>¥{expressAmount}</Text>
  244. </View>
  245. )}
  246. {/* 收货地址 */}
  247. <TouchableOpacity
  248. style={styles.addressSection}
  249. onPress={goToAddress}
  250. >
  251. {!address ? (
  252. <Text style={styles.noAddress}>请填写收货地址</Text>
  253. ) : (
  254. <View style={styles.addressInfo}>
  255. <Text style={styles.addressName}>
  256. {address.contactName} {address.contactNo}
  257. </Text>
  258. <Text style={styles.addressDetail}>
  259. {address.province}
  260. {address.city}
  261. {address.district}
  262. {address.address}
  263. </Text>
  264. </View>
  265. )}
  266. <Text style={styles.arrowIcon}>›</Text>
  267. </TouchableOpacity>
  268. {/* 提交按钮 */}
  269. <TouchableOpacity
  270. style={styles.submitBtn}
  271. onPress={handleSubmit}
  272. disabled={submitting}
  273. >
  274. <ImageBackground
  275. source={{ uri: Images.common.loginBtn }}
  276. style={styles.submitBtnBg}
  277. resizeMode="contain"
  278. >
  279. <Text style={styles.submitBtnText}>
  280. {submitting ? "提交中..." : "确定发货"}
  281. </Text>
  282. </ImageBackground>
  283. </TouchableOpacity>
  284. </>
  285. )}
  286. </View>
  287. </View>
  288. {/* 支付结果轮询确认加载中 */}
  289. <Modal
  290. visible={verifyLoading}
  291. transparent
  292. animationType="fade"
  293. onRequestClose={() => {}}
  294. >
  295. <View style={styles.verifyLoadingOverlay}>
  296. <View style={styles.verifyLoadingBox}>
  297. <ActivityIndicator size="large" color="#ff9600" />
  298. <Text style={styles.verifyLoadingText}>正在确认支付结果...</Text>
  299. </View>
  300. </View>
  301. </Modal>
  302. </Modal>
  303. );
  304. }
  305. const styles = StyleSheet.create({
  306. verifyLoadingOverlay: {
  307. ...StyleSheet.absoluteFillObject,
  308. backgroundColor: "rgba(0,0,0,0.4)",
  309. justifyContent: "center",
  310. alignItems: "center",
  311. zIndex: 9999,
  312. },
  313. verifyLoadingBox: {
  314. backgroundColor: "rgba(0,0,0,0.8)",
  315. padding: 20,
  316. borderRadius: 12,
  317. alignItems: "center",
  318. },
  319. verifyLoadingText: {
  320. color: "#fff",
  321. marginTop: 10,
  322. fontSize: 14,
  323. },
  324. overlay: { flex: 1, justifyContent: "flex-end" },
  325. overlayBg: {
  326. position: "absolute",
  327. top: 0,
  328. left: 0,
  329. right: 0,
  330. bottom: 0,
  331. backgroundColor: "rgba(0,0,0,0.5)",
  332. },
  333. container: {
  334. backgroundColor: "#fff",
  335. borderTopLeftRadius: 15,
  336. borderTopRightRadius: 15,
  337. paddingHorizontal: 14,
  338. },
  339. header: {
  340. flexDirection: "row",
  341. alignItems: "center",
  342. justifyContent: "center",
  343. paddingVertical: 20,
  344. position: "relative",
  345. },
  346. title: { fontSize: 16, fontWeight: "bold", color: "#000" },
  347. closeBtn: {
  348. position: "absolute",
  349. right: 0,
  350. top: 15,
  351. width: 24,
  352. height: 24,
  353. backgroundColor: "#ebebeb",
  354. borderRadius: 12,
  355. justifyContent: "center",
  356. alignItems: "center",
  357. },
  358. closeBtnText: { fontSize: 18, color: "#a2a2a2", lineHeight: 20 },
  359. loadingBox: { height: 200, justifyContent: "center", alignItems: "center" },
  360. goodsSection: { paddingVertical: 10 },
  361. goodsItem: {
  362. width: 79,
  363. height: 103,
  364. backgroundColor: "#fff",
  365. borderRadius: 6,
  366. marginRight: 8,
  367. alignItems: "center",
  368. justifyContent: "center",
  369. position: "relative",
  370. borderWidth: 1,
  371. borderColor: "#eaeaea",
  372. },
  373. goodsImg: { width: 73, height: 85 },
  374. goodsCount: {
  375. position: "absolute",
  376. top: 0,
  377. right: 0,
  378. backgroundColor: "#ff6b00",
  379. borderRadius: 2,
  380. paddingHorizontal: 4,
  381. paddingVertical: 2,
  382. },
  383. goodsCountText: { color: "#fff", fontSize: 10, fontWeight: "bold" },
  384. feeRow: {
  385. flexDirection: "row",
  386. justifyContent: "space-between",
  387. alignItems: "center",
  388. paddingVertical: 8,
  389. },
  390. feeLabel: { fontSize: 14, color: "#333" },
  391. feeValue: { fontSize: 14, color: "#ff6b00", fontWeight: "bold" },
  392. addressSection: {
  393. flexDirection: "row",
  394. alignItems: "center",
  395. paddingVertical: 10,
  396. borderTopWidth: 1,
  397. borderTopColor: "#f0f0f0",
  398. },
  399. noAddress: { flex: 1, fontSize: 16, fontWeight: "bold", color: "#333" },
  400. addressInfo: { flex: 1 },
  401. addressName: { fontSize: 14, color: "#333", fontWeight: "bold" },
  402. addressDetail: { fontSize: 12, color: "#666", marginTop: 4 },
  403. arrowIcon: { fontSize: 20, color: "#999", marginLeft: 10 },
  404. submitBtn: { alignItems: "center", marginTop: 15 },
  405. submitBtnBg: {
  406. width: 260,
  407. height: 60,
  408. justifyContent: "center",
  409. alignItems: "center",
  410. },
  411. submitBtnText: { color: "#000", fontSize: 16, fontWeight: "bold" },
  412. });