AddToCartModal.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. "use client";
  2. import { useState, useMemo } from "react";
  3. import { redirect, RedirectType } from 'next/navigation'
  4. import { useAppDispatch, useAppSelector } from "@/store/hooks";
  5. import { useCustomToast } from "@utils/hooks/useToast";
  6. import {
  7. closeAddToCartDialog,
  8. clearAddToCartProduct
  9. } from '@/store/slices/addToCartDialogSlice';
  10. import { useAddProduct } from "@utils/hooks/useAddToCart";
  11. import Portal from "@/components/Portal";
  12. import {
  13. Drawer,
  14. DrawerContent,
  15. DrawerHeader,
  16. DrawerBody,
  17. DrawerFooter
  18. } from "@heroui/drawer";
  19. import {
  20. ProductOption,
  21. ResolvedVariant
  22. } from "@/components/catalog/type";
  23. import ImgSwiperInAddToCartModal from "./ImgSwiperInAddToCartModal";
  24. import ProductOptionsInAddToCartModal from "./ProductOptionsInAddToCartModal";
  25. import FooterBtnInAddToCartModal from "./FooterBtnInAddToCartModal";
  26. import { Price } from "@components/theme/ui/Price";
  27. import {
  28. isValueAvailable,
  29. isOptionValueAvailable,
  30. getFirstAvailable,
  31. getAvailableVariants,
  32. isCombinationAvailable,
  33. formatFlexibleVariants,
  34. findNearestAvailableVariant
  35. } from "@/utils/variantTools";
  36. export function AddToCartModal() {
  37. const dispatch = useAppDispatch();
  38. const {isOpen, product} = useAppSelector((state) => state.addToCartDialog);
  39. const { isCartLoading, onAddToCart } = useAddProduct();
  40. const { showToast } = useCustomToast();
  41. const images = useMemo(() => {
  42. return product?.images?.edges.map((item) => {
  43. return item.node;
  44. }) ?? [];
  45. },[product?.images]);
  46. const flexibleVariants = useMemo(() => {
  47. return formatFlexibleVariants(product?.flexibleVariants);
  48. },[product?.flexibleVariants]);
  49. const productOptions: ProductOption[] = useMemo(() => {
  50. return product?.productOptions ? JSON.parse(product.productOptions) : [];
  51. },[product?.productOptions]);
  52. // 获取所有可用变体
  53. const availableVariants = useMemo(() => {
  54. return getAvailableVariants(flexibleVariants);
  55. },[flexibleVariants]);
  56. const isSaleable = product?.isSaleable;
  57. const [productQty, setProductQty] = useState(1);
  58. // 记录当前哪个选项组刚刚被点击(用于实现“点击组内全部可点”)
  59. const [lastClickedOptionId, setLastClickedOptionId] = useState<number>(productOptions[0]?.id );
  60. // 当前选中的选项值映射:option_id -> value_id
  61. // useEffect和useMemo的执行时机不同,useMemo早于useEffect(useEffect在浏览器绘制后执行)执行,
  62. // useLayoutEffect早于useEffect执行,useLayoutEffect在浏览器绘制之前执行(官方说会阻塞浏览器绘制)
  63. const [selected, setSelected] = useState<Record<number, number>>(() => {
  64. // if (Object.keys(selected).length === 0) {
  65. let res: Record<number, number> = {};
  66. const defaultSelected = getFirstAvailable(productOptions, flexibleVariants);
  67. if (defaultSelected) {
  68. res = defaultSelected;
  69. } else {
  70. // 极端情况:没有任何可用组合,默认全选每组第一个(但仍需标记为不可用,由禁用逻辑处理)
  71. productOptions.forEach((opt) => {
  72. res[opt.id] = opt.values[0]?.id;
  73. });
  74. }
  75. console.log('set default selected ---- ', res);
  76. return res;
  77. // }
  78. });
  79. // 计算每个选项值的禁用状态
  80. const disabledMap = useMemo(() => {
  81. const map: Record<number, boolean> = {};
  82. if (Object.keys(selected).length === 0) return map; // 没有选中的项
  83. productOptions.forEach((option) => {
  84. option.values.forEach((value) => {
  85. // 规则:如果该选项组是最近点击的组,校验组中的值是否存在可用变体
  86. if (option.id === lastClickedOptionId) {
  87. // map[value.id] = false;
  88. map[value.id] = !isValueAvailable(value.id,availableVariants);
  89. } else {
  90. // 校验其他组的选项值是否可用
  91. map[value.id] = !isOptionValueAvailable(
  92. option.id,
  93. value.id,
  94. selected,
  95. productOptions,
  96. availableVariants
  97. );
  98. }
  99. });
  100. });
  101. return map;
  102. }, [selected, lastClickedOptionId, productOptions, availableVariants]);
  103. // 判断当前选中的组合是否可购买(用于控制购买按钮等)
  104. const isCurrentSelectionAvailable = useMemo(() => {
  105. let res = true;
  106. if(isSaleable !== '1') {
  107. res = false;
  108. } else {
  109. const selectedIds = Object.values(selected);
  110. if (selectedIds.length !== productOptions.length) {
  111. res = false
  112. } else {
  113. res = isCombinationAvailable(selectedIds, availableVariants);
  114. }
  115. }
  116. return res;
  117. }, [selected, productOptions, availableVariants, isSaleable]);
  118. // 获取当前选中变体和价格等信息
  119. const currentVariantInfo: {variant:ResolvedVariant | null; totalLinePrice: number; totalNowPrice: number; save: number;} = useMemo(() => {
  120. const selectedIds = Object.values(selected);
  121. let totalLinePrice = 0;
  122. let totalNowPrice = 0;
  123. let save = 0;
  124. let variant = flexibleVariants.find((v) => {
  125. const vIds = v.optionValues.map((ov) => ov.id);
  126. return selectedIds.length === vIds.length && selectedIds.every((id) => vIds.includes(id));
  127. });
  128. if (selectedIds.length === 0 || variant === undefined) {
  129. // 尚未初始化,返回一个安全占位对象
  130. return { variant: null, totalLinePrice: 0, totalNowPrice: 0, save: 0 };
  131. }
  132. if(variant.priceIndices && variant.priceIndices.length > 0) {
  133. totalLinePrice = Number(variant.priceIndices[0].regular_min_price) * productQty;
  134. totalNowPrice = Number(variant.priceIndices[0].min_price) * productQty;
  135. }
  136. if(totalLinePrice !== totalNowPrice) {
  137. save = -(totalLinePrice - totalNowPrice);
  138. }
  139. return {
  140. variant,
  141. totalLinePrice: totalLinePrice,
  142. totalNowPrice: totalNowPrice,
  143. save: save
  144. };
  145. }, [selected, flexibleVariants, productQty]);
  146. const handleOptionClick = (result:{
  147. clickOptionId: number;
  148. clickValueId: number;
  149. }) => {
  150. // 更新前需要判断当前选中的组合是否可以购买,如果可以购买正常更新;如果不能购买查找可以购买的组合然后更新
  151. let {clickOptionId: optionId, clickValueId: valueId} = result;
  152. let newSelected: Record<number, number> = {...selected,[optionId]: valueId};
  153. let selectedValueIds = Object.values(newSelected);
  154. if(!isCombinationAvailable(selectedValueIds, availableVariants)) {
  155. newSelected = findNearestAvailableVariant(optionId,valueId,{...newSelected},productOptions,availableVariants);
  156. }
  157. setSelected(newSelected);
  158. // 记录当前点击的选项组
  159. setLastClickedOptionId(optionId);
  160. };
  161. async function addProductToCart(action:string = 'addtocart') {
  162. let params = {
  163. productId: String(product?._id),
  164. quantity: productQty,
  165. variantId: currentVariantInfo.variant?._id,
  166. };
  167. let res = await onAddToCart(params);
  168. console.log('onAddToCart run ----- 1');
  169. if(action === 'buynow') {
  170. if(res) {
  171. const responseData = res.data?.createAddProductInCart?.addProductInCart;
  172. if(responseData && responseData.success) {
  173. redirect('/checkout?step=address', RedirectType.push);
  174. }
  175. }
  176. }
  177. }
  178. const addToCartHandler = async (callback: ()=> void) => {
  179. if(!isCurrentSelectionAvailable) {
  180. showToast("The selected options are not available!", "warning");
  181. return;
  182. }
  183. if(currentVariantInfo.variant && !isCartLoading) {
  184. await addProductToCart();
  185. callback();
  186. }
  187. };
  188. const buyNowHandler = async (callback: ()=> void) => {
  189. if(!isCurrentSelectionAvailable) {
  190. showToast("The selected options are not available!", "warning");
  191. return;
  192. }
  193. if(currentVariantInfo.variant && !isCartLoading) {
  194. await addProductToCart('buynow');
  195. callback();
  196. }
  197. };
  198. const closeModal = () => {
  199. dispatch(closeAddToCartDialog());
  200. setTimeout(() => {
  201. dispatch(clearAddToCartProduct());
  202. }, 300);
  203. };
  204. const openChange = (e:boolean) => {
  205. if(!e) {
  206. closeModal();
  207. }
  208. }
  209. return (
  210. <Portal>
  211. <Drawer
  212. backdrop={"blur"}
  213. placement="bottom"
  214. isDismissable={false}
  215. isKeyboardDismissDisabled={true}
  216. isOpen={isOpen}
  217. hideCloseButton
  218. onOpenChange={(e) => openChange(e)}
  219. >
  220. <DrawerContent className="rounded-none h-17/20 max-h-none">
  221. {(onClose) => (
  222. <>
  223. <DrawerHeader className="flex flex-col gap-1">
  224. <div>
  225. Select Options
  226. <button className="absolute top-2.5 right-2.5 w-6 h-6" onClick={onClose}>
  227. <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>
  228. </button>
  229. </div>
  230. {/**产品图片 */}
  231. {images.length > 0 && (
  232. <div>
  233. <ImgSwiperInAddToCartModal images={images} />
  234. </div>
  235. )}
  236. </DrawerHeader>
  237. <DrawerBody className="drawer-body relative">
  238. <div>
  239. {/**产品选项 */}
  240. <div className="box-border w-full">
  241. <ProductOptionsInAddToCartModal
  242. productOptions={productOptions}
  243. selected={selected}
  244. disabledMap={disabledMap}
  245. onOptionClick={handleOptionClick}
  246. />
  247. </div>
  248. </div>
  249. </DrawerBody>
  250. <DrawerFooter className="flex-col border-t border-gray-200 gap-y-4 p-4">
  251. <div className="flex justify-between items-center">
  252. <Price
  253. className="text-ly-14 text-ly-gray line-through"
  254. amount={String(currentVariantInfo.totalLinePrice)}
  255. currencyCode="USD"
  256. />
  257. <div className="flex items-center">
  258. <Price
  259. className="text-ly-14 bg-ly-gold py-0.5 px-1"
  260. amount={String(currentVariantInfo.save)}
  261. currencyCode="USD"
  262. />
  263. <Price
  264. className="text-ly-20 font-bold ml-1.5"
  265. amount={String(currentVariantInfo.totalNowPrice)}
  266. currencyCode="USD"
  267. />
  268. </div>
  269. </div>
  270. <div>
  271. <FooterBtnInAddToCartModal
  272. isAvailable={isCurrentSelectionAvailable}
  273. isLoading={isCartLoading}
  274. onAddToCart={()=> addToCartHandler(onClose)}
  275. onBuyNow={()=> buyNowHandler(onClose)}
  276. />
  277. </div>
  278. </DrawerFooter>
  279. </>
  280. )}
  281. </DrawerContent>
  282. </Drawer>
  283. </Portal>
  284. );
  285. }