AddToCartModal.tsx 18 KB

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