[\s\S]*<\/div>/g.exec(data.description);if(sizeAll && sizeAll[0]) {$(sizeAll[0]).find('.sizeContainer').each(function(element) {sizeAllHtml.push($(this).html().replace(/
[\s\S]*<\/div>/, ''))})}// setSkuInfoBuyIndex();// 加载完数据处理$('.CartSkuSelect_loading').hide()$('.CartSkuSelect_box, .CartSkuSelect_confirm').fadeIn(100);handleBriefProductTrackShow();}})})resovle()})};// 初始化面板function handleInit(data) {options = data.options;variantsObject = data.variants;var colorStyle = findProductMetafieldsByKey(gqlData, 'skc_attributes') || {}var selectOptions = [];if (id) {variant = findVariantById(id); // 当前选中的selectOptions = variant.options;} else {selectOptions = [options[0].values[0]]}if(options) {var html = "";options.forEach(function(element, index) {var isColor = element.name == 'Color';var isSize = element.name == 'Size';var str = `
`;var str2 = '';element.values.forEach(function(element2, index2) {str2 += `
${isColor?getColorBgURL(element2):element2}
`})str += `
${str2}
`;str = `
${str}
`;html += str;});$('.CartSkuSelect_selectbox').html(html);// 简易处理 setTimeout(function() {handlePopupAll()}, 10)}};function handleOptionsStatus(data) { var ProductOptions = data.options; var optionsValue = {}; // 所有规格属性 var selectOptions = Array(ProductOptions.length).fill(''); // 选中规格 ProductOptions.forEach((option, index) => {const key = option.name; optionsValue[key] = []; $(`.variant-button[data-name="${key}"]`).each(function () { optionsValue[key].push($(this).attr('data-value')) }); selectOptions[index] = $(`.on.variant-button[data-name="${key}"]`).attr('data-value') || '' }) var skus = {}; data.variants.forEach(item => { skus[`${item.options.join(';')}`] = item.available ? 1 : 0 }); // 判断库存 const hasSku = (reg) => Object.keys(skus).some(key => { const result = key.search(reg) > -1; if (result) { return skus[key] > 0; // 找到了再判断是否还有库存 } return false }) // 生成reg const genReg = (args) => args.reduce((acc, cur, idx) => { if (idx === 0) { return acc += cur ? `^(${cur})` : '' } if (idx === args.length - 1) { return acc += cur ? `;(${cur})$` : '' } return acc += cur ? `;(${cur})` : '.+' }, '') const renderOption = (key) => { const optionIndex = ProductOptions.findIndex((option) => option.name === key); return optionsValue[key].map(current => { const currentOption = [...selectOptions] currentOption[optionIndex] = current const reg = genReg(currentOption) const disabled = !hasSku(new RegExp(reg)) $(`.variant-button[data-value="${current}"]`)[disabled ? 'addClass' : 'removeClass']('disabled'); return { current, disabled } }) } ProductOptions.forEach((option) => { renderOption(option.name); }); };// 查找选中SKUfunction findVariantById(id) {return variantsObject.find(item => item.id == id);};// 找到选中颜色与Size按钮Domfunction findVariantByDom() {var result = []$('.variant-wrappers .variant-button.on').each((idx, ele) => {result.push($(ele).data('value'))})return variantsObject.find(item => item.options.toString() == result.toString())};window.handleOptionClick = async function(e) {$(e).parent().find('.variant-button').removeClass('on');$(e).addClass('on');handlePopupAll()};/* 处理图片列表定位、sku展示价格 , 预售时间, 展示tips等 */function handlePopupAll() {handleOptionsStatus(product)variant = findVariantByDom();handleSkuPrice();handleConfirmStyle();handlePreOrderTime();handleScrollImagePosition();handleOptionsTips();}/*处理价格*/function handleSkuPrice() {if (variant && variant.compare_at_price && variant.price) {var hasDeletePrice = variant.compare_at_price > variant.price$('.CartSkuSelect_price__origin span').text(hasDeletePrice ? `$${(variant.compare_at_price/100).toFixed(2)}`:'')$('.CartSkuSelect_price__true')[hasDeletePrice?'addClass':'removeClass']('CartSkuSelect_price__trueRed').find('span').text(`$${(variant.price/100).toFixed(2)}`);}};function handleOptionsTips() {if (window.detailOptionTips) {window.detailOptionTips.forEach(item => {var key = $(`.variant-button.on[data-name="${item.key}"`).text();var tipsbox = $(`.variant-wrappers-tips[data-name="${item.key}"]`);if (key) {tipsbox && tipsbox.html(item.options[key]) } else {tipsbox && tipsbox.html() }})}};// 处理滚动定位的与颜色处理function handleScrollImagePosition() {// 如果有选中的颜色var color = $(".variant-button.variant-button__bgp.on").attr("data-value");var imgid = null;if (color) {var find = variantsObject.find(item => item.option1 == color);if (find) {imgid = find.featured_media.id;}$("#variant_Color").text(color);}if (imgid) {var current = ".CartSkuSelect_imglist li[data-id="+imgid+"]";$('.CartSkuSelect_imglist ul').animate({scrollLeft: $(current)[0].offsetLeft - 16}, 100);}};// 处理Pre Order Timefunction handlePreOrderTime() {var result = false;var color = $(".variant-button.variant-button__bgp.on").attr("data-value");var baseTime = 60 * 60 * 24 * 3 * 1000;if (preOrderTime) {var colorVariants = variantsObject.filter(item => item.option1 == color);$('.variant-button[data-name="Size"]').removeAttr('data-arriva-time');colorVariants.forEach(item => {preOrderTime.forEach(item2 => {if (item.sku == item2.sku_code && item.available) {var timeEnd = new Date(item2.arriva_date).getTime();var now = Date.now();if ((timeEnd - now) > baseTime) {$(`.variant-button[data-value="${item.option2}"]`).attr('data-arriva-time', '');}}})})}if (variant && preOrderTime) { var current = preOrderTime.find(function(item) {return item.sku_code == variant.sku }) var now = Date.now() var result = current && new Date(current.arriva_date).getTime() - now > baseTime;}if (result) {$('.CartSkuSelect_pretime').html(`Pre-order:Estimated to ship by ${theme.dateTransform(current.arriva_date)}`).show();var dayDiff = new Date(current.arriva_date).getTime() - new Date().getTime()$('.CartSkuSelect_pretime').attr('data-value', Math.ceil(dayDiff / (1000 * 3600 * 24)));} else {$('.CartSkuSelect_pretime').hide();$('.CartSkuSelect_pretime').attr('data-value', 0);}};// 批量处理按钮状态, 现在是disabed掉function handleOptionsHide() {var list = document.querySelectorAll('.variant-button');for(let i = 0; i < list.length; i++) {// list[i].classList.remove('disabled');if (optionsMerger) {list[i].classList.add('disabled');} else {list[i].classList.add('disabled');}}};// 处理确认按钮$('.CartSkuSelect_confirm').click(function(e) {if (!variant) {theme.toast.show({message: "Please Choose Size"})return}if (!id) {handleCartAdd(variant.id);return}if(variant.id == id) {closeModal()return}handleCartOptions();});// 处理颜色背景图function getColorBgURL(color) {var bgImage = ''if (skcPictureUrls && skcPictureUrls[color]) {bgImage = skcPictureUrls[color]} else {var findOne = variantsObject.find(item => item.option1 == color && item.featured_image && item.featured_image.src);bgImage = `${findOne.featured_image.src}&width=200`}return `
`}; // sku购物车操作 function handleCartOptions() {var findOne = gqlData.variants.nodes.find(item => item.id.includes(variant.id)); // 切换判断是否超限制 var postData = [ { sku: sku, variant_id: parseInt(id), chosen: chosen, action_time: Date.now(), deleted: true,product_type: 1, quantity: 0 }, { sku: variant.sku, variant_id: variant.id, chosen: chosen, action_time: Date.now(), deleted: false,product_type: 1, quantity: !findOne.availableForSale ? 0 : parseInt(qty) <= findOne.quantityAvailable ? parseInt(qty) : (findOne.quantityAvailable || 1) } ];handleCartAddTrackClick(); document.dispatchEvent(new CustomEvent("cart:variant.cart-drawer", { detail: { data: postData } })); };// 加购async function handleCartAdd(id) {await theme.ShopCart.addToCart(id, variant.sku, variant.price / 100) // 加购// wishList的时候会调用moveToCartConfirmif (window.moveToCartConfirm) {window.moveToCartConfirm() // 调用加购} else {theme.toast.show({message: "Added Successfully!", type:"success"});}document.dispatchEvent(new CustomEvent("cart:addCartSuccess", {status: true}));// 补加购事件handleCartAddTrackClick()closeModal()};// 刷新购物车function refreshCart(e) {document.dispatchEvent(new CustomEvent("cart:build"), {detail: {}})};// 格式化图片function formatImgUrl(url) {return url.replace(/(\.[^.]*)$/, "_180x$1")};// 处理状态function handleConfirmStyle() {if(!variant || !variant.available) {$('.CartSkuSelect_confirm').attr('disabled', true).text(!variant ?'Add to Cart':'Sold Out')} else {$('.CartSkuSelect_confirm').removeAttr('disabled').text(!id ? window.isMoveToCart ? 'Move To Cart' : 'Add to Cart' : 'Update');}};/* 获取上报数据 */function getSelectPopupProductValue() {return {product_id: product.id,product_spu: theme.utils.getProductSpu(product.variants[0].sku || ""),product_name: product.title,preorder_skus: preOrderTime?.map(item => item.sku_code).join(','),web_original_price: product.compare_at_price / 100,web_current_price: product.price / 100,web_discount_price: (product.compare_at_price - product.price) / 100,product_from_page: product_from_page || '购物车页',}}function handleBriefProductTrackShow() {var colorStyle = findProductMetafieldsByKey(gqlData, 'skc_attributes') || {};var productSkcTag = {}; Object.keys(colorStyle).forEach(key => {var tagValue = colorStyle[key].tag_styleif (tagValue) {let curKey = `product_skc_tag_${tagValue}`;if (!productSkcTag[curKey]) {productSkcTag[curKey] = []}productSkcTag[curKey].push(key)}});Object.keys(productSkcTag).forEach(key => { productSkcTag[key] = productSkcTag[key].join(';')})sensors.track("BriefProductShow", Object.assign(getSelectPopupProductValue(), {preorder_skus: preOrderTime?.map(item => item.sku_code).join(';'),...productSkcTag,}))}function handleCartAddTrackClick() {sensors.track("AddToCartClick", Object.assign( getSelectPopupProductValue(), {page_code: '微商详',product_size: variant.option2,product_color: variant.option1,preorder_left_date: $('.CartSkuSelect_pretime').attr('data-value') || 0,recommend_size: ''}))}})