CheckoutModal.tsx 12 KB

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