AddToCartModal.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. "use client";
  2. import { useState, useMemo } from "react";
  3. import { useRouter } from "next/navigation";
  4. import { Swiper, SwiperSlide } from 'swiper/react';
  5. import Big from 'big.js';
  6. import { useAppDispatch, useAppSelector } from "@/store/hooks";
  7. import { useCustomToast } from "@utils/hooks/useToast";
  8. import {
  9. closeAddToCartDialog,
  10. clearAddToCartProduct
  11. } from '@/store/slices/addToCartDialogSlice';
  12. import { useAddProduct } from "@utils/hooks/useAddToCart";
  13. import {useConfig} from "@/utils/hooks/useConfig";
  14. import { overlayLoading } from "@/components/theme/ui/kernel/loading/api";
  15. import type {
  16. ProductOption,
  17. ResolvedVariant
  18. } from "@/components/catalog/type";
  19. import CommonModal from "@/components/theme/ui/CommonModal";
  20. import ProductOptionsInAddToCartModal from "./ProductOptionsInAddToCartModal";
  21. import { Price } from "@components/theme/ui/Price";
  22. import {
  23. isValueAvailable,
  24. isOptionValueAvailable,
  25. getFirstAvailable,
  26. getAvailableVariants,
  27. isCombinationAvailable,
  28. formatFlexibleVariants,
  29. findNearestAvailableVariant
  30. } from "@/utils/variantTools";
  31. export default function AddToCartModal() {
  32. const router = useRouter();
  33. const dispatch = useAppDispatch();
  34. const {getCurrentCurrencyItem} = useConfig();
  35. const currentCurrency = getCurrentCurrencyItem();
  36. const {isOpen, product} = useAppSelector((state) => state.addToCartDialog);
  37. const { appendProductToCart } = useAddProduct();
  38. const { showToast } = useCustomToast();
  39. const images = useMemo(() => {
  40. return product?.images?.edges.map((item) => {
  41. return item.node;
  42. }) ?? [];
  43. },[product?.images]);
  44. const flexibleVariants = useMemo(() => {
  45. return formatFlexibleVariants(product?.flexibleVariants);
  46. },[product?.flexibleVariants]);
  47. const productOptions: ProductOption[] = useMemo(() => {
  48. const opts = product?.productOptions;
  49. return opts ? JSON.parse(opts) : [];
  50. },[product?.productOptions]);
  51. // 获取所有可用变体
  52. const availableVariants = useMemo(() => {
  53. return getAvailableVariants(flexibleVariants);
  54. },[flexibleVariants]);
  55. const isSaleable = product?.isSaleable;
  56. const [productQty] = useState(1);
  57. // 记录当前哪个选项组刚刚被点击(用于实现“点击组内全部可点”)
  58. const [lastClickedOptionId, setLastClickedOptionId] = useState<number>(productOptions[0]?.id );
  59. // 当前选中的选项值映射:option_id -> value_id
  60. // useEffect和useMemo的执行时机不同,useMemo早于useEffect(useEffect在浏览器绘制后执行)执行,
  61. // useLayoutEffect早于useEffect执行,useLayoutEffect在浏览器绘制之前执行(官方说会阻塞浏览器绘制)
  62. const [selected, setSelected] = useState<Record<number, number>>(() => {
  63. // if (Object.keys(selected).length === 0) {
  64. let res: Record<number, number> = {};
  65. const defaultSelected = getFirstAvailable(productOptions, flexibleVariants);
  66. if (defaultSelected) {
  67. res = defaultSelected;
  68. } else {
  69. // 极端情况:没有任何可用组合,默认全选每组第一个(但仍需标记为不可用,由禁用逻辑处理)
  70. productOptions.forEach((opt) => {
  71. res[opt.id] = opt.values[0]?.id;
  72. });
  73. }
  74. console.log('set default selected ---- ', res);
  75. return res;
  76. // }
  77. });
  78. // 计算每个选项值的禁用状态
  79. const disabledMap = useMemo(() => {
  80. const map: Record<number, boolean> = {};
  81. if (Object.keys(selected).length === 0) return map; // 没有选中的项
  82. productOptions.forEach((option) => {
  83. option.values.forEach((value) => {
  84. // 规则:如果该选项组是最近点击的组,校验组中的值是否存在可用变体
  85. if (option.id === lastClickedOptionId) {
  86. // map[value.id] = false;
  87. map[value.id] = !isValueAvailable(value.id,availableVariants);
  88. } else {
  89. // 校验其他组的选项值是否可用
  90. map[value.id] = !isOptionValueAvailable(
  91. option.id,
  92. value.id,
  93. selected,
  94. productOptions,
  95. availableVariants
  96. );
  97. }
  98. });
  99. });
  100. return map;
  101. }, [selected, lastClickedOptionId, productOptions, availableVariants]);
  102. // 判断当前选中的组合是否可购买(用于控制购买按钮等)
  103. const isCurrentSelectionAvailable = useMemo(() => {
  104. let res = true;
  105. if(isSaleable !== '1') {
  106. res = false;
  107. } else {
  108. const selectedIds = Object.values(selected);
  109. if (selectedIds.length !== productOptions.length) {
  110. res = false
  111. } else {
  112. res = isCombinationAvailable(selectedIds, availableVariants);
  113. }
  114. }
  115. return res;
  116. }, [selected, productOptions, availableVariants, isSaleable]);
  117. // 获取当前选中变体和价格等信息
  118. const currentVariantInfo: {variant:ResolvedVariant | null; totalLinePrice: number; totalNowPrice: number; save: number;} = useMemo(() => {
  119. const selectedIds = Object.values(selected);
  120. let totalLinePrice = 0;
  121. let totalNowPrice = 0;
  122. let save = 0;
  123. const variant = flexibleVariants.find((v) => {
  124. const vIds = v.optionValues.map((ov) => ov.id);
  125. return selectedIds.length === vIds.length && selectedIds.every((id) => vIds.includes(id));
  126. });
  127. if (selectedIds.length === 0 || variant === undefined) {
  128. // 尚未初始化,返回一个安全占位对象
  129. return { variant: null, totalLinePrice: 0, totalNowPrice: 0, save: 0 };
  130. }
  131. if(variant.priceIndices && variant.priceIndices.length > 0) {
  132. totalLinePrice = Big(variant.priceIndices[0].regular_min_price).times(productQty).toNumber();
  133. totalNowPrice = Big(variant.priceIndices[0].min_price).times(productQty).toNumber();
  134. }
  135. if(totalLinePrice !== totalNowPrice) {
  136. save = Big(totalNowPrice).minus(totalLinePrice).toNumber();
  137. }
  138. return {
  139. variant,
  140. totalLinePrice: totalLinePrice,
  141. totalNowPrice: totalNowPrice,
  142. save: save
  143. };
  144. }, [selected, flexibleVariants, productQty]);
  145. const handleOptionClick = (result:{
  146. clickOptionId: number;
  147. clickValueId: number;
  148. }) => {
  149. // 更新前需要判断当前选中的组合是否可以购买,如果可以购买正常更新;如果不能购买查找可以购买的组合然后更新
  150. const {clickOptionId: optionId, clickValueId: valueId} = result;
  151. let newSelected: Record<number, number> = {...selected,[optionId]: valueId};
  152. const selectedValueIds = Object.values(newSelected);
  153. if(!isCombinationAvailable(selectedValueIds, availableVariants)) {
  154. newSelected = findNearestAvailableVariant(optionId,valueId,{...newSelected},productOptions,availableVariants);
  155. }
  156. setSelected(newSelected);
  157. // 记录当前点击的选项组
  158. setLastClickedOptionId(optionId);
  159. };
  160. async function addProductToCart() {
  161. if(!product) {
  162. showToast("Get product detail failed!", "danger");
  163. return;
  164. }
  165. overlayLoading.start();
  166. const params = {
  167. productId: product._id,
  168. quantity: productQty,
  169. variantId: currentVariantInfo.variant?._id,
  170. };
  171. const res = await appendProductToCart({
  172. productId: params.productId,
  173. quantity: params.quantity,
  174. variantId: params.variantId
  175. });
  176. console.log('onAddToCart run ----- 1',res);
  177. overlayLoading.stop();
  178. return res;
  179. }
  180. const addToCartHandler = async () => {
  181. if(!isCurrentSelectionAvailable) {
  182. showToast("The selected options are not available!", "warning");
  183. return;
  184. }
  185. if(currentVariantInfo.variant) {
  186. await addProductToCart();
  187. closeModal();
  188. }
  189. };
  190. const buyNowHandler = async () => {
  191. if(!isCurrentSelectionAvailable) {
  192. showToast("The selected options are not available!", "warning");
  193. return;
  194. }
  195. if(currentVariantInfo.variant) {
  196. const res = await addProductToCart();
  197. closeModal();
  198. if(res && !res.error) {
  199. const responseData = res.data;
  200. if(responseData && responseData.success) {
  201. router.push('/checkout');
  202. }
  203. }
  204. }
  205. };
  206. const closeModal = () => {
  207. dispatch(closeAddToCartDialog());
  208. setTimeout(() => {
  209. dispatch(clearAddToCartProduct());
  210. }, 300);
  211. };
  212. return (<>
  213. <CommonModal
  214. isOpen={isOpen}
  215. onClose={closeModal}
  216. fullyCustomer={true}
  217. contentClassName="absolute box-border transition-transform duration-300 ease-out bottom-0 left-0 w-full p-4 bg-white rounded-t-xl"
  218. body={<>
  219. <div className="flex justify-between items-center text-ly-16">
  220. Select Options
  221. <button className="flex-none w-6 h-6" onClick={closeModal} type="button">
  222. <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" aria-hidden="true" data-slot="icon" className="h-6 transition-all ease-in-out hover:scale-110"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12"></path></svg>
  223. </button>
  224. </div>
  225. {images.length > 0 && (
  226. <div className="w-full mt-4">
  227. <Swiper
  228. spaceBetween={10}
  229. slidesPerView={3}
  230. >
  231. {images.map((img) => {
  232. return (
  233. <SwiperSlide key={img.id} className="w-24 h-32">
  234. <img className="block h-full w-full object-cover" src={img.publicPath} />
  235. </SwiperSlide>
  236. );
  237. })}
  238. </Swiper>
  239. </div>
  240. )}
  241. <div className="box-border w-full mt-6 h-73.75 overflow-y-auto scrollbar-thin scrollbar-thumb-gray-100">
  242. <div className="box-border w-full">
  243. <ProductOptionsInAddToCartModal
  244. productOptions={productOptions}
  245. selected={selected}
  246. disabledMap={disabledMap}
  247. onOptionClick={handleOptionClick}
  248. />
  249. </div>
  250. </div>
  251. <div className="box-border w-full border-t-1 border-[#f2f2f2] mt-1.5 pt-3">
  252. <div className="flex justify-between items-center">
  253. <Price
  254. className="text-ly-14 text-ly-gray line-through"
  255. amount={String(currentVariantInfo.totalLinePrice)}
  256. currencyCode={currentCurrency.code}
  257. />
  258. <div className="flex items-center">
  259. <Price
  260. className="text-ly-14 bg-ly-gold py-0.5 px-1"
  261. amount={String(currentVariantInfo.save)}
  262. currencyCode={currentCurrency.code}
  263. />
  264. <Price
  265. className="text-ly-20 font-bold ml-1.5"
  266. amount={String(currentVariantInfo.totalNowPrice)}
  267. currencyCode={currentCurrency.code}
  268. />
  269. </div>
  270. </div>
  271. {isCurrentSelectionAvailable ?
  272. <>
  273. <div className="flex justify-between gap-3 mt-3">
  274. <button className="flex-1 flex justify-center items-center h-12 text-ly-16 font-bold text-white rounded-3xl bg-ly-deepgreen"
  275. type="button"
  276. onClick={buyNowHandler}
  277. >
  278. Buy now
  279. </button>
  280. <button className="flex-1 flex justify-center items-center h-12 text-ly-16 font-bold text-white rounded-3xl bg-ly-middlegreen"
  281. type="button"
  282. onClick={addToCartHandler}
  283. >
  284. Add to bag
  285. </button>
  286. </div>
  287. {/* <button className="flex justify-center items-center w-full mt-3 h-12 text-ly-16 font-bold text-white rounded-3xl bg-[#ffc43a]" type="button">
  288. <img className="h-6 w-18.75" src="/image/payment/paypal-logo.svg" />
  289. </button> */}
  290. </>
  291. :
  292. <p className="text-center text-ly-14">The selected options are not available!</p>
  293. }
  294. </div>
  295. </>}
  296. />
  297. </>);
  298. }