//index.js //获取应用实例 var http = require("../../utils/http.js"); var util = require('../../utils/util.js'); var QQMapWX = require('../../utils/qqmap-wx-jssdk.js'); var qqmapsdk; const updateManager = wx.getUpdateManager() Page({ isHand:false, data: { active:1, imgUrl:'https://zswl-shop.oss-cn-chengdu.aliyuncs.com/', swiperCurrent:0, swiperList:[], shopName:'附近暂无可配送门店', indicatorDots: true, indicatorColor: '#d1e5fb', indicatorActiveColor: '#1b7dec', autoplay: true, interval: 2000, duration: 1000, indexImgs: [], seq: 0, news: [], hotSalesList: [], sts: 0, current: 1, sort: 1, isAll: false, snapUpList: [], //秒杀列表 aBulkList: [], //团购列表 pageTopHeight: wx.getWindowInfo().statusBarHeight + 30 + 7, gapTop: 1, titleOpacity: 1, days: 0, hours: 0, minutes: 0, seconds: 0, hotList: [], recommendedList: [], totalNum: 1, addCarshow: false, shopDetail: {}, select_address: '', categoryList: [], categoryList1: [], currentIndex: 0, topCurrentIndex: 0, currentTop: 0, shop_id: 0, get_distance: '', banner_img: [ { img:'https://zswl-dev.oss-cn-chengdu.aliyuncs.com/63b7c68b71a69169d1b33f92/store/bdb/user/avatar/JrXik2T4vhwp7c25b370159a7498499e7b4b76cfb288.png/1.png', name:'' }, { img:'https://zswl-dev.oss-cn-chengdu.aliyuncs.com/63b7c68b71a69169d1b33f92/store/bdb/user/avatar/OFG6necEvIOpcd39097fe6f106894503a4d77c14d7b8.png/1.png', name:'' }, ] }, onLoad: function () { // 实例化API核心类 qqmapsdk = new QQMapWX({ key: 'D3MBZ-LQK6U-IONVC-GJDPK-C43GF-UYFOC' // key: 'UNBBZ-OKDCB-FSTU4-N5EGG-CMJ67-CKB6H' }); // 绑定页面滚动事件 wx.pageScrollTo({ scrollTop: 0, // 初始滚动位置,可按需调整 duration: 0 }); this.get_setting() this.setData({ select_address: wx.getStorageSync('ADDRESS') }) setTimeout(() => { this.getAllData(); }, 1000) }, handleTab(e){ this.setData({ active:Number(e.currentTarget.dataset.active), current:Number(e.currentTarget.dataset.active), hotSalesList:[], isHand:true }) setTimeout(() => { this.getHotSalesProds() }, 100); }, // 顶部轮播滚动 changeIndex(e){ this.setData({ swiperCurrent:e.detail.current }) }, get_setting: function () { let that = this wx.getSetting({ success: (res) => { let authSetting = res.authSetting if (authSetting['scope.userLocation'] || authSetting['scope.userFuzzyLocation']) { that.getCurrentLocation() } else if (authSetting['scope.userLocation'] || authSetting['scope.userFuzzyLocation'] === false) { wx.removeStorageSync('ADDRESS') wx.showModal({ title: '您未开启地理位置授权', content: '请在系统设置中打开位置授权,以便我们为您提供更好的服务', success: (res) => { if (res.confirm) { wx.openSetting() } } }) } else { wx.authorize({ scope: 'scope.userLocation', scope: 'scope.userFuzzyLocation', success: () => { that.getCurrentLocation() }, fail: () => { wx.removeStorageSync('ADDRESS') wx.showModal({ title: '您未开启地理位置授权', content: '请在系统设置中打开位置授权,以便我们为您提供更好的服务', success: (res) => { if (res.confirm) { wx.openSetting() } } }) } }) } } }) }, getCurrentLocation() { let that = this wx.getFuzzyLocation({ type: 'wgs84', success: function (res) { const latitude = res.latitude const longitude = res.longitude wx.setStorageSync('LATITUDE', res.latitude) wx.setStorageSync('LONGITUDE', res.longitude) // 调用腾讯地图api获取当前位置 qqmapsdk.reverseGeocoder({ location: { latitude: latitude, longitude: longitude }, success: function (res) { console.log(res.result, '---address_success'); wx.setStorageSync('ADDRESS', res.result.address_component.street) that.setData({ select_address: wx.getStorageSync('ADDRESS') }) }, fail: function (res) { console.log(res, '---address_err'); wx.showToast({ title: res + '地址信息获取失败', icon: "none" }) setTimeout(() => { wx.hideToast(); }, 2000) }, complete: function (res) { // console.log(res, '---callback'); } }); }, fail: function (err) { wx.removeStorageSync('ADDRESS') console.log(err); if (err.errMsg === 'getFuzzyLocation:fail system permission denied') { wx.showModal({ title: '系统定位未开启', content: '请在系统设置中打开位置授权,以便我们为您提供更好的服务', success: (res) => {} }) } else if (err.errMsg === 'getFuzzyLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF' || err.errMsg === 'getFuzzyLocation:fail system permission denied' || err.errMsg === 'getFuzzyLocation:fail:system permission denied' || err.errMsg === 'getFuzzyLocation:fail auth deny') { wx.showModal({ title: '您未开启地理位置授权', content: '请在系统设置中打开位置授权,以便我们为您提供更好的服务', success: (res) => { if (res.confirm) { wx.openSetting() } } }) } } }) }, // 页面滚动到指定位置指定元素固定在顶部 onPageScroll: function (e) { //监听页面滚动 if (e.scrollTop < 10) { this.setData({ titleOpacity: 1 }) } if (e.scrollTop > 10) { this.setData({ titleOpacity: 0.8 }) } if (e.scrollTop > 20) { this.setData({ titleOpacity: 0.6 }) } if (e.scrollTop > 30) { this.setData({ titleOpacity: 0.2 }) } if (e.scrollTop >= 40) { this.setData({ titleOpacity: 0 }) } this.handlePageScroll(e.scrollTop); this.setData({ scrollTop: e.scrollTop }) }, handlePageScroll: function (scrollTop) { const query = wx.createSelectorQuery().in(this); query.select('#my-element').boundingClientRect(); query.exec((res) => { if (res && res[0]) { const elementTop = res[0].top; const relativeTop = elementTop - scrollTop; // 也可以将这个距离数据存储到data中,方便在页面中进行展示或其他操作 if (relativeTop < 0.5) { this.setData({ gapTop: relativeTop }); } else { this.setData({ gapTop: 1 }); } } }); }, /** * 广告位 */ getAdv: function () { var params = { url: "/advert/search", method: "GET", data: { current: 1, size:99, status:1 }, callBack: (res) => { this.setData({ swiperList: res.records }) } }; http.request(params); }, /** * 推荐词,type:1关键词,2热门搜索词,3推荐搜索词 */ getRecommended: function () { var params = { url: "/keyword/list", method: "GET", data: { type: 2 }, callBack: (res) => { let reslut = res.filter(item => item.status !== 2) //过滤下线词 let timeReslut = reslut.filter(e => util.dateToTimestamp(e.effectiveTime) < new Date().getTime()) //过滤未生效词 this.setData({ hotList: timeReslut }) } }; http.request(params); }, getRecommendeds: function () { var params = { url: "/keyword/list", method: "GET", data: { type: 3 }, callBack: (res) => { let reslut = res.filter(item => item.status !== 2) //过滤已线下推荐词 let timeReslut = reslut.filter(e => util.dateToTimestamp(e.effectiveTime) < new Date().getTime()) //过滤未到生效时间推荐词 this.setData({ recommendedList: timeReslut }) } }; http.request(params); }, /** * 推荐词搜索 */ topSwiperChange: function (e) { this.setData({ topCurrentIndex: e.detail.current // 获取当前滚动到的swiper-item的索引并更新到data中 }) }, topHotSearch: function () { const topname = this.data.hotList[this.data.topCurrentIndex].name wx.navigateTo({ url: '/pages/search-prod-show/search-prod-show?prodName=' + topname, }) }, swiperChange: function (e) { this.setData({ currentIndex: e.detail.current }); }, inputSearch: function () { const currentName = this.data.hotList[this.data.currentIndex].name; wx.navigateTo({ url: '/pages/search-prod-show/search-prod-show?prodName=' + currentName, }) }, recommendedSearch: function (e) { let name = e.currentTarget.dataset.name wx.navigateTo({ url: '/pages/search-prod-show/search-prod-show?prodName=' + name, }) }, /** * 对象映射,每多一个swiper-item需+10,用以金刚区的分类跳转到指定分类菜单,当菜单类大于三十个时需再次手动添加 * @param {*} e */ menuSwiper: function (e) { const topMap = { 0: 0, 1: 10, 2: 20 }; const currentValue = topMap[e.detail.current]; if (currentValue !== undefined) { this.setData({ currentTop: currentValue }); } }, /** * 当分类大于10时进行切割 */ splitList: function (arr) { let result = []; let groupCount = Math.ceil(arr.length / 5); for (let i = 0; i < groupCount; i++) { let startIndex = i * 5; let endIndex = Math.min((i + 1) * 5, arr.length); result.push(arr.slice(startIndex, endIndex)); } return result; }, /** * 宫格分类 */ getClassInfo: function (shopId) { let _this = this //加载分类列表 var params = { url: "/category/categoryInfo", method: "GET", data: { shopId: shopId, current:1, size:99999 }, callBack: function (res) { let categoryName = '' res.records.forEach(e => { categoryName = e.categoryName.split('>') e.categoryName = categoryName[0] }) let newRes = _this.splitList(res.records) let categoryList = newRes.splice(0,2) if(categoryList.length == 2){ categoryList = categoryList[0].concat(categoryList[1]) }else if(categoryList.length == 1){ categoryList = categoryList[0] } _this.setData({ categoryList: categoryList, categoryList1: newRes, }); } }; http.request(params); }, /** * 点击宫格 */ selectMenu: function (e) { console.log(e); let categoryId = e.currentTarget.dataset.itemid let index = e.currentTarget.dataset.index + this.data.currentTop let pic = e.currentTarget.dataset.pic let categories = e.currentTarget.dataset.categories if (categories == null || categories.length < 1) { wx.navigateTo({ url: `/pages/sub-category/sub-category?categoryId=${categoryId}&shopId=${this.data.shop_id}`, }) } else { getApp().globalData.categoryId = categoryId getApp().globalData.index = index getApp().globalData.pic = pic wx.switchTab({ url: '/pages/category/category' }) } }, // 领红包 toRedPackage: function () { wx.navigateTo({ url: '/pages/ledRedPackage/ledRedPackage', }) }, /** * banner图跳转 * @param {判断条件} e */ goToLevelPage: function (e) { let name = e.currentTarget.dataset.name if (name == 'new') { wx.navigateTo({ url: '/pages/prod-classify/prod-classify?sts=' + 1 }) } else if (name == 'favorable') { wx.navigateTo({ url: '/pages/specialDiscount/specialDiscount' }) } else if (name == 'groupBuy') { wx.navigateTo({ url: '/pages/aBulkList/aBulkList', }) } else { wx.navigateTo({ url: '/pages/snapUpList/snapUpList', }) } }, /** * 跳转到商品详情页 */ toProdPage: function (e) { var prodid = e.currentTarget.dataset.prodid; if (prodid) { wx.navigateTo({ url: '/pages/prod/prod?prodid=' + prodid, }) } }, toCouponCenter: function () { wx.navigateTo({ url: '/pages/couponCenter/couponCenter', }) }, newToProdPage: function (e) { let prodId = e.currentTarget.dataset.prod if (prodId) { wx.navigateTo({ url: '/pages/prod/prod?prodid=' + prodId, }) } }, /** * 跳转秒杀列表页 */ toSpecialDiscount: function () { wx.navigateTo({ url: '/pages/specialDiscount/specialDiscount', }) }, /** * 跳转到定位页面 */ toLocationPage: function () { wx.navigateTo({ url: '/pages/locationAdd/locationAdd', }) }, /** * 秒杀 */ getSnapUpList: function () { wx.showLoading() var params = { url: "/seckill/pageProd", method: "GET", data: { size: 4, lat: wx.getStorageSync('LATITUDE'), lon: wx.getStorageSync('LONGITUDE'), distance: wx.getStorageSync('DISTANCE') || 0 }, callBack: (res) => { wx.hideLoading(); let result = res.records.filter(item => util.dateToTimestamp(item.endTime) > new Date().getTime()) //过滤掉秒杀时间已结束的商品 let img = '' result.map(e => { img = e.pic.split(',') e.pic = img[0] }) this.setData({ snapUpList: result }); let closestItem = null; let minTimeDiff = Infinity; this.data.snapUpList.forEach((e) => { const endTime = util.dateToTimestamp(e.endTime); const now = new Date().getTime(); const timeDiff = endTime - now; // 获取距离时间最近的秒杀时间 if (timeDiff < minTimeDiff && timeDiff > 0) { minTimeDiff = timeDiff; closestItem = e; } }) if (closestItem) { const endTime = util.dateToTimestamp(closestItem.endTime); const interval = setInterval(() => { const now = new Date().getTime(); const timeDiff = endTime - now; if (timeDiff <= 0) { clearInterval(interval); return; } const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24)); const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000); this.setData({ days: days, hours: hours, minutes: minutes, seconds: seconds }); }, 1000); } } }; http.request(params); }, /** * 新品推荐 */ getNewList: function () { // var params = { // url: "/prod/lastedProdPage", // method: "GET", // data: { // current: 1, // size: 4, // lat: wx.getStorageSync('LATITUDE'), // lon: wx.getStorageSync('LONGITUDE'), // distance: wx.getStorageSync('DISTANCE') || 0, // shopId:this.data.shop_id // }, // callBack: (res) => { // let img = '' // res.records.map(e => { // img = e.pic.split(',') // e.pic = img[0] // }) // this.setData({ // newList: res.records, // }) // } // }; // http.request(params); }, /** * 获取距离最近店铺id * @param {*} e */ get_neighborShop: function () { console.log('get_neighborShop'); var params = { url: "/shop/neighborShop", method: "GET", data: { lat: wx.getStorageSync('LATITUDE'), lon: wx.getStorageSync('LONGITUDE'), }, callBack: (res) => { if(typeof res == 'number'){ this.getaddress_transports(res) this.setData({ shop_id: res }) setTimeout(() => { this.getClassInfo(res); }, 300) }else{ this.getaddress_transports(res.shopId) this.setData({ shop_id: res.shopId, shopName:res.shopName }) setTimeout(() => { this.getClassInfo(res.shopId); }, 300) } } }; http.request(params); }, /** * 获取最大配送范围 */ getaddress_transports: function (shopId) { let _this = this var params = { url: "/p/address/transport2", method: "GET", data: { shopId: shopId, latitude: wx.getStorageSync('LATITUDE'), longitude: wx.getStorageSync('LONGITUDE'), }, callBack: function (res) { wx.setStorageSync('DISTANCE', res.distance) _this.setData({ get_distance: res.distance }) }, errCallBack(res) { console.log(res); wx.setStorageSync('DISTANCE', 0) } }; http.request(params); }, onClose: function () { this.setData({ addCarshow: false }) }, /** * 步进器 */ minusButton: function (e) { let totalNum = this.data.totalNum if (totalNum > 0) { this.setData({ totalNum: totalNum - 1 }) } }, addButton: function (e) { let totalNum = this.data.totalNum this.setData({ totalNum: totalNum + 1 }) }, /** * 跳转秒杀列表页 */ toSnapUpPage: function () { wx.navigateTo({ url: '/pages/snapUpList/snapUpList', }) }, toSnapUpListPage: function (e) { var seckillId = e.currentTarget.dataset.seckillid; wx.navigateTo({ url: "/pages/snapUpDetail/snapUpDetail?seckillid=" + seckillId, }) }, /** * 团购 */ getAbulk: function () { wx.showLoading() var param = { url: "/groupProd/indexList", method: "GET", data: {}, callBack: (res) => { wx.hideLoading(); this.setData({ aBulkList: res }); } }; http.request(param); }, /** * 跳转团购列表页 */ toAbulkPage: function () { wx.navigateTo({ url: '/pages/aBulkList/aBulkList', }) }, toAbulkListPage: function (e) { var prodId = e.currentTarget.dataset.prodid; var groupActivityId = e.currentTarget.dataset.groupactivityid; wx.navigateTo({ url: '/pages/prod/prod?prodid=' + prodId + "&groupActivityId=" + groupActivityId }) }, // 跳转搜索页 toSearchPage: function () { wx.navigateTo({ url: '/pages/search-page/search-page', }) }, //跳转商品活动页面 toClassifyPage: function (e) { var url = '/pages/prod-classify/prod-classify?sts=' + e.currentTarget.dataset.sts; var id = e.currentTarget.dataset.id; var title = e.currentTarget.dataset.title; if (id) { url += "&tagid=" + id + "&title=" + title; } wx.navigateTo({ url: url }) }, toSecKillPage: function () { wx.navigateTo({ url: '/pages/snapUpList/snapUpList', }) }, //跳转公告列表页面 onNewsPage: function () { wx.navigateTo({ url: '/pages/recent-news/recent-news', }) }, onShow: function () { // this.get_test() this.setData({ select_address: wx.getStorageSync('ADDRESS') }) // this.getCurrentLocation() updateManager.onCheckForUpdate(function (res) { updateManager.onUpdateReady(function () { wx.showModal({ title: '更新提示', content: '新版本已经准备好,是否重启应用?', success(res) { if (res.confirm) { // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 updateManager.applyUpdate() } } }) }) }) http.getCartCount(); //重新计算购物车总数量 }, /** * 接口测试用 */ /** * 选择定位后更新列表 */ go_update() { this.get_neighborShop() setTimeout(() => { this.getNewList(); this.getSnapUpList(); this.getHotSalesProds() }, 1000) }, getAllData() { http.getCartCount(); //重新计算购物车总数量 this.getIndexImgs(); this.get_neighborShop() // this.getNoticeList(); this.getAbulk(); this.getRecommended() this.getRecommendeds() this.getAdv() setTimeout(() => { this.getNewList(); this.getSnapUpList(); this.getHotSalesProds(); }, 500) }, //加载轮播图 getIndexImgs() { console.log('getIndexImgs'); //加载轮播图 var params = { url: "/indexImgs/0", method: "GET", data: {}, callBack: (res) => { this.setData({ indexImgs: res, seq: res }); wx.hideLoading(); } }; http.request(params); }, // getNoticeList() { // // 加载公告 // var params = { // url: "/shop/notice/topNoticeList/0", // method: "GET", // data: {}, // callBack: (res) => { // this.setData({ // news: res, // }); // wx.hideLoading(); // } // }; // http.request(params); // }, /** * 加载热销商品列表 */ getHotSalesProds() { var param = { url: "/search/searchProdPage", method: "GET", data: { current: this.data.current, size: 10, sort: 3, orderBy: 1, lat: wx.getStorageSync('LATITUDE'), lon: wx.getStorageSync('LONGITUDE'), distance: wx.getStorageSync('DISTANCE') || 0, shopId: this.data.shop_id }, callBack: (res) => { var hotSalesList = [] let img = '' res.records.map(e => { img = e.pic.split(',') e.pic = img[0] }) if (this.data.current == 1) { setTimeout(() => { this.setData({ hotSalesList: res.records, pages: res.pages, current: res.current }); }, 500) } else { hotSalesList = this.data.hotSalesList hotSalesList.push(...res.records) this.setData({ hotSalesList }) if (res.records.length < 1) { this.setData({ isAll: true }) } } this.setData({ isHand:false }) } }; http.request(param); }, // 触底加载下一页 getNextPage() { console.log('getNextPage',this.data.current); if (this.data.pages > this.data.current) { this.setData({ current: this.data.current + 1 }) !this.data.isHand&&this.getHotSalesProds() } else { this.setData({ isAll: true }) } }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { this.getNextPage() }, onPullDownRefresh: function () { // wx.showNavigationBarLoading() //在标题栏中显示加载 //模拟加载 var ths = this; this.setData({ //下拉刷新 current: 1 }) setTimeout(function () { ths.getAllData(); // wx.hideNavigationBarLoading() //完成停止加载 wx.stopPullDownRefresh() //停止下拉刷新 }, 100); }, onShareAppMessage: function (e) { return { path: "pages/index/index" } } })