CheckoutModal.tsx 12 KB

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