AddToCartModal.tsx 13 KB

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