CheckoutModal.tsx 12 KB

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