base.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. var coreServer = $("#coreServer").val();
  2. var spiServer = $("#spiServer").val();
  3. var isPC = ($(window).width()>768);
  4. var globalUserData = '';
  5. var GLOBAL_TOKEN = 'X-Token';
  6. var GLOBAL_USER_ID = 0;
  7. var GLOBAL_USER_IDENTITY = 0;//2-会员机构;3-供应商;4-普通机构
  8. var GLOBAL_SHOP_ID = 0;
  9. if(localStorage.getItem('userInfo')){
  10. globalUserData = JSON.parse(localStorage.getItem('userInfo'));
  11. GLOBAL_TOKEN = globalUserData.token;
  12. GLOBAL_USER_ID = globalUserData.userId*1;
  13. GLOBAL_USER_IDENTITY = globalUserData.userIdentity*1;
  14. GLOBAL_SHOP_ID = globalUserData.shopId*1;
  15. if (GLOBAL_USER_ID === 5261 || GLOBAL_USER_ID === 10947 || GLOBAL_USER_ID === 11579) {
  16. GLOBAL_USER_IDENTITY = 1;
  17. }
  18. } else {
  19. var pathname = window.location.pathname;
  20. var weChatLoginFlag = (Number(getBaseCookie("weChatAutoLogin"))===1 || Number(getBaseCookie("weChatAutoLogin"))===2);
  21. if(pathname.indexOf('/product/auth/') === -1 && !weChatLoginFlag ){
  22. var userAgent = navigator.userAgent.toLowerCase();
  23. if (userAgent.match(/MicroMessenger/i)) {
  24. // 微信浏览器自动授权登录
  25. var urlForWeChat = 'https://www.caimei365.com/we_chat/redirect_uri.html';
  26. $.get(spiServer+'/user/authorizationLink?mode=1&redirectUri='+urlForWeChat, function(r){
  27. if(r.code===0 && r.data){
  28. setBaseCookie("weChatAutoLogin", 1);
  29. setBeforeUrl();
  30. window.location.href = r.data;
  31. }
  32. });
  33. }
  34. }
  35. }
  36. // 头部
  37. var globalHead = new Vue({
  38. el: '#globalHead',
  39. data: {
  40. loginStatus: false,
  41. userData: {},
  42. classify: [],
  43. headCart: {
  44. cartList: [],
  45. cartCount: 0,
  46. productCount: 0,
  47. priceTotal: 0
  48. },
  49. shopId:'',
  50. userIdentity:'',
  51. articleType: '',
  52. isFiexd:false,
  53. classifyIndex:1,
  54. nav_linkName:''
  55. },
  56. methods: {
  57. changeClassify: function(value){
  58. this.classifyIndex=value;
  59. },
  60. // 初始化分类菜单效果
  61. initClassufyTab: function(){
  62. if(isPC){
  63. setTimeout(function(){
  64. $('#mainClassify').slide({
  65. mainCell:".clsCon",
  66. titCell:".clsTab a",
  67. trigger: "mouseover"
  68. });
  69. $('#mainClassify_1').slide({
  70. mainCell:".tabItem_right",
  71. titCell:".tabItem_lift a",
  72. trigger: "mouseover"
  73. });
  74. $('#mainClassify_2').slide({
  75. mainCell:".tabItem_right",
  76. titCell:".tabItem_lift a",
  77. trigger: "mouseover"
  78. });
  79. $("#mainClassify_2 .tabItem_lift a").eq(0).trigger("mouseover");
  80. $("#mainClassify_1 .tabItem_lift a").eq(0).trigger("mouseover");
  81. },500);
  82. }else{
  83. setTimeout(function(){
  84. $('#mainClassify').slide({
  85. mainCell:".clsCon",
  86. titCell:".clsTab a",
  87. trigger: "click"
  88. });
  89. $('#mainClassify_1').slide({
  90. mainCell:".tabItem_right",
  91. titCell:".tabItem_lift a",
  92. trigger: "click"
  93. });
  94. $('#mainClassify_2').slide({
  95. mainCell:".tabItem_right",
  96. titCell:".tabItem_lift a",
  97. trigger: "click"
  98. });
  99. $("#mainClassify_2 .tabItem_lift a").eq(0).trigger("click");
  100. $("#mainClassify_1 .tabItem_lift a").eq(0).trigger("click");
  101. },500);
  102. }
  103. },
  104. // 头部购物车数据
  105. getHeadCart: function(userId) {
  106. var _self = this;
  107. tokenAjax("get", "/shoppingCart/header/cart", {userId: userId},function (r) {
  108. if (r.code === 0 && r.data) {
  109. _self.headCart.cartList = r.data;
  110. _self.headCart.cartCount = r.data.length;
  111. _self.headCart.productCount = 0;
  112. _self.headCart.priceTotal = 0;
  113. r.data.map(function(item){
  114. _self.headCart.productCount += item.number;
  115. _self.headCart.priceTotal += item.number*item.price;
  116. });
  117. }else if(r.code== -99){
  118. CAIMEI.Storage.clear();
  119. location.href = "/login.html";
  120. }
  121. });
  122. },
  123. goCartsLinkFn:function(){
  124. var _self = this;
  125. if(_self.loginStatus){
  126. window.location.href='/shopping/cart.html';
  127. }else{
  128. window.location.href='/login.html';
  129. }
  130. },
  131. productDetailsFn:function(id){ // 跳转详情
  132. window.location.href='/product-'+id+'.html';
  133. },
  134. DeleteCartProducts:function(id){ // 删除购物车
  135. var _self = this;
  136. ShoppingApi.DeleteCartProducts({userID: this.userData.userId, productIDs: id},function(response){
  137. if(response.code === 0){
  138. _self.getHeadCart(_self.userData.userId);
  139. }else{
  140. CAIMEI.Alert(response.msg,'确定',false);
  141. }
  142. });
  143. },
  144. pageLinkSupplier: function(){//预览商品
  145. window.open('/supplier-'+this.shopId+'.html');
  146. },
  147. // 退出登录
  148. userLogOut: function(){
  149. localStorage.removeItem('userInfo');
  150. delBaseCookie("loginBeforePath");
  151. this.loginStatus = false;
  152. window.location.href = "/index.html";
  153. },
  154. showGlobalMenu: function(){
  155. if(!isPC){
  156. $("#mGlobalMenu").show().find(".cShow").slideDown(500);
  157. }
  158. },
  159. hideGlobalMenu: function(){
  160. if(!isPC){
  161. $("#mGlobalMenu").hide().find(".cShow").hide();
  162. }
  163. }
  164. },
  165. created: function () {
  166. // 判断登录状态
  167. if (globalUserData.token) {
  168. this.loginStatus = true;
  169. this.userData = globalUserData;
  170. var userId = this.userData.userId;
  171. if(userId){
  172. var _self = this;
  173. // 获取头部购物车数据
  174. setTimeout(function(){
  175. _self.getHeadCart(userId);
  176. }, 1000);
  177. }
  178. }
  179. // 信息中心
  180. this.articleType = getUrlParam("type");
  181. },
  182. mounted:function(){
  183. var _self = this;
  184. // 初始化分类菜单效果
  185. this.initClassufyTab();
  186. var userData = JSON.parse(window.localStorage.getItem('userInfo'));
  187. if(userData!=null) {
  188. this.userIdentity = userData.userIdentity;
  189. this.shopId = userData.shopId;
  190. }
  191. if($(window).width() > 1400){
  192. $(window).on('scroll', function() {
  193. var scrollTop = $(this).scrollTop();
  194. if(scrollTop>200){
  195. _self.isFiexd = true;
  196. }else{
  197. _self.isFiexd = false;
  198. }
  199. })
  200. }
  201. console.log('hello')
  202. _self.nav_linkName = decodeURI(CAIMEI.getUrlParam('name'));
  203. if(!_self.nav_linkName || _self.nav_linkName.length === 0 || _self.nav_linkName == "undefined") {
  204. var paramsArr = window.location.pathname.split(".")[0].split("-");
  205. if (paramsArr[0].indexOf('/product/type') >= 0) {
  206. var pageId = paramsArr.length>=1 ? paramsArr[1] : '';
  207. if (pageId*1 === 287) {
  208. _self.nav_linkName = "产品";
  209. } else if (pageId*1 === 286) {
  210. _self.nav_linkName = "仪器";
  211. }
  212. } else if (paramsArr[0].indexOf('/info/center') >= 0){
  213. _self.nav_linkName = "信息平台";
  214. } else if (paramsArr[0].indexOf('/flea-market') >= 0 && (paramsArr.length>=1 && paramsArr[1].indexOf('market') >= 0)){
  215. _self.nav_linkName = "二手市场";
  216. } else if (paramsArr[0].indexOf('/investment') >= 0){
  217. _self.nav_linkName = "品牌招商";
  218. } else if (paramsArr[0].indexOf('/repair') >= 0){
  219. _self.nav_linkName = "维修";
  220. }
  221. }
  222. // _self.nav_linkName = window.localStorage.getItem('name');
  223. setTimeout(function(){
  224. $('.navBox li').each(function () {
  225. var _thisName = $(this).find('a').text();
  226. if(_self.nav_linkName == _thisName){
  227. $(this).find('a').addClass('on')
  228. }
  229. });
  230. },500);
  231. }
  232. });
  233. // 初始化效果
  234. $(function(){
  235. // PC,H5切换时刷新
  236. $(window).resize(function() {
  237. var flag = (isPC && $(window).width()<=768) || (!isPC && $(window).width()>768);
  238. if(flag){
  239. window.location.reload();
  240. }
  241. });
  242. // 导航分类
  243. if(isPC){
  244. jqClickShow(".baseHeadTop .cTab", ".baseHeadTop .cShow");
  245. jqSelect(".jqSelect");
  246. jqHoverShow(".classBtn", "#mainClassify");
  247. }else{
  248. jqMultipleShow("click", ".footLink .list", ".tab", ".con", true);
  249. $('body').on('click', '.baseHeadCenter .mClassBtn',function () {
  250. $('#mainClassify').show();
  251. fixedBody();
  252. }).on('click', '#mainClassify .close,#mainClassify .mClassBtn',function () {
  253. $('#mainClassify').hide();
  254. looseBody();
  255. }).on('click', '#mainClassify',function (e) {
  256. e.stopPropagation();
  257. });
  258. }
  259. // 登录弹窗
  260. function loginAert(content, btnTxt){
  261. $.confirm({
  262. useBootstrap: false,
  263. boxWidth: (isPC?'338px':'74.6vw'),
  264. title: false,
  265. content:'<div class="loginAlert">'+content+'</div>',
  266. closeIcon: true,
  267. animation: 'opacity',
  268. closeAnimation: 'opacity',
  269. animateFromElement: false,
  270. scrollToPreviousElement: false,
  271. buttons: {
  272. login: {
  273. text: btnTxt,
  274. btnClass: 'btn-confirm-login',
  275. action: function(){
  276. setBeforeUrl();
  277. window.location.href = '/login.html';
  278. }
  279. },
  280. close: {
  281. text: '取消',
  282. btnClass: 'btn-cancel-login'
  283. }
  284. }
  285. });
  286. }
  287. // 去登录弹窗
  288. $('body').on("click", '.toLogin',function () {
  289. //loginAert('<span>你还未登录</span><span>请登录后再进行购买</span>', '去登录');
  290. setBeforeUrl();
  291. window.location.href = '/login.html';
  292. });
  293. // 退出登录
  294. $('body').on("click", '.toLogOut',function () {
  295. localStorage.removeItem('userInfo');
  296. delBaseCookie("loginBeforePath");
  297. globalHead.loginStatus = false;
  298. window.location.href = "/index.html";
  299. });
  300. // 置顶
  301. $('#scrollTop').on("click", '.toTop',function () {
  302. $("html,body").animate({scrollTop:0},500);
  303. });
  304. // 热线
  305. if(!isPC){
  306. $('#scrollTop').on("click", '.phone',function () {
  307. $('#scrollTop').find('.phoneHover').show();
  308. fixedBody();
  309. }).on("click", '.phoneHover div',function (e) {
  310. e.stopPropagation();
  311. }).on("click", '.phoneHover,.phoneHover .close',function () {
  312. $('#scrollTop').find('.phoneHover').hide();
  313. looseBody();
  314. });
  315. $('body').on("click", '#centerNav .home',function () {
  316. if($('#centerNav').find('.home').hasClass("on")){
  317. $('#centerNav').find('.home').removeClass("on");
  318. $('#centerNav').find('.centerBox').slideUp();
  319. looseBody();
  320. }else{
  321. $('#centerNav').find('.home').addClass("on");
  322. $('#centerNav').find('.centerBox').slideDown();
  323. fixedBody();
  324. }
  325. }).on("click", '#centerNav .wrap',function (e) {
  326. e.stopPropagation();
  327. }).on("click", '#centerNav .centerBox',function () {
  328. $('#centerNav').find('.home').removeClass("on");
  329. $('#centerNav').find('.centerBox').slideUp();
  330. looseBody();
  331. });
  332. }
  333. // 侧边栏滚动判断
  334. $(window).scroll(function () {
  335. if($('body').attr("style") && $('body').attr("style").indexOf('fixed')>0){
  336. return false;
  337. }
  338. var scoll = Math.max($('html').scrollTop(), $('body').scrollTop());
  339. if(scoll >200){
  340. $('#scrollTop').show();
  341. }else {
  342. $('#scrollTop').hide();
  343. }
  344. });
  345. // 顶部搜索框
  346. $('#topSearch').on("click", '.searchBtn', function(){
  347. var type = isPC ? $('#topSearch').find('[data-select]').attr("data-select")*1 : $('#topSearch').find('select').val()*1;
  348. var keyword = $.trim($('#topSearch').find('.keyword').val());
  349. // 商品
  350. if (keyword.length < 2) {
  351. $.confirm({
  352. useBootstrap: false,
  353. boxWidth: (isPC?'300px':'70%'),
  354. title:'提示',
  355. content:'请至少输入两个关键字!',
  356. closeIcon: true,
  357. animation: 'opacity',
  358. closeAnimation: 'opacity',
  359. animateFromElement: false,
  360. buttons: {
  361. close: {
  362. text: '确定',
  363. btnClass: 'btn-confirm'
  364. }
  365. }
  366. });
  367. return false;
  368. }
  369. if (type === 0) {
  370. window.location.href = '/product/list.html?keyword='+encodeURIComponent(keyword);
  371. } else if(type === 1) {
  372. // 供应商
  373. window.location.href = '/supplier/list.html?keyword='+encodeURIComponent(keyword);
  374. } else if (type === 2) {
  375. // 项目仪器
  376. window.location.href = '/equipment/list.html?keyword=' + encodeURIComponent(keyword);
  377. } else{
  378. // 文章
  379. window.location.href = '/info/search.html?keyword=' + encodeURIComponent(keyword);
  380. }
  381. }).on('keyup', '.keyword', function(event) {
  382. // 搜索输入框 按回车键搜索
  383. var keyCode = event.keyCode || event.which;
  384. if(keyCode === 13){
  385. $(this).parents('#topSearch').find('.searchBtn').trigger("click");
  386. }
  387. }).on("click", '.hotKey .word', function(){
  388. // 点击热词 触发搜索
  389. $(this).parents('#topSearch').find('.keyword').val($(this).text());
  390. $(this).parents('#topSearch').find('.searchBtn').trigger("click");
  391. });
  392. // 支付弹框复制标识
  393. $('body').on("click", '.payAlert .copy',function () {
  394. var oInput = document.createElement('textarea');
  395. oInput.value = $(this).parents('.payAlert').find('.no').text();
  396. document.body.appendChild(oInput);
  397. oInput.select(); // 选择对象
  398. document.execCommand("Copy"); // 执行浏览器复制命令
  399. document.body.removeChild(oInput);
  400. CAIMEI.dialog('复制成功');
  401. });
  402. });
  403. /*function uuid() {
  404. var s = [];
  405. var hexDigits = "0123456789abcdef";
  406. for (var i = 0; i < 36; i++) {
  407. s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  408. }
  409. s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  410. s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  411. s[8] = s[13] = s[18] = s[23] = "-";
  412. return s.join("");
  413. }*/
  414. function setBeforeUrl(){
  415. var baseUrl = window.location.href;
  416. var flag = baseUrl.indexOf('/login.html')>0 || baseUrl.indexOf('/register.html')>0 || baseUrl.indexOf('/we_chat/redirect_uri.html')>0;
  417. if(!flag){
  418. setBaseCookie("loginBeforePath", baseUrl);
  419. }
  420. }
  421. // 公共方法
  422. function setBaseCookie(cname,cvalue,exdays){
  423. if (exdays) {
  424. var d = new Date();
  425. d.setTime(d.getTime()+(exdays*24*60*60*1000));
  426. var expires = "expires="+d.toGMTString();
  427. document.cookie = cname+"="+cvalue+"; path=/; "+expires;
  428. } else {
  429. document.cookie = cname+"="+cvalue+"; path=/";
  430. }
  431. }
  432. function getBaseCookie(cname){
  433. if (document.cookie) {
  434. var name = cname + "=";
  435. var ca = document.cookie.split(';');
  436. for(var i=0; i<ca.length; i++) {
  437. var c = ca[i].trim();
  438. if (c && c.indexOf(name)===0) {
  439. return c.substring(name.length,c.length);
  440. }
  441. }
  442. }
  443. return "";
  444. }
  445. function delBaseCookie(cname){
  446. var exp = new Date();
  447. exp.setTime(exp.getTime() - 1);
  448. var cval=getBaseCookie(cname);
  449. if(cval!=null) {
  450. document.cookie= cname + "="+cval+";expires="+exp.toGMTString();
  451. }
  452. }
  453. function getDateStr(dd, addCount) {
  454. dd.setDate(dd.getDate() + addCount);//获取addCount天后的日期
  455. var y = dd.getFullYear();
  456. var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1);//获取当前月份的日期,不足10补0
  457. var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
  458. return y + "/" + m + "/" + d;
  459. }
  460. function jqClickShow(tab, con){
  461. $("body").on("click", tab, function(e){
  462. e.stopPropagation();
  463. if($(tab).hasClass("on")){
  464. $(tab).removeClass("on");
  465. $(con).slideUp("fast");
  466. }else{
  467. $(tab).addClass("on");
  468. $(con).slideDown("fast");
  469. }
  470. }).on("click", function(){
  471. $(tab).removeClass("on");
  472. $(con).slideUp("fast");
  473. });
  474. }
  475. function jqHoverShow(tab, con){
  476. $("body").on("mouseover", tab, function(e){
  477. e.stopPropagation();
  478. if($(tab).hasClass("on")){
  479. $(tab).removeClass("on");
  480. $(con).slideUp("fast");
  481. }else{
  482. $(tab).addClass("on");
  483. $(con).slideDown("fast");
  484. }
  485. }).on("mouseover", con, function(e){
  486. e.stopPropagation();
  487. }).on("mouseover", function(e){
  488. $(tab).removeClass("on");
  489. $(con).slideUp("fast");
  490. });
  491. }
  492. function jqMultipleShow(event, item, tab, con, stop){
  493. $("body").on(event, item+' '+tab, function(e){
  494. e.stopPropagation();
  495. $(this).parents(item).siblings(item).find(con).slideUp("fast");
  496. $(this).parents(item).siblings(item).removeClass("on");
  497. $(this).parents(item).siblings(item).find(tab).removeClass("on");
  498. if($(this).hasClass("on")){
  499. $(this).removeClass("on");
  500. $(this).parents(item).removeClass("on");
  501. $(this).parents(item).find(con).slideUp("fast");
  502. }else{
  503. $(this).addClass("on");
  504. $(this).parents(item).addClass("on");
  505. $(this).parents(item).find(con).slideDown("fast");
  506. }
  507. }).on(event, item+' '+con, function(e){
  508. e.stopPropagation();
  509. }).on(event, function(){
  510. if(stop){
  511. $(item+' '+tab).removeClass("on");
  512. $(item).removeClass("on");
  513. $(item+' '+con).slideUp("fast");
  514. }
  515. });
  516. }
  517. function jqSelect(selectBox){
  518. $("body").on("click", selectBox, function(e){
  519. e.stopPropagation();
  520. var select = $(this).find("select");
  521. var options = select.find("option");
  522. var list = "";
  523. for (var i=0; i<options.length; i++){
  524. list += '<li data-id="'+$(options[i]).val()+'">'+$(options[i]).text()+'</li>';
  525. if($(options[i]).val()===select.val()){
  526. $(this).find("[data-select]").text($(options[i]).text()).attr('data-select',$(options[i]).val());
  527. }
  528. }
  529. $(this).find("ul").html(list);
  530. $(this).find("ul").slideToggle("fast");
  531. }).on("click", selectBox + " li", function(e){
  532. e.stopPropagation();
  533. $(this).parent().prev().attr('data-select',$(this).attr("data-id")).text($(this).text());
  534. $(this).parents("pc").next().val($(this).attr("data-id"));
  535. $(this).parent().slideUp("fast");
  536. }).on("click", function(){
  537. $(selectBox).find("ul").slideUp("fast");
  538. });
  539. }
  540. //解决移动端滚动穿透
  541. function fixedBody(){
  542. var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  543. setTimeout(function(){
  544. document.body.style.cssText += 'position:fixed;top:-'+scrollTop+'px;';
  545. },10);
  546. }
  547. function looseBody() {
  548. var body = document.body;
  549. body.style.position = '';
  550. var top = body.style.top;
  551. document.body.scrollTop = document.documentElement.scrollTop = -parseInt(top);
  552. body.style.top = '';
  553. }
  554. //url参数
  555. function getUrlParam(name) {
  556. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  557. var r = decodeURIComponent(window.location.search).substr(1).match(reg);
  558. if (r != null) {
  559. return (r[2])
  560. }
  561. return null;
  562. }
  563. function updateUrlParam(params) {
  564. var loca = window.location;
  565. var baseUrl = loca.origin + loca.pathname + "?";
  566. var query = loca.search.substr(1).toLowerCase();
  567. var queryArr = query.split("&");
  568. var keys = Object.keys(params);
  569. if (keys.length > 0) {
  570. var obj = {};
  571. for (var i = 0; i < queryArr.length; i++) {
  572. queryArr[i] = queryArr[i].split("=");
  573. obj[queryArr[i][0]] = queryArr[i][1]
  574. }
  575. for (var k = 0; k < keys.length; k++) {
  576. var name = keys[k];
  577. var value = params[name];
  578. obj[name.toLowerCase()] = value;
  579. }
  580. var url = baseUrl + JSON.stringify(obj).replace(/["\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
  581. return url;
  582. }
  583. }
  584. function tokenAjax(type, url, params, callback, errorBack){
  585. $.ajax({
  586. type: type,
  587. url: spiServer + url,
  588. xhrFields: {
  589. withCredentials: true
  590. },
  591. data: params,
  592. headers:{
  593. 'Content-Type': type=='post'?'application/x-www-form-urlencoded':'application/json;charset=utf8',
  594. 'X-Token':GLOBAL_TOKEN
  595. },
  596. success : function (res) {
  597. if(res.code === -99){
  598. localStorage.removeItem('userInfo');
  599. delBaseCookie("loginBeforePath");
  600. // window.location.href ='/login.html';
  601. }else{
  602. callback(res);
  603. }
  604. },
  605. error : function (res) {
  606. alertInfo("网络连接超时,请重试!",function (res) {
  607. console.log(res)
  608. });
  609. }
  610. });
  611. }
  612. function setSearchProductList(list, userId, callback) {//处理搜索
  613. var productIdArr = [];
  614. var resultData = [];
  615. list.map(function (item) {
  616. resultData.push({
  617. productId: item.productId,
  618. name: item.name,
  619. image: item.image,
  620. unit: item.unit,
  621. brandName: item.brandName,
  622. priceFlag: item.priceFlag,
  623. priceGrade: item.priceGrade,
  624. actStatus: 0,
  625. priceLoaded: false,
  626. beautyActFlag:item.beautyActFlag
  627. });
  628. // 0公开价格 1不公开价格 2仅对会员机构公开
  629. if (item.priceFlag !== 1) {
  630. productIdArr.push(item.productId)
  631. }
  632. });
  633. if (userId && userId > 0) {
  634. setProductPrice(resultData, productIdArr.join(","), userId, callback);
  635. }else {
  636. setProductPrice(resultData, productIdArr.join(","), 0, callback);
  637. }
  638. return resultData;
  639. }
  640. function setProductPrice(productList, productIds, userId, callback){
  641. $.getJSON(coreServer+"/commodity/price/list",{
  642. userId: userId,
  643. productIds: productIds
  644. }).done(function (r) {
  645. if (r.code === 0 && r.data) {
  646. var priceList = r.data;
  647. productList.map(function(product){
  648. priceList.map(function(item){
  649. if(product.productId*1 === item.productId){
  650. product.shopId = item.shopId;
  651. product.userIdentity = item.userIdentity;
  652. product.price = item.price;
  653. product.originalPrice = item.originalPrice;
  654. product.priceLoaded = true;
  655. product.ladderPriceFlag = item.ladderPriceFlag;
  656. product.actStatus =item.actStatus;
  657. product.promotions =item.promotions;
  658. }
  659. });
  660. });
  661. }
  662. return callback();
  663. }).fail(function(){
  664. return callback();
  665. })
  666. }
  667. // 登录后返回登录前页面
  668. function toBeforePath(){
  669. var loginBeforePath = getBaseCookie("loginBeforePath");
  670. if (loginBeforePath && loginBeforePath!='undefined' && loginBeforePath.indexOf('.html')>0) {
  671. delBaseCookie("loginBeforePath");
  672. window.location.href = loginBeforePath;
  673. }
  674. window.location.href = '/index.html';
  675. }
  676. function toLogin() {//去登录
  677. setBeforeUrl();
  678. window.location.href = '/login.html';
  679. }
  680. function upgrade () { //升级会员
  681. window.location.href='';
  682. }
  683. function toLogOut() {//登出
  684. localStorage.removeItem('userInfo');
  685. delBaseCookie("loginBeforePath");
  686. this.loginStatus = false;
  687. window.location.href = "/index.html";
  688. }
  689. /**
  690. * 至少保留两位小数
  691. * 10 => "10.00"
  692. * @param {number} num
  693. */
  694. function toFloat(num) {
  695. var temp = String(num).split('.');
  696. if (temp.length === 1 || temp[1].length < 2) {
  697. return Number(num).toFixed(2);
  698. }else{
  699. return Number(num);
  700. }
  701. }
  702. /** 表单输入框校验 */
  703. function verifyHandle(obj){
  704. if ($(obj).is(":hidden")) { return false; }
  705. var v = $.trim($(obj).val()).replace(/\s+/g,"");
  706. var reg = $(obj).attr("rule");
  707. var errorTxt = $(obj).siblings('.errTips').attr("tips");
  708. if ($.trim(v) === '') {
  709. if ($(obj).attr("placeholder") && $(obj).attr("placeholder").indexOf("请输入")>=0) {
  710. errorTxt = $(obj).attr("placeholder").split("请输入")[1]+'不能为空';
  711. } else {
  712. errorTxt = '不能为空';
  713. }
  714. setErrorTxt(obj, errorTxt);
  715. return false;
  716. }else if (typeof reg != "undefined") {
  717. reg = new RegExp(reg);
  718. if (!reg.test(v)) {
  719. setErrorTxt(obj, errorTxt);
  720. return false;
  721. }
  722. }
  723. clearErrorTxt(obj);
  724. }
  725. function setErrorTxt(obj, txt) {
  726. $(obj).parent().addClass("error").find('.checked').removeClass("show");
  727. $(obj).siblings('.errTips').text(txt).addClass("show");
  728. }
  729. function clearErrorTxt(obj) {
  730. $(obj).siblings('.errTips').removeClass("show");
  731. $(obj).parent().removeClass("error").find('.checked').addClass("show");
  732. }
  733. // 提交时验证表单
  734. function verifyForm() {
  735. $("[needverify]:visible").each(function (index, ele) {
  736. if (!$(ele).siblings('.checked').hasClass("show")) {
  737. verifyHandle(ele);
  738. }
  739. });
  740. var len = $('.errTips.show:visible').length;
  741. return (len === 0);
  742. }
  743. // 单个验证表单
  744. function verifyCheack(ele) {
  745. if (!$(ele).siblings('.checked').hasClass("show")) {
  746. verifyHandle(ele);
  747. }
  748. var len = $(ele).siblings('.errTips.show:visible').length;
  749. return (len === 0);
  750. }
  751. // 公共信息提示弹框
  752. function alertInfo(txt,callback) {
  753. $.confirm({
  754. useBootstrap: false,
  755. boxWidth: (isPC?'300px':'70%'),
  756. title:'提示',
  757. content: txt,
  758. closeIcon: true,
  759. animation: 'opacity',
  760. closeAnimation: 'opacity',
  761. animateFromElement: false,
  762. buttons: {
  763. close: {
  764. text: '确定',
  765. btnClass: 'btn-confirm',
  766. action: function () {
  767. callback()
  768. }
  769. }
  770. }
  771. });
  772. }
  773. //公共吐司
  774. function dialog(txt,callback) {
  775. $.confirm({
  776. title: false,
  777. content: txt,
  778. boxWidth: (isPC?'300px':'70%'),
  779. autoClose: 'close|2000',
  780. useBootstrap:false,
  781. buttons: {
  782. close:{
  783. isHidden: true,
  784. action: function () {
  785. callback()
  786. }
  787. }
  788. }
  789. });
  790. }
  791. // 加入购物车
  792. function addShoppingCart(userId, productId, count, callback){
  793. tokenAjax("post", "/shoppingCart/addCart", {
  794. userID: userId,
  795. productID: productId,
  796. productCount: count
  797. },function (res) {
  798. if(res && res.code*1 === 0){
  799. globalHead.getHeadCart(userId);
  800. $.confirm({
  801. useBootstrap: false,
  802. boxWidth: (isPC?'338px':'74.6vw'),
  803. title: false,
  804. content:'<div class="cartAlert"><h6>商品已成功加入购物车!</h6><p>当前购物车共<em>'+res.data+'</em>种商品</p></div>',
  805. closeIcon: true,
  806. animation: 'opacity',
  807. closeAnimation: 'opacity',
  808. animateFromElement: false,
  809. scrollToPreviousElement: false,
  810. buttons: {
  811. login: {
  812. text: '去结算',
  813. btnClass: 'btn-to-cart',
  814. action: function(){
  815. window.location.href = '/shopping/cart.html';
  816. }
  817. },
  818. close: {
  819. text: '继续购物',
  820. btnClass: 'btn-to-goon',
  821. action: callback?callback():function(){}
  822. }
  823. }
  824. });
  825. } else {
  826. dialog("加入购物车失败!");
  827. }
  828. });
  829. }