CheckoutModal.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. if (Platform.OS === "ios")
  136. Alipay.setAlipayScheme("alipay2021005175632205");
  137. appStateSub = AppState.addEventListener(
  138. "change",
  139. async (nextAppState) => {
  140. if (nextAppState === "active" && !isResolved) {
  141. setTimeout(async () => {
  142. if (!isResolved) {
  143. console.log(
  144. "Alipay SDK did not resolve, assuming success or checking...",
  145. );
  146. // Store doesn't have an easy getApplyResult by tradeNo in this scope,
  147. // but if they returned to the app we can just assume success and
  148. // refresh the page to let the backend state reflect.
  149. isResolved = true;
  150. setVerifyLoading(false);
  151. showAlert("支付完成正在核实");
  152. onSuccess();
  153. }
  154. }, 500); // 瞬间回退没有拿到原生支付结果时,0.5秒后默认成功并刷新列表验证
  155. }
  156. },
  157. );
  158. const result = await Alipay.pay(res.payInfo);
  159. if (isResolved) return;
  160. isResolved = true;
  161. setVerifyLoading(false);
  162. console.log("Alipay Result:", result);
  163. if (result?.resultStatus === "9000") {
  164. showAlert("提货成功");
  165. onSuccess();
  166. } else if (result?.resultStatus === "6001") {
  167. showAlert("用户取消支付");
  168. } else {
  169. showAlert("支付未完成");
  170. }
  171. } catch (e: any) {
  172. isResolved = true;
  173. setVerifyLoading(false);
  174. console.error("Alipay Error:", e);
  175. showAlert("调用支付宝失败");
  176. } finally {
  177. setVerifyLoading(false);
  178. if (appStateSub) {
  179. appStateSub.remove();
  180. }
  181. }
  182. } else if (res) {
  183. // Wallet payment or free success
  184. showAlert("提货成功");
  185. onSuccess();
  186. }
  187. } catch (e) {
  188. console.error("提货失败:", e);
  189. // Usually axios interceptor handles error alerts, but just in case
  190. // showAlert('提货失败');
  191. }
  192. setSubmitting(false);
  193. };
  194. return (
  195. <Modal
  196. visible={visible}
  197. transparent
  198. animationType="slide"
  199. onRequestClose={onClose}
  200. >
  201. <View style={styles.overlay}>
  202. <TouchableOpacity
  203. style={styles.overlayBg}
  204. onPress={onClose}
  205. activeOpacity={1}
  206. />
  207. <View style={[styles.container, { paddingBottom: insets.bottom + 20 }]}>
  208. {/* 标题 */}
  209. <View style={styles.header}>
  210. <Text style={styles.title}>提货</Text>
  211. <TouchableOpacity style={styles.closeBtn} onPress={onClose}>
  212. <Text style={styles.closeBtnText}>×</Text>
  213. </TouchableOpacity>
  214. </View>
  215. {loading ? (
  216. <View style={styles.loadingBox}>
  217. <ActivityIndicator size="large" color="#FC7D2E" />
  218. </View>
  219. ) : (
  220. <>
  221. {/* 商品列表 */}
  222. <View style={styles.goodsSection}>
  223. <ScrollView horizontal showsHorizontalScrollIndicator={false}>
  224. {goodsList.map((goods, idx) => (
  225. <View key={idx} style={styles.goodsItem}>
  226. <Image
  227. source={{ uri: goods.data.cover }}
  228. style={styles.goodsImg}
  229. contentFit="contain"
  230. />
  231. <View style={styles.goodsCount}>
  232. <Text style={styles.goodsCountText}>
  233. x{goods.total}
  234. </Text>
  235. </View>
  236. </View>
  237. ))}
  238. </ScrollView>
  239. </View>
  240. {/* 运费 */}
  241. {expressAmount > 0 && (
  242. <View style={styles.feeRow}>
  243. <Text style={styles.feeLabel}>运费</Text>
  244. <Text style={styles.feeValue}>¥{expressAmount}</Text>
  245. </View>
  246. )}
  247. {/* 收货地址 */}
  248. <TouchableOpacity
  249. style={styles.addressSection}
  250. onPress={goToAddress}
  251. >
  252. {!address ? (
  253. <Text style={styles.noAddress}>请填写收货地址</Text>
  254. ) : (
  255. <View style={styles.addressInfo}>
  256. <Text style={styles.addressName}>
  257. {address.contactName} {address.contactNo}
  258. </Text>
  259. <Text style={styles.addressDetail}>
  260. {address.province}
  261. {address.city}
  262. {address.district}
  263. {address.address}
  264. </Text>
  265. </View>
  266. )}
  267. <Text style={styles.arrowIcon}>›</Text>
  268. </TouchableOpacity>
  269. {/* 提交按钮 */}
  270. <TouchableOpacity
  271. style={styles.submitBtn}
  272. onPress={handleSubmit}
  273. disabled={submitting}
  274. >
  275. <ImageBackground
  276. source={{ uri: Images.common.loginBtn }}
  277. style={styles.submitBtnBg}
  278. resizeMode="contain"
  279. >
  280. <Text style={styles.submitBtnText}>
  281. {submitting ? "提交中..." : "确定发货"}
  282. </Text>
  283. </ImageBackground>
  284. </TouchableOpacity>
  285. </>
  286. )}
  287. </View>
  288. </View>
  289. {/* 支付结果轮询确认加载中 */}
  290. <Modal
  291. visible={verifyLoading}
  292. transparent
  293. animationType="fade"
  294. onRequestClose={() => {}}
  295. >
  296. <View style={styles.verifyLoadingOverlay}>
  297. <View style={styles.verifyLoadingBox}>
  298. <ActivityIndicator size="large" color="#ff9600" />
  299. <Text style={styles.verifyLoadingText}>正在确认支付结果...</Text>
  300. </View>
  301. </View>
  302. </Modal>
  303. </Modal>
  304. );
  305. }
  306. const styles = StyleSheet.create({
  307. verifyLoadingOverlay: {
  308. ...StyleSheet.absoluteFillObject,
  309. backgroundColor: "rgba(0,0,0,0.4)",
  310. justifyContent: "center",
  311. alignItems: "center",
  312. zIndex: 9999,
  313. },
  314. verifyLoadingBox: {
  315. backgroundColor: "rgba(0,0,0,0.8)",
  316. padding: 20,
  317. borderRadius: 12,
  318. alignItems: "center",
  319. },
  320. verifyLoadingText: {
  321. color: "#fff",
  322. marginTop: 10,
  323. fontSize: 14,
  324. },
  325. overlay: { flex: 1, justifyContent: "flex-end" },
  326. overlayBg: {
  327. position: "absolute",
  328. top: 0,
  329. left: 0,
  330. right: 0,
  331. bottom: 0,
  332. backgroundColor: "rgba(0,0,0,0.5)",
  333. },
  334. container: {
  335. backgroundColor: "#fff",
  336. borderTopLeftRadius: 15,
  337. borderTopRightRadius: 15,
  338. paddingHorizontal: 14,
  339. },
  340. header: {
  341. flexDirection: "row",
  342. alignItems: "center",
  343. justifyContent: "center",
  344. paddingVertical: 20,
  345. position: "relative",
  346. },
  347. title: { fontSize: 16, fontWeight: "bold", color: "#000" },
  348. closeBtn: {
  349. position: "absolute",
  350. right: 0,
  351. top: 15,
  352. width: 24,
  353. height: 24,
  354. backgroundColor: "#ebebeb",
  355. borderRadius: 12,
  356. justifyContent: "center",
  357. alignItems: "center",
  358. },
  359. closeBtnText: { fontSize: 18, color: "#a2a2a2", lineHeight: 20 },
  360. loadingBox: { height: 200, justifyContent: "center", alignItems: "center" },
  361. goodsSection: { paddingVertical: 10 },
  362. goodsItem: {
  363. width: 79,
  364. height: 103,
  365. backgroundColor: "#fff",
  366. borderRadius: 6,
  367. marginRight: 8,
  368. alignItems: "center",
  369. justifyContent: "center",
  370. position: "relative",
  371. borderWidth: 1,
  372. borderColor: "#eaeaea",
  373. },
  374. goodsImg: { width: 73, height: 85 },
  375. goodsCount: {
  376. position: "absolute",
  377. top: 0,
  378. right: 0,
  379. backgroundColor: "#ff6b00",
  380. borderRadius: 2,
  381. paddingHorizontal: 4,
  382. paddingVertical: 2,
  383. },
  384. goodsCountText: { color: "#fff", fontSize: 10, fontWeight: "bold" },
  385. feeRow: {
  386. flexDirection: "row",
  387. justifyContent: "space-between",
  388. alignItems: "center",
  389. paddingVertical: 8,
  390. },
  391. feeLabel: { fontSize: 14, color: "#333" },
  392. feeValue: { fontSize: 14, color: "#ff6b00", fontWeight: "bold" },
  393. addressSection: {
  394. flexDirection: "row",
  395. alignItems: "center",
  396. paddingVertical: 10,
  397. borderTopWidth: 1,
  398. borderTopColor: "#f0f0f0",
  399. },
  400. noAddress: { flex: 1, fontSize: 16, fontWeight: "bold", color: "#333" },
  401. addressInfo: { flex: 1 },
  402. addressName: { fontSize: 14, color: "#333", fontWeight: "bold" },
  403. addressDetail: { fontSize: 12, color: "#666", marginTop: 4 },
  404. arrowIcon: { fontSize: 20, color: "#999", marginLeft: 10 },
  405. submitBtn: { alignItems: "center", marginTop: 15 },
  406. submitBtnBg: {
  407. width: 260,
  408. height: 60,
  409. justifyContent: "center",
  410. alignItems: "center",
  411. },
  412. submitBtnText: { color: "#000", fontSize: 16, fontWeight: "bold" },
  413. });