12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028 |
- const coreServer = $("#coreServer").val();
- const isPC = ($(window).width() > 768);
- let globalUserData = '';
- let GLOBAL_TOKEN = 'X-Token';
- let GLOBAL_USER_ID = 0; // 用户Id
- let GLOBAL_USER_IDENTITY = 0;//2-会员机构;3-供应商;4-普通机构
- let GLOBAL_SHOP_ID = 0; // 供应商Id
- let GLOBAL_VIP_FLAG = 0; // 超级会员标记
- let GLOBAL_CLUB_TYPE = 0; // 会员类型 1 医美机构 2 胜美机构
- let IDENTITY = 0; // 用户标记
- let isForbidTabs = true; //控制菜单
- let isShopIsOrder = false; //控制菜单
- if(localStorage.getItem('userInfo')){
- globalUserData = JSON.parse(localStorage.getItem('userInfo'));
- GLOBAL_TOKEN = globalUserData.token;
- GLOBAL_USER_ID = globalUserData.userId*1;
- GLOBAL_USER_IDENTITY = globalUserData.userIdentity*1;
- IDENTITY = globalUserData.userIdentity*1;
- GLOBAL_VIP_FLAG = globalUserData.vipFlag;
- GLOBAL_SHOP_ID = globalUserData.shopId*1;
- GLOBAL_CLUB_TYPE = globalUserData.firstClubType ? globalUserData.firstClubType : null;
- if (GLOBAL_USER_ID === 5261 || GLOBAL_USER_ID === 10947 || GLOBAL_USER_ID === 11579) {
- GLOBAL_USER_IDENTITY = 1;
- GLOBAL_VIP_FLAG = 1;
- IDENTITY = 1;
- }else if(GLOBAL_CLUB_TYPE === 1){
- IDENTITY = 5;
- }
- if(globalUserData.listingFee === 1){
- isForbidTabs = false;
- }
- if(globalUserData){
- isShopIsOrder = globalUserData.shopIsOrder;
- }
- } else {
- // const pathname = window.location.pathname;
- // const weChatLoginFlag = (Number(getBaseCookie("weChatAutoLogin")) === 1 || Number(getBaseCookie("weChatAutoLogin")) === 2);
- // if(pathname.indexOf('/product/auth/') === -1 && !weChatLoginFlag ){
- // const userAgent = navigator.userAgent.toLowerCase();
- // const isWechatLogin = window.location.href.indexOf('isDataBase') !== -1
- // if (userAgent.match(/MicroMessenger/i) && !isWechatLogin) {
- // // 微信浏览器自动授权登录
- // var urlForWeChat = 'https://www.caimei365.com/we_chat/redirect_uri.html';
- // $.get(coreServer+'/user/login/auth/link?mode=1&redirectUri='+urlForWeChat, function(r){
- // if(r.code===0 && r.data){
- // setBaseCookie("weChatAutoLogin", 1);
- // setBeforeUrl();
- // window.location.href = r.data;
- // }
- // });
- // }
- // }
- }
- // 头部
- const globalHead = new Vue({
- el: '#globalHead',
- data: {
- loginStatus: false,
- userData: {},
- classify: [],
- headCart: {
- cartList: [],
- cartCount: 0,
- productCount: 0,
- priceTotal: 0
- },
- noticeNum: 0,
- shopId: '',
- userIdentity: '',
- articleType: '',
- isFiexd: false,
- classifyIndex: 1,
- supplierLinks: [
- {
- title: '美业参谋',
- link: '/supplier/attraction.html',
- },
- {
- title: '供应商协议',
- link: '/help/1007.html',
- },
- {
- title: '商家登录',
- link: '/supplierlogin.html',
- },
- {
- title: '隐私政策',
- link: '/help/1013.html',
- },
- {
- title: '入驻流程',
- link: '/help/1044.html',
- },
- ], // 供应商链接
- activeLinks: [],
- },
- watch: {
- isFiexd: function (nVal, oVal) {
- // 防止跳动
- // if(nVal && isPC){
- // $("body").css('paddingTop', $("#globalHead").height() + "px");
- // }else{
- // $("body").css('paddingTop', "0px");
- // }
- },
- loginStatus: {
- handler(val) {
- if (val) {
- this.activeLinks = this.supplierLinks.filter((i, index) => index !== 2)
- } else {
- this.activeLinks = this.supplierLinks
- }
- },
- deep: true,
- immediate: true
- }
- },
- methods: {
- changeClassify: function (value) {
- this.classifyIndex = value;
- },
- // 初始化分类菜单效果
- initClassufyTab: function () {
- if (isPC) {
- setTimeout(function () {
- $('#mainClassify').slide({
- mainCell: ".clsCon",
- titCell: ".clsTab a",
- trigger: "mouseover"
- });
- $('#mainClassify_1').slide({
- mainCell: ".tabItem_right",
- titCell: ".tabItem_lift a",
- trigger: "mouseover"
- });
- $('#mainClassify_2').slide({
- mainCell: ".tabItem_right",
- titCell: ".tabItem_lift a",
- trigger: "mouseover"
- });
- $("#mainClassify_2 .tabItem_lift a").eq(0).trigger("mouseover");
- $("#mainClassify_1 .tabItem_lift a").eq(0).trigger("mouseover");
- }, 500);
- } else {
- setTimeout(function () {
- $('#mainClassify').slide({
- mainCell: ".clsCon",
- titCell: ".clsTab a",
- trigger: "click"
- });
- $('#mainClassify_1').slide({
- mainCell: ".tabItem_right",
- titCell: ".tabItem_lift a",
- trigger: "click"
- });
- $('#mainClassify_2').slide({
- mainCell: ".tabItem_right",
- titCell: ".tabItem_lift a",
- trigger: "click"
- });
- $("#mainClassify_2 .tabItem_lift a").eq(0).trigger("click");
- $("#mainClassify_1 .tabItem_lift a").eq(0).trigger("click");
- }, 500);
- }
- },
- // 头部购物车数据
- getHeadCart: function (userId) {
- var _self = this;
- ShoppingApi.getHeaderCartList({userId: userId}, function (response) {
- if (response.code === 0 && response.data) {
- var data = response.data;
- _self.headCart.cartList = data.list;
- _self.headCart.cartCount = data.list.length;
- _self.headCart.productCount = 0;
- _self.headCart.priceTotal = 0;
- data.list.map(function (item) {
- _self.headCart.productCount += item.number;
- _self.headCart.priceTotal += item.number * item.price;
- });
- } else if (r.code == -99) {
- CAIMEI.Storage.clear();
- location.href = "/login.html";
- }
- });
- },
- getAuthClubCount: function (clubId) {
- var _self = this;
- PublicApi.getAuthClubCount({commonId: clubId}, function (response) {
- if (response.code === 0 && response.data) {
- var data = response.data;
- if (data.count > 99) {
- _self.noticeNum = '99+'
- } else {
- _self.noticeNum = data.count
- }
- console.log('noticeNum', _self.noticeNum)
- } else {
- console.log('获取机构通知消息数量异常')
- }
- });
- },
- getAuthShopCount: function (shopId) {
- var _self = this;
- PublicApi.getAuthShopCount({commonId: shopId}, function (response) {
- if (response.code === 0 && response.data) {
- var data = response.data;
- if (data.count > 99) {
- _self.noticeNum = '99+'
- } else {
- _self.noticeNum = data.count
- }
- localStorage.setItem('noticeNum', _self.noticeNum)
- } else {
- console.log('获取供应商通知消息数量异常')
- }
- });
- },
- goMsgLinkFn: function (url) {
- var _self = this;
- if (_self.loginStatus) {
- window.location.href = url;
- } else {
- window.location.href = '/login.html';
- }
- },
- goSupplierLink() {
- window.location.href = '/supplier/attraction.html'
- },
- // 头部供应商跳转链接
- goHeaderLink(link) {
- if (link) {
- window.location.href = link
- }
- },
- goCartsLinkFn: function () {
- var _self = this;
- if (_self.loginStatus) {
- window.location.href = '/shopping/cart.html';
- } else {
- window.location.href = '/login.html';
- }
- },
- productDetailsFn: function (id) { // 跳转详情
- window.location.href = '/product-' + id + '.html';
- },
- DeleteCartProducts: function (skuId) { // 删除购物车
- const _self = this;
- ShoppingApi.DeleteCartProducts({userId: this.userData.userId, skuIds: skuId}, function (response) {
- if (response.code === 0) {
- _self.getHeadCart(_self.userData.userId);
- } else {
- CAIMEI.Alert(response.msg, '确定', false);
- }
- });
- },
- pageLinkSupplier: function () {//预览商品
- window.open('/supplier-' + this.shopId + '.html');
- },
- // 退出登录
- userLogOut: function () {
- localStorage.removeItem('userInfo');
- delBaseCookie("loginBeforePath");
- this.loginStatus = false;
- window.location.href = "/index.html";
- },
- showGlobalMenu: function () {
- if (!isPC) {
- $("#mGlobalMenu").show().find(".cShow").slideDown(500);
- }
- },
- hideGlobalMenu: function () {
- if (!isPC) {
- $("#mGlobalMenu").hide().find(".cShow").hide();
- }
- },
- // init auto-input complete
- initAuthInputComplete() {
- new AutoComplete({
- el: '.auto-input',
- callback: async function (keyword) {
- try {
- const res = await PublicApi.fetchQueryKeywordList({keyword: keyword});
- if (!res.data) return [];
- return res.data.map(item => item.keyword);
- } catch (e) {
- console.log(e);
- }
- },
- itemClick: function (keyword) {
- window.location.href = '/product/list.html?keyword=' + keyword + '&productFlag=1' + '&linkageFlag=1';
- }
- });
- },
- },
- created: function () {
- var _self = this;
- // 判断登录状态
- if (globalUserData.token) {
- this.loginStatus = true;
- this.userData = globalUserData;
- if (this.userData.userIdentity === 3) {
- // 获取头部通知消息数量
- setTimeout(function () {
- _self.getAuthShopCount(_self.userData.shopId);
- }, 1000);
- // 获取头部通知消息数量
- var timerShopCount = setInterval(function () {
- _self.getAuthShopCount(_self.userData.shopId);
- }, 1000 * 120);
- } else {
- setTimeout(function () {
- // 获取头部购物车数据
- _self.getHeadCart(_self.userData.userId);
- _self.getAuthClubCount(_self.userData.clubId);
- }, 1000);
- // 获取头部通知消息数量
- var timerClubCount = setInterval(function () {
- _self.getAuthClubCount(_self.userData.clubId);
- }, 1000 * 600);
- }
- }
- // 信息中心
- this.articleType = getUrlParam("type");
- },
- mounted: function () {
- var _self = this;
- // 初始化分类菜单效果
- this.initClassufyTab();
- var userData = JSON.parse(window.localStorage.getItem('userInfo'));
- if (userData != null) {
- this.userIdentity = userData.userIdentity;
- this.shopId = userData.shopId;
- }
- if ($(window).height() > 750) {
- $(window).on('scroll', function () {
- var scrollTop = $(this).scrollTop();
- if (scrollTop > 50) {
- _self.isFiexd = true;
- } else {
- _self.isFiexd = false;
- }
- })
- }
- // 判断导航菜单高亮-对比url
- setTimeout(function () {
- var path = window.location.pathname;
- var paramsArr = path.split(".")[0].split("-");
- var key = paramsArr[0].split("/")[1];
- var pageId = paramsArr.length >= 1 ? paramsArr[1] : '';
- if (key && key.length > 0) {
- $('.navBox li').each(function () {
- var href = $(this).find('a').attr("href");
- if (href.indexOf(path) >= 0) {
- $(this).find('a').addClass('on');
- return false;
- } else if (key != 'product' && key != 'info' && href.indexOf('/' + key) >= 0) {
- $(this).find('a').addClass('on');
- return false;
- }
- });
- }
- }, 500);
- this.initAuthInputComplete();
- }
- });
- // 底部
- const globalFot = new Vue({
- el: '#globalFot',
- mixins: [cmAiMixins],
- data: {
- isShowIcon: true,
- },
- computed: {
- copyrightYear() {
- let date = new Date()
- return date.getFullYear()
- }
- },
- methods: {
- goSupplierLink() {
- window.location.href = '/supplier/attraction.html'
- },
- },
- mounted() {
- }
- });
- // 初始化效果
- $(function(){
- // PC,H5切换时刷新
- $(window).resize(function() {
- var flag = (isPC && $(window).width()<=768) || (!isPC && $(window).width()>768);
- if(flag){
- window.location.reload();
- }
- });
- // 导航分类
- if(isPC){
- jqClickShow(".baseHeadTop .cTab", ".baseHeadTop .cShow");
- jqSelect(".jqSelect");
- jqHoverShow(".classBtn", "#mainClassify");
- }else{
- jqMultipleShow("click", ".footLink .list", ".tab", ".con", true);
- $('body').on('click', '.baseHeadCenter .mClassBtn',function () {
- $('#mainClassify').show();
- fixedBody();
- }).on('click', '#mainClassify .close,#mainClassify .mClassBtn',function () {
- $('#mainClassify').hide();
- looseBody();
- }).on('click', '#mainClassify',function (e) {
- e.stopPropagation();
- });
- }
- // 登录弹窗
- function loginAert(content, btnTxt){
- $.confirm({
- useBootstrap: false,
- boxWidth: (isPC?'338px':'74.6vw'),
- title: false,
- content:'<div class="loginAlert">'+content+'</div>',
- closeIcon: true,
- animation: 'opacity',
- closeAnimation: 'opacity',
- animateFromElement: false,
- scrollToPreviousElement: false,
- buttons: {
- login: {
- text: btnTxt,
- btnClass: 'btn-confirm-login',
- action: function(){
- setBeforeUrl();
- window.location.href = '/login.html';
- }
- },
- close: {
- text: '取消',
- btnClass: 'btn-cancel-login'
- }
- }
- });
- }
- // 去登录弹窗
- $('body').on("click", '.toLogin',function () {
- //loginAert('<span>你还未登录</span><span>请登录后再进行购买</span>', '去登录');
- setBeforeUrl();
- window.location.href = '/login.html';
- });
- // 退出登录
- $('body').on("click", '.toLogOut',function () {
- localStorage.removeItem('userInfo');
- delBaseCookie("loginBeforePath");
- globalHead.loginStatus = false;
- window.location.href = "/index.html";
- });
- // 置顶
- $('#scrollTop').on("click", '.toTop',function () {
- $("html,body").animate({scrollTop:0},500);
- });
- // 热线
- if(!isPC){
- $('#scrollTop').on("click", '.phone',function () {
- $('#scrollTop').find('.phoneHover').show();
- fixedBody();
- }).on("click", '.phoneHover div',function (e) {
- e.stopPropagation();
- }).on("click", '.phoneHover,.phoneHover .close',function () {
- $('#scrollTop').find('.phoneHover').hide();
- looseBody();
- });
- $('body').on("click", '#centerNav .home',function () {
- if($('#centerNav').find('.home').hasClass("on")){
- $('#centerNav').find('.home').removeClass("on");
- $('#centerNav').find('.centerBox').slideUp();
- looseBody();
- }else{
- $('#centerNav').find('.home').addClass("on");
- $('#centerNav').find('.centerBox').slideDown();
- fixedBody();
- }
- }).on("click", '#centerNav .wrap',function (e) {
- e.stopPropagation();
- }).on("click", '#centerNav .centerBox',function () {
- $('#centerNav').find('.home').removeClass("on");
- $('#centerNav').find('.centerBox').slideUp();
- looseBody();
- });
- }
- // 侧边栏滚动判断
- $(window).scroll(function () {
- if($('body').attr("style") && $('body').attr("style").indexOf('fixed')>0){
- return false;
- }
- var scoll = Math.max($('html').scrollTop(), $('body').scrollTop());
- if(scoll >200){
- $('#scrollTop').show();
- }else {
- $('#scrollTop').hide();
- }
- });
- // 顶部搜索框
- $('#topSearch').on("click", '.searchBtn', function () {
- /*
- * 搜索类型 type
- * 0:产品 1:供应商 2:项目仪器 NaN:文章
- * 关键词 keyword
- * */
- const type = isPC ? $('#topSearch').find('[data-select]').attr("data-select") * 1 : $('#topSearch').find('select').val() * 1;
- const keyword = $.trim($('#topSearch').find('.keyword').val());
- const tips = isNaN(type) ? '请输入文章关键词' : '请输入搜索关键词';
- if ((type === 0 && keyword.length < 2) || (!type && !keyword)) {
- CAIMEI.dialog(tips,true,function () {});
- return false;
- }
- if (type === 0) {
- // 产品
- window.location.href = '/product/list.html?keyword=' + encodeURIComponent(keyword);
- } else if (type === 1) {
- // 供应商
- if (!keyword) {
- window.location.href = '/supplier/list.html';
- } else {
- window.location.href = '/supplier/list.html?keyword=' + encodeURIComponent(keyword);
- }
- } else if (type === 2) {
- // 项目仪器
- if (!keyword) {
- window.location.href = '/equipment/list.html';
- } else {
- window.location.href = '/equipment/list.html?keyword=' + encodeURIComponent(keyword);
- }
- } else {
- // 文章
- window.location.href = '/info/search-1.html?keyword=' + encodeURIComponent(keyword);
- }
- }).on('keyup', '.keyword', function (event) {
- // 搜索输入框 按回车键搜索
- var keyCode = event.keyCode || event.which;
- if (keyCode === 13) {
- $(this).parents('#topSearch').find('.searchBtn').trigger("click");
- }
- }).on("click", '.hotKey .word', function () {
- // 点击热词 触发搜索
- $(this).parents('#topSearch').find('.keyword').val($(this).text());
- $(this).parents('#topSearch').find('.searchBtn').trigger("click");
- });
- // 支付弹框复制标识
- $('body').on("click", '.payAlert .copy',function () {
- var oInput = document.createElement('textarea');
- oInput.value = $(this).parents('.payAlert').find('.no').text();
- document.body.appendChild(oInput);
- oInput.select(); // 选择对象
- document.execCommand("Copy"); // 执行浏览器复制命令
- document.body.removeChild(oInput);
- CAIMEI.dialog('复制成功');
- });
- });
- /*function uuid() {
- var s = [];
- var hexDigits = "0123456789abcdef";
- for (var i = 0; i < 36; i++) {
- s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
- }
- s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
- s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
- s[8] = s[13] = s[18] = s[23] = "-";
- return s.join("");
- }*/
- function setBeforeUrl(){
- var baseUrl = window.location.href;
- var flag = baseUrl.indexOf('/login.html')>0 || baseUrl.indexOf('/register.html')>0 || baseUrl.indexOf('/we_chat/redirect_uri.html')>0;
- if(!flag){
- setBaseCookie("loginBeforePath", baseUrl);
- }
- }
- // 公共方法
- function setBaseCookie(cname,cvalue,exdays){
- if (exdays) {
- var d = new Date();
- d.setTime(d.getTime()+(exdays*24*60*60*1000));
- var expires = "expires="+d.toGMTString();
- document.cookie = cname+"="+cvalue+"; path=/; "+expires;
- } else {
- document.cookie = cname+"="+cvalue+"; path=/";
- }
- }
- function getBaseCookie(cname){
- if (document.cookie) {
- var name = cname + "=";
- var ca = document.cookie.split(';');
- for(var i=0; i<ca.length; i++) {
- var c = ca[i].trim();
- if (c && c.indexOf(name)===0) {
- return c.substring(name.length,c.length);
- }
- }
- }
- return "";
- }
- function delBaseCookie(cname){
- var exp = new Date();
- exp.setTime(exp.getTime() - 1);
- var cval=getBaseCookie(cname);
- if(cval!=null) {
- document.cookie= cname + "="+cval+";expires="+exp.toGMTString();
- }
- }
- function getDateStr(dd, addCount) {
- dd.setDate(dd.getDate() + addCount);//获取addCount天后的日期
- var y = dd.getFullYear();
- var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1);//获取当前月份的日期,不足10补0
- var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
- return y + "/" + m + "/" + d;
- }
- function jqClickShow(tab, con){
- $("body").on("click", tab, function(e){
- e.stopPropagation();
- if($(tab).hasClass("on")){
- $(tab).removeClass("on");
- $(con).slideUp("fast");
- }else{
- $(tab).addClass("on");
- $(con).slideDown("fast");
- }
- }).on("click", function(){
- $(tab).removeClass("on");
- $(con).slideUp("fast");
- });
- }
- function jqHoverShow(tab, con){
- $("body").on("mouseover", tab, function(e){
- e.stopPropagation();
- if($(tab).hasClass("on")){
- $(tab).removeClass("on");
- $(con).slideUp("fast");
- }else{
- $(tab).addClass("on");
- $(con).slideDown("fast");
- }
- }).on("mouseover", con, function(e){
- e.stopPropagation();
- }).on("mouseover", function(e){
- $(tab).removeClass("on");
- $(con).slideUp("fast");
- });
- }
- function jqMultipleShow(event, item, tab, con, stop){
- $("body").on(event, item+' '+tab, function(e){
- e.stopPropagation();
- $(this).parents(item).siblings(item).find(con).slideUp("fast");
- $(this).parents(item).siblings(item).removeClass("on");
- $(this).parents(item).siblings(item).find(tab).removeClass("on");
- if($(this).hasClass("on")){
- $(this).removeClass("on");
- $(this).parents(item).removeClass("on");
- $(this).parents(item).find(con).slideUp("fast");
- }else{
- $(this).addClass("on");
- $(this).parents(item).addClass("on");
- $(this).parents(item).find(con).slideDown("fast");
- }
- }).on(event, item+' '+con, function(e){
- e.stopPropagation();
- }).on(event, function(){
- if(stop){
- $(item+' '+tab).removeClass("on");
- $(item).removeClass("on");
- $(item+' '+con).slideUp("fast");
- }
- });
- }
- function jqSelect(selectBox){
- $("body").on("click", selectBox, function(e){
- e.stopPropagation();
- var select = $(this).find("select");
- var options = select.find("option");
- var list = "";
- for (var i=0; i<options.length; i++){
- list += '<li data-id="'+$(options[i]).val()+'">'+$(options[i]).text()+'</li>';
- if($(options[i]).val()===select.val()){
- $(this).find("[data-select]").text($(options[i]).text()).attr('data-select',$(options[i]).val());
- }
- }
- $(this).find("ul").html(list);
- $(this).find("ul").slideToggle("fast");
- }).on("click", selectBox + " li", function(e){
- e.stopPropagation();
- $(this).parent().prev().attr('data-select',$(this).attr("data-id")).text($(this).text());
- $(this).parents("pc").next().val($(this).attr("data-id"));
- $(this).parent().slideUp("fast");
- }).on("click", function(){
- $(selectBox).find("ul").slideUp("fast");
- });
- }
- //解决移动端滚动穿透
- function fixedBody(){
- var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
- setTimeout(function(){
- document.body.style.cssText += 'position:fixed;top:-'+scrollTop+'px;';
- },10);
- }
- function looseBody() {
- var body = document.body;
- body.style.position = '';
- var top = body.style.top;
- document.body.scrollTop = document.documentElement.scrollTop = -parseInt(top);
- body.style.top = '';
- }
- //url参数
- function getUrlParam(name) {
- var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
- var r = decodeURIComponent(window.location.search).substr(1).match(reg);
- if (r != null) {
- return (r[2])
- }
- return null;
- }
- function updateUrlParam(params) {
- var loca = window.location;
- var baseUrl = loca.origin + loca.pathname + "?";
- var query = loca.search.substr(1).toLowerCase();
- var queryArr = query.split("&");
- var keys = Object.keys(params);
- if (keys.length > 0) {
- var obj = {};
- for (var i = 0; i < queryArr.length; i++) {
- queryArr[i] = queryArr[i].split("=");
- obj[queryArr[i][0]] = queryArr[i][1]
- }
- for (var k = 0; k < keys.length; k++) {
- var name = keys[k];
- var value = params[name];
- obj[name.toLowerCase()] = value;
- }
- var url = baseUrl + JSON.stringify(obj).replace(/["\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
- return url;
- }
- }
- function setSearchProductList(list, userId, callback) {//处理搜索
- var productIdArr = [];
- var resultData = [];
- list.map(function (item) {
- resultData.push({
- productId: item.productId,
- name: item.name,
- image: item.image,
- unit: item.unit,
- brandName: item.brandName,
- priceFlag: item.priceFlag,
- priceGrade: item.priceGrade,
- actStatus: 0,
- priceLoaded: false,
- beautyActFlag:item.beautyActFlag,
- productType:item.productType
- });
- // 0公开价格 1不公开价格 2仅对会员机构公开
- if (item.priceFlag !== 1) {
- productIdArr.push(item.productId)
- }
- });
- if (userId && userId > 0) {
- setProductPrice(resultData, productIdArr.join(","), userId, callback);
- }else {
- setProductPrice(resultData, productIdArr.join(","), 0, callback);
- }
- return resultData;
- }
- function setProductPrice(productList, productIds, userId, callback){
- $.getJSON(coreServer+"/commodity/price/list",{
- userId: userId,
- productIds: productIds,
- source: 1
- }).done(function (r) {
- if (r.code === 0 && r.data) {
- var priceList = r.data;
- productList.map(function(product){
- priceList.map(function(item){
- if(product.productId*1 === item.productId){
- product.shopId = item.shopId;
- product.userIdentity = item.userIdentity;
- product.price = item.price;
- product.originalPrice = item.originalPrice;
- product.priceLoaded = true;
- product.ladderPriceFlag = item.ladderPriceFlag;
- product.actStatus =item.actStatus;
- product.couponsLogo =item.couponsLogo;
- product.promotions =item.promotions;
- product.svipPriceTag =item.svipPriceTag;
- product.svipPriceType =item.svipPriceType;
- product.svipProductFlag =item.svipProductFlag;
- }
- });
- });
- }
- return callback();
- }).fail(function(){
- return callback();
- })
- }
- // 登录后返回登录前页面
- function toBeforePath(){
- var loginBeforePath = getBaseCookie("loginBeforePath");
- if (loginBeforePath && loginBeforePath!=='undefined' && loginBeforePath.indexOf('.html')>0) {
- delBaseCookie("loginBeforePath");
- window.location.href = loginBeforePath;
- }
- window.location.href = '/index.html';
- }
- function toLogin() {//去登录
- setBeforeUrl();
- window.location.href = '/login.html';
- }
- function upgrade () { //升级会员
- window.location.href='';
- }
- function toLogOut() {//登出
- localStorage.removeItem('userInfo');
- delBaseCookie("loginBeforePath");
- this.loginStatus = false;
- window.location.href = "/index.html";
- }
- /**
- * 至少保留两位小数
- * 10 => "10.00"
- * @param {number} num
- */
- function toFloat(num) {
- var temp = String(num).split('.');
- if (temp.length === 1 || temp[1].length < 2) {
- return Number(num).toFixed(2);
- }else{
- return Number(num);
- }
- }
- /** 表单输入框校验 */
- function verifyHandle(obj){
- if ($(obj).is(":hidden")) { return false; }
- var v = $.trim($(obj).val()).replace(/\s+/g,"");
- var reg = $(obj).attr("rule");
- var errorTxt = $(obj).siblings('.errTips').attr("tips");
- if ($.trim(v) === '') {
- if ($(obj).attr("placeholder") && $(obj).attr("placeholder").indexOf("请输入")>=0) {
- errorTxt = $(obj).attr("placeholder").split("请输入")[1]+'不能为空';
- } else {
- errorTxt = '不能为空';
- }
- setErrorTxt(obj, errorTxt);
- return false;
- }else if (typeof reg != "undefined") {
- reg = new RegExp(reg);
- if (!reg.test(v)) {
- setErrorTxt(obj, errorTxt);
- return false;
- }
- }
- clearErrorTxt(obj);
- }
- function setErrorTxt(obj, txt) {
- $(obj).parent().addClass("error").find('.checked').removeClass("show");
- $(obj).siblings('.errTips').text(txt).addClass("show");
- }
- function clearErrorTxt(obj) {
- $(obj).siblings('.errTips').removeClass("show");
- $(obj).parent().removeClass("error").find('.checked').addClass("show");
- }
- function clearAllErrorTxt(obj) {
- $(obj).siblings('.errTips').removeClass("show");
- $(obj).parent().removeClass("error");
- }
- // 提交时验证表单
- function verifyForm() {
- $("[needverify]:visible").each(function (index, ele) {
- if (!$(ele).siblings('.checked').hasClass("show")) {
- verifyHandle(ele);
- }
- });
- var len = $('.errTips.show:visible').length;
- return (len === 0);
- }
- // 单个验证表单
- function verifyCheack(ele) {
- if (!$(ele).siblings('.checked').hasClass("show")) {
- verifyHandle(ele);
- }
- var len = $(ele).siblings('.errTips.show:visible').length;
- return (len === 0);
- }
- // 公共信息提示弹框
- function alertInfo(txt,callback) {
- $.confirm({
- useBootstrap: false,
- boxWidth: (isPC?'300px':'70%'),
- title:'提示',
- content: txt,
- closeIcon: true,
- animation: 'opacity',
- closeAnimation: 'opacity',
- animateFromElement: false,
- buttons: {
- close: {
- text: '确定',
- btnClass: 'btn-confirm',
- action: function () {
- callback()
- }
- }
- }
- });
- }
- //公共吐司
- function dialog(txt,callback) {
- $.confirm({
- title: false,
- content: txt,
- boxWidth: (isPC?'300px':'70%'),
- autoClose: 'close|2000',
- useBootstrap:false,
- buttons: {
- close:{
- isHidden: true,
- action: function () {
- callback()
- }
- }
- }
- });
- }
- /** 时间格式化
- * @param {Date} date 标准时间格式 -> new Date()
- * @param {string} format 时间格式化的格式 'yyyy-MM-dd hh:mm:ss'
- * @returns {string} 格式化后的时间 '2017-01-01 01:00:00'
- */
- function dateFormat(date = new Date(), format = 'yyyy-MM-dd hh:mm:ss') {
- var o = {
- 'M+': date.getMonth() + 1, // month
- 'd+': date.getDate(), // day
- 'h+': date.getHours(), // hour
- 'm+': date.getMinutes(), // minute
- 's+': date.getSeconds(), // second
- 'q+': Math.floor((date.getMonth() + 3) / 3), // quarter
- S: date.getMilliseconds(), // millisecond
- };
- if (/(y+)/.test(format)) {
- format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
- }
- for (var k in o) {
- if (new RegExp('(' + k + ')').test(format)) {
- format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
- }
- }
- return format
- }
- /**
- * @param {Array} actual
- * @returns {Array}
- */
- function cleanArray(actual) {
- const newArray = []
- for (let i = 0; i < actual.length; i++) {
- if (actual[i]) {
- newArray.push(actual[i])
- }
- }
- return newArray
- }
- /**
- * @param {Object} json
- * @returns {Array}
- */
- function param(json) {
- if (!json) return ''
- return cleanArray(
- Object.keys(json).map(key => {
- if (json[key] === undefined) return ''
- return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
- })
- ).join('&')
- }
- /**
- * 防抖
- */
- function debounce(func, wait = 200, immediate = false) {
- let timeout, result;
- return function () {
- const context = this;
- const args = arguments;
- if (timeout) clearTimeout(timeout);
- if (immediate) {
- const callNow = !timeout;
- timeout = setTimeout(function () {
- timeout = null;
- }, wait);
- if (callNow) result = func.apply(context, args);
- } else {
- timeout = setTimeout(function () {
- func.apply(context, args);
- }, wait);
- }
- return result;
- };
- }
- /* 深度克隆 */
- function deepClone(obj, cache = new WeakMap()) {
- if (typeof obj !== 'object') return obj // 普通类型,直接返回
- if (obj === null) return obj
- if (cache.get(obj)) return cache.get(obj) // 防止循环引用,程序进入死循环
- if (obj instanceof Date) return new Date(obj)
- if (obj instanceof RegExp) return new RegExp(obj)
- // 找到所属原型上的constructor,所属原型上的constructor指向当前对象的构造函数
- let cloneObj = new obj.constructor()
- cache.set(obj, cloneObj) // 缓存拷贝的对象,用于处理循环引用的情况
- for (let key in obj) {
- if (obj.hasOwnProperty(key)) {
- cloneObj[key] = deepClone(obj[key], cache) // 递归拷贝
- }
- }
- return cloneObj
- }
|