base.js 28 KB

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