base.js 29 KB

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