AddToCartModal.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 { overlayLoading } from "@/components/theme/ui/kernel/loading/api";
  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 { appendProductToCart } = 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() {
  163. if(!product) {
  164. showToast("Get product detail failed!", "danger");
  165. return;
  166. }
  167. overlayLoading.start();
  168. const params = {
  169. productId: product._id,
  170. quantity: productQty,
  171. variantId: currentVariantInfo.variant?._id,
  172. };
  173. const res = await appendProductToCart({
  174. productId: params.productId,
  175. quantity: params.quantity,
  176. variantId: params.variantId
  177. });
  178. console.log('onAddToCart run ----- 1',res);
  179. overlayLoading.stop();
  180. return res;
  181. }
  182. const addToCartHandler = async (callback: ()=> void) => {
  183. if(!isCurrentSelectionAvailable) {
  184. showToast("The selected options are not available!", "warning");
  185. return;
  186. }
  187. if(currentVariantInfo.variant) {
  188. await addProductToCart();
  189. callback();
  190. }
  191. };
  192. const buyNowHandler = async (callback: ()=> void) => {
  193. if(!isCurrentSelectionAvailable) {
  194. showToast("The selected options are not available!", "warning");
  195. return;
  196. }
  197. if(currentVariantInfo.variant) {
  198. const res = await addProductToCart();
  199. callback();
  200. if(res && !res.error) {
  201. const responseData = res.data;
  202. if(responseData && responseData.success) {
  203. redirect('/checkout', RedirectType.push);
  204. }
  205. }
  206. }
  207. };
  208. const closeModal = () => {
  209. dispatch(closeAddToCartDialog());
  210. setTimeout(() => {
  211. dispatch(clearAddToCartProduct());
  212. }, 300);
  213. };
  214. const openChange = (e:boolean) => {
  215. if(!e) {
  216. closeModal();
  217. }
  218. }
  219. return (
  220. <Drawer
  221. backdrop={"blur"}
  222. placement="bottom"
  223. isDismissable={false}
  224. isKeyboardDismissDisabled={true}
  225. isOpen={isOpen}
  226. hideCloseButton
  227. onOpenChange={(e) => openChange(e)}
  228. >
  229. <DrawerContent className="rounded-none h-17/20 max-h-none">
  230. {(onClose) => (
  231. <>
  232. <DrawerHeader className="flex flex-col gap-1">
  233. <div>
  234. Select Options
  235. <button className="absolute top-2.5 right-2.5 w-6 h-6" onClick={onClose}>
  236. <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>
  237. </button>
  238. </div>
  239. {/**产品图片 */}
  240. {images.length > 0 && (
  241. <div>
  242. <ImgSwiperInAddToCartModal images={images} />
  243. </div>
  244. )}
  245. </DrawerHeader>
  246. <DrawerBody className="drawer-body relative">
  247. <div>
  248. {/**产品选项 */}
  249. <div className="box-border w-full">
  250. <ProductOptionsInAddToCartModal
  251. productOptions={productOptions}
  252. selected={selected}
  253. disabledMap={disabledMap}
  254. onOptionClick={handleOptionClick}
  255. />
  256. </div>
  257. </div>
  258. </DrawerBody>
  259. <DrawerFooter className="flex-col border-t border-gray-200 gap-y-4 p-4">
  260. <div className="flex justify-between items-center">
  261. <Price
  262. className="text-ly-14 text-ly-gray line-through"
  263. amount={String(currentVariantInfo.totalLinePrice)}
  264. currencyCode="USD"
  265. />
  266. <div className="flex items-center">
  267. <Price
  268. className="text-ly-14 bg-ly-gold py-0.5 px-1"
  269. amount={String(currentVariantInfo.save)}
  270. currencyCode="USD"
  271. />
  272. <Price
  273. className="text-ly-20 font-bold ml-1.5"
  274. amount={String(currentVariantInfo.totalNowPrice)}
  275. currencyCode="USD"
  276. />
  277. </div>
  278. </div>
  279. <div>
  280. <FooterBtnInAddToCartModal
  281. isAvailable={isCurrentSelectionAvailable}
  282. onAddToCart={()=> addToCartHandler(onClose)}
  283. onBuyNow={()=> buyNowHandler(onClose)}
  284. />
  285. </div>
  286. </DrawerFooter>
  287. </>
  288. )}
  289. </DrawerContent>
  290. </Drawer>
  291. );
  292. }