// ==UserScript== // @name jlcShopTool // @namespace http://tampermonkey.net/ // @version 2.3.5 // @description jlcShopTool_1.0 // @author Lx // @match https://so.szlcsc.com/global.html** // @match https://bom.szlcsc.com/member/eda/search.html?** // @match https://bom.szlcsc.com/member/bom/upload/**.html // @match https://www.szlcsc.com/huodong.html?** // @match https://list.szlcsc.com/brand** // @match https://list.szlcsc.com/catalog** // @icon https://www.google.com/s2/favicons?sz=64&domain=szlcsc.com // @require https://update.greasyfork.icu/scripts/446666/1389793/jQuery%20Core%20minified.js // @require https://update.greasyfork.icu/scripts/455576/1122361/Qmsg.js // @resource customCSS https://gitee.com/snwjas/message.js/raw/master/dist/message.min.css // @grant GM_openInTab // @grant GM_xmlhttpRequest // @grant GM_setClipboard // @grant GM_addStyle // @grant GM_getResourceText // @connect szlcsc.com // @license MIT // @downloadURL none // ==/UserScript== (async function() { 'use strict'; // 软件版本 const __version = 'Version 2.3.5'; // 引入message的css文件并加入html中 const css = GM_getResourceText("customCSS") GM_addStyle(css) const webSiteShareData = { lcscCartUrl: "https://cart.szlcsc.com", lcscWwwUrl: "https://www.szlcsc.com", lcscSearchUrl: "https://so.szlcsc.com", }; /** * rgb颜色随机 * @returns */ const rgb = () => { var r = Math.floor(Math.random() * 256) var g = Math.floor(Math.random() * 256) var b = Math.floor(Math.random() * 256) var rgb = 'rgb(' + r + ',' + g + ',' + b + ')'; return rgb; } /** * rgba颜色随机 * @param {*} a * @returns */ const rgba = (a = 1) => { var r = Math.floor(Math.random() * 256) var g = Math.floor(Math.random() * 256) var b = Math.floor(Math.random() * 256) var rgb = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; return rgb; } /** * 深色 随机色 * @returns */ const srdmRgbColor = () => { //随机生成RGB颜色 let arr = []; for (var i = 0; i < 3; i++) { // 暖色 arr.push(Math.floor(Math.random() * 128 + 64)); // 亮色 // arr.push(Math.floor(Math.random() * 128 + 128)); } let [r, g, b] = arr; // rgb颜色 // var color=`rgb(${r},${g},${b})`; // 16进制颜色 var color = `#${r.toString(16).length > 1 ? r.toString(16) : '0' + r.toString(16)}${g.toString(16).length > 1 ? g.toString(16) : '0' + g.toString(16)}${b.toString(16).length > 1 ? b.toString(16) : '0' + b.toString(16)}`; return color; } /** * 十六进制颜色随机 * @returns */ const color16 = () => { var r = Math.floor(Math.random() * 256) var g = Math.floor(Math.random() * 256) var b = Math.floor(Math.random() * 256) var color = '#' + r.toString(16) + g.toString(16) + b.toString(16) return color; } /** * 获取品牌名称 * 支持列表: * 1、XUNDA(讯答) * 2、立创开发板 * 3、50元德立品牌优惠 * 4、<新人专享>15元芯声品牌优惠 * @param text */ const brandNameProcess = (text) => { let replaceText = text; try { // 取括号里的品牌名称 如:ICEY(冰禹) if (replaceText.includes("(")) { const t = replaceText.split(/\(|\)/g).filter((e => e)); replaceText = (1 === t.length ? t[0] : t.length > 1 ? t[t.length - 1] : name) }else { const t = /<.+>/g.exec(text) if(t != null) { replaceText = t[0].replace(/<|>/g,'') if(replaceText === '新人专享') { replaceText = text.replace(/^.[^元]*元(.*)品牌.*$/, '$1') } } else { replaceText = text.replace(/^.[^元]*元(.*)品牌.*$/, '$1') } } }catch (e) { console.error(e) }finally { return replaceText } } /** * 等待 * @param {*} timeout * @returns */ const setAwait = (timeout) => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(true) }, timeout); }) } /** * 等待 执行函数 * @param {*} timeout * @returns */ const setAwaitFunc = (timeout, func) => { return new Promise((resolve, reject) => { setTimeout(() => { func && func() }, timeout); }) } /** * 获取本地缓存 * @param {*} key */ const getLocalData = (k) => { return localStorage.getItem(k) } /** * 设置本地缓存 * @param {*} key */ const setLocalData = (k, v) => { localStorage.setItem(k, v) } /** * 判断插件是否已经加载切是显示状态 * @returns */ const plguinIsHavedAndShow = () => { return plguinIsHaved() && $('.bd').is(':visible'); } /** * 判断插件是否已经加载 * @returns */ const plguinIsHaved = () => { return $('.bd').length > 0; } /** * 品牌名称加工 * @param {*} name * @returns */ const brandNameDataProcess = (name) => { return name.replace(/\//g, '_') } // 后续支持强排序按钮 // 商品清单集合暂存 const dataCartMp = new Map() // 品牌对应颜色,用于快速查找位置。 const dataBrandColorMp = new Map() // 优惠券页面,数据暂存。只保存16-15的优惠券 const all16_15CouponMp = new Map() // 自动领券的定时器 let couponTimer = null; // 搜索页总条数 var searchPageTotalCount = () => parseInt($('div.g01 span:eq(1)').text()) || parseInt($('#by-channel-total b').text()); // 搜索页单页条数 var searchPageSize = 30; // 搜索页需要显示多少条数据 自行修改 var searchPageRealSize = 100; // 搜索页总页数 var searchTotalPage = () => Math.min(((parseInt((searchPageTotalCount() / searchPageSize).toFixed(0)) + 1) || 34), 34); // 存储动态的function,用做数据处理 var jsRules = []; // 搜索页数据预览定时器 var searchTimer = null; // 搜索页数据暂存 var searchTempList = []; // 品牌搜索结束标记 var brandSearchEnd = false; // 搜索首页的结束标记 var globalSearchEnd = false; // 消息弹框全局参数配置 Qmsg.config({ showClose: true, timeout: 2800, maxNums: 50 }) /** * 根据value排序Map * @param {*} map * @returns */ const sortMapByValue = (map) => { var arrayObj = Array.from(map) //按照value值降序排序 arrayObj.sort(function(a, b) { return a[1] - b[1] }) return arrayObj } /** * GET请求封装 * @param {} data */ const getAjax = (url) => { return new Promise((resolve, reject) => { GM_xmlhttpRequest({ url, method: 'GET', onload: (r) => { resolve(r.response) }, onerror: (err) => { reject(err) } }) }) } /** * POST请求封装 * @param {} data */ const postAjaxJSON = (url, data) => { return new Promise((resolve, reject) => { GM_xmlhttpRequest({ url, method: 'POST', headers: { 'Content-Type': 'application/json' }, data, onload: (r) => { resolve(r.response) }, onerror: (err) => { reject(err) } }) }) } function jsonToUrlParam(json, ignoreFields = '') { return Object.keys(json) .filter(key => ignoreFields.indexOf(key) === -1) .map(key => key + '=' + json[key]).join('&'); } /** * POST请求封装 * @param {} data */ const postFormAjax = (url, jsonData) => { return new Promise((resolve, reject) => { GM_xmlhttpRequest({ url, data: jsonToUrlParam(jsonData), method: 'POST', headers: { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }, onload: (r) => { resolve(r.response) }, onerror: (err) => { reject(err) } }) }) } /** * 有进度的等待所有异步任务的执行 * @param {*} requests * @param {*} callback * @returns */ const allWithProgress = (requests, callback) => { let index = 0; requests.forEach(item => { item.then(() => { index++; const progress = index * 100 / requests.length; callback({ total: requests.length, cur: index, progress }); }) }); return Promise.all(requests); } /** * 订购数量发生变化的时候 */ const onChangeCountHandler = () => { // 订购数量 $('.product-item .cart-li input.input').on('change', () => { setTimeout(refresh, 1000); }) // 加减数量 $('.decrease,.increase').on('click', () => { setTimeout(refresh, 1000); }) } /** * 换仓按钮事件 * 一键换仓专用 * 换仓逻辑 https://cart.szlcsc.com/cart/warehouse/deliverynum/update cartKey规则: 标签id product-item-186525218 商品的跳转地址(商品id)20430799 cartKey: 186525218~0~20430799~RMB~CN gdDeliveryNum: 0 jsDeliveryNum: 1 */ const onClickChangeDepotBtnHandler = () => { /** * * @param {*} this 标签 * @param {*} warehouseType 仓库类型 GUANG_DONG:广东,JIANG_SU * @returns */ // 换仓封装 const _changeDepot = (that, warehouseType) => { return new Promise((resolve, reject) => { // 是否锁定样品 let isLocked = (that.find('.warehouse-wrap .warehouse:contains(广东仓)').length + that.find('.warehouse-wrap .warehouse:contains(江苏仓)').length) == 0 // 查找商品的属性 let infoElement = that.find('.cart-li:eq(1) a') if (isLocked === true) { Qmsg.error(`物料编号:${infoElement.text()},处于锁定样品状态,无法换仓`) console.error(`物料编号:${infoElement.text()},处于锁定样品状态,无法换仓`) return } // 订购数量 let count = that.find('.cart-li:eq(-4) input').val() // 物料ID1 let productId1 = /\d+/g.exec(that.attr('id'))[0] // 物料ID2 let productId2 = /\d+/g.exec(infoElement.attr('href'))[0] // 取最低起订量 let sinpleCount = /\d+/g.exec(that.find('.price-area:eq(0)').text())[0] // 订购套数 let batchCount = count / sinpleCount // 修改库存的参数体 let params = '' // 当前是广东仓 if (warehouseType == 'GUANG_DONG') { params = `cartKey=${productId1}~0~${productId2}~RMB~CN&gdDeliveryNum=${batchCount}&jsDeliveryNum=${0}` } // 其他情况当成是江苏仓 else if (warehouseType == 'JIANG_SU') { params = `cartKey=${productId1}~0~${productId2}~RMB~CN&gdDeliveryNum=${0}&jsDeliveryNum=${batchCount}` } GM_xmlhttpRequest({ url: `${webSiteShareData.lcscCartUrl}/cart/warehouse/deliverynum/update`, data: params, method: 'POST', headers: { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }, onload: (r) => { console.log(r.response) resolve(r.response) }, onerror: (err) => { reject(err) } }) }) } /** * 动态刷新页面,不强制刷新 * !!!暂时不能用,需要考虑订货商品还是现货 */ // const _reload = async () => { // // 购物车URL // const cartDataUrl = `${webSiteShareData.lcscCartUrl}/cart/display?isInit=false&isOrderBack=${window.isOrderBack}&${Date.now()}` // const res = await getAjax(cartDataUrl) // const resObj = JSON.parse(res) // // 合并订货和现货商品 // const newArr = [...resObj.result.shoppingCartVO.rmbCnShoppingCart.currentlyProductList, // ...resObj.result.shoppingCartVO.rmbCnShoppingCart.isNeedProductList] // // 遍历物料编号 // newArr.forEach(function (item) { // const { // jsDeliveryNum, // 江苏的订货量 // gdDeliveryNum, // 广东的订货量 // productCode, // 物料编码 // isChecked, // 是否选中 // jsValidStockNumber, // 江苏剩余库存 // szValidStockNumber, // 广东剩余库存 // jsDivideSplitDeliveryNum, // 江苏起订量的倍数 // gdDivideSplitDeliveryNum, // 广东起订量的倍数 // shopCarMapKey // 购物车主键 // } = item // // 查找到这个物料编号所在的行 // const ele = getAllLineInfoByBrandName(productCode) // // 计算出仓库名 // const depotName = jsDeliveryNum > 0 ? '江苏仓' : (gdDeliveryNum > 0 ? '广东仓' : '') // const depotEle = ele.find('.warehouse-wrap .warehouse') // const newDepotName = (depotEle.html() || '').replace('江苏仓', depotName).replace('广东仓', depotName) // // 重新设置仓库名称 // depotEle.html(newDepotName) // }) // } // 换仓-江苏 $('.change-depot-btn-left_').on('click', function() { let count = 0; const eles = getAllCheckedLineInfo() eles.each(async function() { count++ await _changeDepot($(this), 'JIANG_SU').then(res => { Qmsg.success('切换【江苏仓】成功!') }) if (eles.length === count) { // setTimeout(_reload, 500); setTimeout(function() { location.reload() // 官方刷新购物车 // cartModuleLoadCartList() }, 2500); } }) }) // 换仓-广东 $('.change-depot-btn-right_').on('click', function() { let count = 0; const eles = getAllCheckedLineInfo() eles.each(async function() { count++ await _changeDepot($(this), 'GUANG_DONG').then(res => { Qmsg.success('切换【广东仓】成功!') }) if (eles.length === count) { // setTimeout(_reload, 500); setTimeout(function() { location.reload() // 官方刷新购物车 // cartModuleLoadCartList() }, 2500); } }) }) } /** * 选中仓库事件 * 一键选仓专用 * 废弃:由于模拟点击,会导致小窗口频繁刷新,影响性能。下面重新换接口 */ const _checkDepotBtnHandler = () => { const _clickFunc = (depotName, fn) => { const eles = fn() // 先看看有没有指定仓 const jsIsEmpty = getJsLineInfo().length === 0 const gdIsEmpty = getGdLineInfo().length === 0 if (depotName === 'JIANG_SU' && jsIsEmpty) { Qmsg.error('购物车中并没有【江苏仓】的商品!') return } else if (depotName === 'GUANG_DONG' && gdIsEmpty) { Qmsg.error('购物车中并没有【广东仓】的商品!') return } // 是否有至少一个选中的 const isHave = eles.parents('.product-item').find('input.check-box:checked').length > 0 if (isHave) { eles.each(function() { $(this).parents('.product-item').find('input.check-box:checked').click() }) } // 都未选中,则执行仓库全选操作 else { eles.each(function() { $(this).parents('.product-item').find('input.check-box').click() }) } } // 江苏仓 $(".check-js-btn-left_").on('click', function() { _clickFunc('JIANG_SU', getJsLineInfo) }) // 广东仓 $(".check-gd-btn-right_").on('click', function() { _clickFunc('GUANG_DONG', getGdLineInfo) }) } /** * 选中仓库事件 * 一键选仓专用 */ const checkDepotBtnHandlerNew = () => { const _clickFunc = (depotName) => { // 广东仓选中 const gdCheckedEles = getGdLineInfo() // 江苏仓选中 const jsCheckedEles = getJsLineInfo() // 先看看有没有指定仓 const jsIsEmpty = jsCheckedEles.length === 0 const gdIsEmpty = gdCheckedEles.length === 0 let isJs = depotName === 'JIANG_SU' let isGd = depotName === 'GUANG_DONG' if (isJs && jsIsEmpty) { Qmsg.error('购物车中并没有【江苏仓】的商品!') return } else if (isGd && gdIsEmpty) { Qmsg.error('购物车中并没有【广东仓】的商品!') return } // 这里只需要操作多选框的选中状态就行 if (isJs) { const jsInputCheckBox = jsCheckedEles.parents('.product-item').find('input.check-box') const jsInputCheckBoxCK = jsInputCheckBox.parents('.product-item').find('input.check-box:checked') const isHave = jsInputCheckBoxCK.length > 0 jsInputCheckBox.prop('checked', !isHave) } else if (isGd) { const gdInputCheckBox = gdCheckedEles.parents('.product-item').find('input.check-box') const gdInputCheckBoxCK = gdInputCheckBox.parents('.product-item').find('input.check-box:checked') const isHave = gdInputCheckBoxCK.length > 0 gdInputCheckBox.prop('checked', !isHave) } cartUpdateChecked().then(res => { if (res === 'true') { cartModuleLoadCartList() setTimeout(refresh(), 1000); } }) } // 江苏仓 $(".check-js-btn-left_").on('click', function() { _clickFunc('JIANG_SU') }) // 广东仓 $(".check-gd-btn-right_").on('click', function() { _clickFunc('GUANG_DONG') }) } /** * 自动领取优惠券的定时器 */ const autoGetCouponTimerHandler = () => { $('.auto-get-coupon').off('change') couponTimer = null // 自动领取优惠券开关 $('.auto-get-coupon').on('change', function() { const isChecked = $(this).is(':checked') setLocalData('AUTO_GET_COUPON_BOOL', isChecked) autoGetCouponTimerHandler() }) couponTimer = setInterval(() => { const isChecked = $('.auto-get-coupon').is(':checked') if (isChecked) { console.log(`自动领取优惠券,后台运行中...`) dataCartMp.keys().forEach(item => { // 查找优惠券 const $couponEle = $(`.couponModal .coupon-item:contains(${item}):contains(立即抢券) div[data-id]`) if ($couponEle.length === 0) { return } //优惠券ID const couponId = $couponEle.data('id') // 优惠券名称 const couponName = $couponEle.data('name') getAjax(`${webSiteShareData.lcscWwwUrl}/getCoupon/${couponId}`).then(async res => { res = JSON.parse(res) if (res.result === 'success' || res.code == 200) { let msg = `${couponName}券,自动领取成功`; console.log(msg); Qmsg.success({ content: msg, timeout: 4000 }) await setTimeout(5000); allRefresh() } else { console.error(`自动领取优惠券失败:${res.msg}`) } }) }) } else { clearInterval(couponTimer) couponTimer = null } }, 5000); } /** * 一键分享 已经勾选的列表 */ const shareHandler = () => { // 产出数据并放在剪贴板中 const _makeDataAndSetClipboard = () => { const $checkedEles = getAllCheckedLineInfo() if ($checkedEles.length === 0) { Qmsg.error('购物车未勾选任何商品!') return } // 获取所有已经勾选的商品,也包含订货商品 const shareText = [...$checkedEles].map(function(item) { const $this = $(item) // 是否是江苏仓,如果是多个仓的话,只取一个 const isJsDepot = $this.find('.warehouse-wrap .warehouse').text().includes('江苏仓') // 该商品订购的总量 const count = $this.find('.cart-li:eq(4) input').val() return $this.find('.cart-li:eq(1) a').text().trim() + '_' + (isJsDepot ? 'JS_' : 'GD_') + count }).join('~') // navigator.clipboard.writeText(shareText) GM_setClipboard(shareText, "text", () => Qmsg.success('购物车一键分享的内容,已设置到剪贴板中!')) } $('.share_').click(_makeDataAndSetClipboard) } /** * 一键解析 */ const shareParseHandler = () => { let _loading = null // 定义匿名函数 const _shareParse = async() => { // 富文本框内容 const text = $('.textarea').val().trim() if (text.length === 0) { Qmsg.error('解析失败,富文本内容为空!') return } _loading = Qmsg.loading("正在解析中...请耐心等待!") // 成功条数计数 let parseTaskSuccessCount = 0 // 失败条数计数 let parseTaskErrorCount = 0 // 总条数 let parseTaskTotalCount = 0 // 首次处理出来的数组 const firstparseArr = text.split('~') parseTaskTotalCount = firstparseArr.length || 0 for (let item of firstparseArr) { // 二次处理出来的数组 const secondParseArr = item.split('_') // 物料编号 const productNo = secondParseArr[0].trim().replace('\n', '') // 仓库编码 const depotCode = secondParseArr[1].trim().replace('\n', '') // 数量 const count = secondParseArr[2].trim().replace('\n', '') if (productNo === undefined || count === undefined) { Qmsg.error('解析失败,文本解析异常!') _loading.close() return } // 添加购物车 await postFormAjax(`${webSiteShareData.lcscCartUrl}/cart/quick`, { productCode: productNo, productNumber: count }).then(res => { res = JSON.parse(res) if (res.code === 200) { Qmsg.info(`正在疯狂解析中... 共:${parseTaskTotalCount}条,成功:${++parseTaskSuccessCount}条,失败:${parseTaskErrorCount}条。`); } else { Qmsg.error(`正在疯狂解析中... 共:${parseTaskTotalCount}条,成功:${parseTaskSuccessCount}条,失败:${++parseTaskErrorCount}条。`); } }) } Qmsg.success(`解析完成!共:${parseTaskTotalCount}条,成功:${parseTaskSuccessCount}条,失败:${parseTaskErrorCount}条。已自动加入购物车`) _loading.close() // 刷新购物车页面 cartModuleLoadCartList() setTimeout(allRefresh, 100); } $('.share-parse').click(_shareParse) } /** * 一键锁定、释放商品 */ const lockProductHandler = () => { $(`.lock-product`).click(async function() { const $eles = getHavedCheckedLineInfo() if ($eles.has(':contains("锁定样品")').length === 0) { Qmsg.error('没有要锁定的商品!') return; } for (const that of $eles) { // 购物车商品的ID if (!$(that).has(':contains("锁定样品")').length) { continue; } const shoppingCartId = $(that).has(':contains("锁定样品")').attr('id').split('-')[2] // 接口限流延迟操作 await postFormAjax(`${webSiteShareData.lcscCartUrl}/async/samplelock/locking`, { shoppingCartId }).then(res => { res = JSON.parse(res) if (res.code === 200) { Qmsg.success(res.msg || res.result || '商品锁定成功!') } else { Qmsg.error(res.msg || res.result || '商品锁定失败!请稍后再试') } }) } // 刷新购物车页面 setTimeout(() => { cartModuleLoadCartList(); setTimeout(allRefresh, 800); }, 1000); }) $(`.unlock-product`).click(async function() { const $eles = getHavedCheckedLineInfo() if ($eles.has(':contains("释放样品")').length === 0) { Qmsg.error('没有要锁定的商品!') return; } for (const that of $eles) { // 购物车商品的ID if (!$(that).has(':contains("释放样品")').length) { continue; } const shoppingCartId = $(that).has(':contains("释放样品")').attr('id').split('-')[2] // 接口限流延迟操作 await postFormAjax(`${webSiteShareData.lcscCartUrl}/async/samplelock/release/locking`, { shoppingCartId }).then(res => { res = JSON.parse(res) if (res.code === 200) { Qmsg.success(res.msg || res.result || '商品释放成功!') } else { Qmsg.error(res.msg || res.result || '商品释放失败!请稍后再试') } }) } // 刷新购物车页面 setTimeout(() => { cartModuleLoadCartList(); setTimeout(allRefresh, 800); }, 1000); }) } // 控制按钮的生成 const buttonListFactory = () => { let isBool = getAllCheckedLineInfo().length > 0 return `
一键分享
${dataCartMp.size}
` } /** * 计算总的金额 */ const totalMoneyFactory = () => { let t = 0 if (dataCartMp.size > 0) { t = [...dataCartMp.values()].reduce((total, num) => total + num).toFixed(2) } return `${t}
` } /** * 查询16-15优惠券列表 */ const lookCouponListBtnFactory = () => { return `优惠券专区
` } /** * 查看优惠券页面的扩展按钮,绑定事件 */ const lookCouponListExtendsBtnHandler = () => { // 查看已领取的优惠券 $('.filter-haved').off('click').on('click', function() { $('.coupon-item:visible:not(:contains(立即使用))').hide() }) // 过滤16-15的优惠券 $('.filter-16-15').off('click').on('click', function() { $('.coupon-item:visible:not(:contains(满16可用))').hide() }) // 过滤20-15的优惠券 $('.filter-20-15').off('click').on('click', function() { $('.coupon-item:visible:not(:contains(满20可用))').hide() }) // 过滤新人优惠券 $('.filter-newone').off('click').on('click', function() { $('.coupon-item:visible:not(:contains(新人专享))').hide() }) // 过滤非新人优惠券 $('.filter-not-newone').off('click').on('click', function() { $('.coupon-item:visible:contains(新人专享)').hide() }) // 手动刷新优惠券页面 $('.refresh-coupon-page').off('click').on('click', function() { setTimeout(() => { Qmsg.info(`1秒后刷新优惠券页面...`) setTimeout(() => lookCouponListModal(true), 500); }, 500); }) // 一键领取当前显示的所有优惠券 $('.get-all').click(function() { const $couponEles = $('.coupon-item:visible div:contains(立即抢券)') let totalCount = 0, successCount = 0; $couponEles.each(function() { //优惠券ID const couponId = $(this).data('id') // 优惠券名称 const couponName = $(this).data('name') getAjax(`${webSiteShareData.lcscWwwUrl}/getCoupon/${couponId}`).then(res => { res = JSON.parse(res) if (res.code === 200 && res.msg === '') { successCount++ // console.log(`${couponName} 优惠券领取成功`) } else { // console.error(`${couponName} 优惠券领取失败,或者 已经没有可以领取的优惠券了!`) } }) totalCount++ }) if (successCount === 0) { Qmsg.error(`优惠券领取失败,或者已经没有可以领取的优惠券了!`) } else if ($couponEles.length === totalCount) { Qmsg.success(`优惠券领取成功!成功:${successCount}条,失败:${totalCount - successCount}条。`) setTimeout(() => { Qmsg.info(`2秒后刷新优惠券页面...`) // 由于调用接口领取,所以需要重新渲染优惠券页面 setTimeout(lookCouponListModal, 2000); }, 2000); } }) // 过滤新人优惠券 $('.filter-clear').click(function() { $('.coupon-item:hidden').show() }) } /** * 查看优惠券列表的按钮 */ const lookCouponListHandler = () => { const _lookCouponClick = () => { if ($('#couponModal').is(':hidden')) { $('#couponModal').show() } else if ($('#couponModal').is(':visible')) { $('#couponModal').hide() } } $('.look-coupon-btn,.look-coupon-closebtn').on('click', _lookCouponClick) } // 优惠券模态框的锁 var lookCouponLock = false; /** * 优惠券模态框 */ const lookCouponListModal = async(clear = false) => { if (lookCouponLock || !plguinIsHavedAndShow() || ($('.couponModal .all-coupon-page').length > 0 && clear === false)) { return; } //上锁, 防止这次还没处理完, 下次定时任务就已经就绪了。 lookCouponLock = true; let couponHTML = await getAjax(`${webSiteShareData.lcscWwwUrl}/huodong.html`); const $couponHTML = $(couponHTML); let $cssLink = [...$couponHTML].filter(item => item.localName == 'link' && item.href.includes('/public/css/page/activity/couponAllCoupons'))[0].outerHTML; let $jsLink = [...$couponHTML].filter(item => item.localName == 'script' && item.src.includes('/public/js/chunk/page/activity/couponAllCoupons'))[0].outerHTML; let $main_wraper = $couponHTML.find('.main_wraper'); let $navigation = $couponHTML.find('.navigation'); let ht = `多仓库
${val} ${(16 - val).toFixed(2)} ${couponHTMLFactory(key)}查看类目
`) } if ($this.hasClass('receive')) { $this.find('.coupon-item-goto').css({ color: 'unset' }) } $this.find('.coupon-item-goto').css({ background: btnBackgound }) $this.find('.coupon-item-goto').attr('href', $this.find('div[data-id]').data('url')) }); $(`p.watch-category-btn`).off('click').on('click', function() { const brandNameTitle = $(this).data('name'); const brandDataUrl = $(this).data('url'); const brandName = brandNameProcess(brandNameTitle); searchGlobalBOM(brandName, brandNameTitle, brandDataUrl); }); } const searchGlobalBOM = async (k, title, brandDataUrl) => { const brandId = brandDataUrl.replaceAll(/[^\d]+/g, ''); const url = `https://bom.szlcsc.com/global?k=${k}&pageSize=1&pageNumber=1`; const res = await getAjax(url); const resJsonObject = JSON.parse(res) if(resJsonObject.code === 200) { const catalogGroup = resJsonObject.result.searchResult.catalogGroup const renderCatelogHtml = catalogGroup .map(e => ` ${e.label}(${e.count})`).join(``); Qmsg.info({ content: `最低购入价: ${parseFloat((minMum * orderPrice).toFixed(6))}
`) }) } // if ($('.minBuyMoney_').length === 0) { minBuyMoney() } /** * html追加到页面中 */ const appendProductListBox = (html) => { $('.wait-h2').hide(); $('.nodata-h2').hide(); $('#product-list-box div#data-box—').html(html); if (html.length === 0 || $('#product-list-box div#data-box— table').length === 0) { $('.nodata-h2').show(); $('.wait-h2').hide(); return; } } /** * 分类搜索页的凑单逻辑 */ const renderCatalogPageMinPriceSearch = () => { // 持续请求 && 定时器未初始化 && 未查询到结果的时候 if(!globalSearchEnd) { // 总页数。默认:30页 const totalPage = searchTotalPage(); const promiseList = []; var searchData_ = null; // 取一遍值 如果没有定义,则取默认值 try { searchData_ = searchData; } catch (error) { searchData_ = { catalogNodeId: /\d+/g.exec(location.pathname)[0], pageNumber: 1, querySortBySign: 0, showOutSockProduct: 1, showDiscountProduct: 1 } } for (let pn = 1; pn <= totalPage; pn++) { searchData_['pageNumber'] = pn; var settings = { "url": "https://list.szlcsc.com/products/list", "method": "POST", "data": searchData_ }; promiseList.push($.ajax(settings)); } globalSearchEnd = true; allWithProgress(promiseList, ({total, cur, progress}) => { $('.wait-h2').html(`数据加载中...(共${total}页,正在加载第${cur}页。或只查询前1000条记录)...`); }).then(function (result) { result.forEach(data => { if(data.success === true && data.productRecordList) { searchTempList = [...searchTempList, ...data.productRecordList]; } }); }).finally(() => { renderMinPriceSearch(); setTimeout(() => { $('#js-filter-btn').click() }, 100); }); } } /** * 搜索主页的凑单逻辑 */ const renderMainPageMinPriceSearch = () => { // 持续请求 && 定时器未初始化 && 未查询到结果的时候 if(!globalSearchEnd) { var val = $('#search-input').val(); if (val == null || val.length === 0) { searchTempList = []; return; } // 总页数。默认:30页 const totalPage = searchTotalPage(); const promiseList = []; for (let pn = 1; pn <= totalPage; pn++) { const data = {}; [...$('form#allProjectFrom>input[type="hidden"]:not([id*=SloganVal]):not([id*=LinkUrlVal])')].forEach(item => { const name = $(item).attr('name'); const val = $(item).val(); data[name] = val; }); data['pageNumber'] = pn; data['k'] = val; data['sk'] = val; data['localQueryKeyword'] = $('input[name="localQueryKeyword"]').val() || ''; data['bp'] = $('input[name="bpTemp"]').val() || ''; data['ep'] = $('input[name="epTemp"]').val() || ''; var settings = { "url": "https://so.szlcsc.com/search", "method": "POST", // "data": { "pn": searchPageNum, "k": val, "sk": val } "data": data }; // console.log('品牌搜索页参数:', settings); promiseList.push($.ajax(settings)); } globalSearchEnd = true; allWithProgress(promiseList, ({total, cur, progress}) => { $('.wait-h2').html(`数据加载中...(共${total}页,正在加载第${cur}页。或只查询前1000条记录)...`); }).then(function (result) { console.time('搜索首页凑单渲染速度'); result.forEach(data => { if(data.code === 200 && data.result != null) { if (data.result.productRecordList != null) { searchTempList = [...searchTempList, ...data.result.productRecordList]; } } }); }).finally(() => { renderMinPriceSearch(); console.timeEnd('搜索首页凑单渲染速度'); setTimeout(() => { $('#js-filter-btn').click() }, 100); }); } } /** * 品牌搜索主页的凑单逻辑 */ const renderBrandPageMinPriceSearch = async () => { if (!brandSearchEnd) { const totalPage = searchTotalPage(); // 延迟任务集合 const promiseList = []; for (let pn = 1; pn <= totalPage; pn++) { // 取品牌id const brandId = /\d+/g.exec(location.href)[0]; if (brandId != null) { const data = {}; [...$('form#allProjectFrom>input[type="hidden"]')].forEach(item => { const name = $(item).attr('name'); const val = $(item).val(); data[name] = val; }); data['pageNumber'] = pn; data['queryProductGradePlateId'] = brandId; data['localQueryKeyword'] = $('input[name="localQueryKeyword"]').val() || ''; data['queryBeginPrice'] = $('input[name="queryBeginPrice"]').val() || ''; data['queryEndPrice'] = $('input[name="queryEndPrice"]').val() || ''; data['queryBeginPriceTemp'] = $('input[name="queryBeginPriceTemp"]').val() || ''; data['queryEndPriceTemp'] = $('input[name="queryEndPriceTemp"]').val() || ''; var settings = { "url": `https://list.szlcsc.com/brand_page/${brandId}.html`, "method": "POST", "data": data } // console.log('搜索首页参数:', settings); promiseList.push($.ajax(settings)); } } brandSearchEnd = true; allWithProgress(promiseList, ({total, cur, progress}) => { $('.wait-h2').html(`数据加载中...(共${total}页,正在加载第${cur}页。或只查询前1000条记录)...`); }).then((result) => { const dataArray = result.reduce((arr, cur)=> { const $tables = $(cur).find('#shop-list table'); return arr.concat([...$tables]); }, []); const _buildMapData = ($table) => { const map = {}; $table.each((i, e) => { map[$(e).find('span:eq(0)').text().trim()] = $(e).find('span:eq(1)').text().trim(); }); return map; } console.time('品牌页凑单渲染速度'); searchTempList = dataArray.map(h => { const $table = $(h); return { productId: $table.data('productid'), lightStandard: $table.data('encapstandard'), lightProductCode: $table.data('productcode'), productMinEncapsulationNumber: $table.data('productminencapsulationnumber'), productMinEncapsulationUnit: $table.data('productminencapsulationunit'), productName: $table.data('productname'), productModel: $table.data('productmodel'), lightProductModel: $table.data('productmodel-unlight'), productGradePlateId: $table.data('brandid'), productPriceList: [...$table.find('li.three-nr-item span.ccd-ppbbz')].map(e => ({ "startPurchasedNumber": parseInt($(e).data('startpurchasednumber')), "endPurchasedNumber": parseInt($(e).data('endpurchasednumber')), "productPrice": parseFloat($(e).data('productprice')) })), listProductDiscount: $table.find('div.three-box-top ul.three-nr > li.three-nr-01').find('span:eq(0)').text().replace(/[ 折\n]+/g, '') || null, productGradePlateName: $table.data('brandname'), hkConvesionRatio: $table.data('hkconvesionratio'), convesionRatio: $table.data('convesionratio'), theRatio: $table.data('theratio'), smtStockNumber: parseInt($table.find('table div.smt-stock').text() || 0), smtLabel: $table.find('div.smt-flag.common-label').text() || '', productStockStatus: $table.data('productstockstatus'), isPlusDiscount: $table.data('isplusdiscount'), productUnit: $table.data('productunit'), isPresent: $table.data('ispresent'), isGuidePrice: $table.data('isguideprice'), minBuyNumber: $table.data('minbuynumber'), hasSampleRule: $table.data('hassamplerule'), breviaryImageUrl: $table.find('a.one-to-item-link img').data('urls').split('<$>')[0], luceneBreviaryImageUrls: $table.find('a.one-to-item-link img').data('urls') || '', productType: $table.find('li.li-ellipsis a.catalog').attr('title') || '', productTypeCode: /\d+/g.exec($table.find('li.li-ellipsis a.catalog').attr('href') || '')[0], pdfDESProductId: $table.find('li.li-ellipsis a.sjsc').attr('param-click'), gdWarehouseStockNumber: parseInt($table.find('div.stock-nums-gd span').text() || 0), jsWarehouseStockNumber: parseInt($table.find('div.stock-nums-js span').text() || 0), paramLinkedMap: _buildMapData($table.find('ul.params-list li.li-ellipsis')), recentlySalesCount: /\d+/g.exec($table.find('div.stocks span').text() || '0')[0], batchStockLimit: $table.data('batchstocklimit'), }; }); }).finally(() => { renderMinPriceSearch(); console.timeEnd('品牌页凑单渲染速度'); setTimeout(() => { $('#js-filter-btn').click() }, 100); }); } } /** * 搜索页-查找最低价 列表渲染方法 */ const renderMinPriceSearch = () => { // 如果广东仓和江苏仓同时没有货的话,那么就属于订货商品,不需要显示 // 如果没有价格区间,证明是停售商品 var newList = searchTempList.filter(item =>!(parseInt(item.jsWarehouseStockNumber||0) <= 0 && parseInt(item.gdWarehouseStockNumber||0) <= 0) && item.productPriceList.length > 0); // 去重 const map = new Map(); newList.forEach(item => { map.set(item.productId, item); }); newList = [...map.values()]; // 列表自动正序,方便凑单 newList.sort((o1, o2) =>{ return (o1.theRatio * o1.productPriceList[0].productPrice * (o1.listProductDiscount || 10) / 10).toFixed(6) - (o2.theRatio * o2.productPriceList[0].productPrice * (o2.listProductDiscount || 10) / 10).toFixed(6); }); // 外部动态js规则组 if (jsRules.length > 0) { jsRules.forEach(jsr => { newList = newList.filter(jsr); }); } // 取指定条数的数据。默认50个 const html = newList.slice(0, (searchPageRealSize || 50)).map(item => { const { productId , lightStandard , lightProductCode , productMinEncapsulationNumber , productMinEncapsulationUnit , productName , productModel , lightProductModel , productGradePlateId , productPriceList , listProductDiscount , productGradePlateName , hkConvesionRatio , convesionRatio , theRatio , smtStockNumber , smtLabel , productStockStatus , isPlusDiscount , productUnit , isPresent , isGuidePrice , minBuyNumber , hasSampleRule , breviaryImageUrl , luceneBreviaryImageUrls , productType , productTypeCode , pdfDESProductId , gdWarehouseStockNumber , jsWarehouseStockNumber , paramLinkedMap , recentlySalesCount , batchStockLimit } = item; return `
最低购入价: ${parseFloat((theRatio * productPriceList[0].productPrice * (listProductDiscount || 10) / 10).toFixed(6))} ${ productPriceList.map(item => { const discountPrice = parseFloat((item.productPrice * (listProductDiscount || 10) / 10).toFixed(6)); return `
现货最快4H发
|
凑单
页面加载慢,请耐心等待!