CheckoutModal.tsx 12 KB

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