// nova-werun/pages/home/sport/sport-start/index.js const Parse = getApp().Parse; const company = getApp().globalData.company; Page({ /** * 页面的初始数据 */ data: { //屏幕高度 statusBarHeight: 0, // 状态栏高度 screenHeight: 0, // 屏幕高度 customHeight: 0, // 自定义导航栏高度(如小程序右上角胶囊按钮) bottomNavHeight: 0, // 底部导航栏高度 contentHeight: 0, // 可用内容高度 contentHeight2: 0, contentpadding: 0, //顶部padding高度 navheight: 0, //地图 longitude: 0, latitude: 0, markers: [], //是否暂停 isstop: false, //标题 title: '', percentage: '', timer: null, startTime: 0, show: false, // timer2: null, totalSeconds: 0, // 用于存储总秒数 formattedTime: '00:00:00', // 用于存储格式化后的时间 isRunning: false, // 计时器是否在运行 steps: 0, //运动步数 startsteps: 0, defferentstep: 0, distance: 0, calorie: 0, pace: 0, // activitdateid: '', }, /** * 生命周期函数--监听页面加载 */ onLoad: async function (options) { // 计算 const systemInfo = wx.getSystemInfoSync(); const statusBarHeight = systemInfo.statusBarHeight || 0; const screenHeight = systemInfo.screenHeight || 0; const custom = wx.getMenuButtonBoundingClientRect(); const customHeight = custom.height + 10 + 2 || 0; const bottomNavHeight = systemInfo.screenHeight - systemInfo.safeArea.bottom || 0; const navheight = (statusBarHeight + customHeight) * 750 / systemInfo.windowWidth; const contentHeight = (screenHeight - bottomNavHeight) * 750 / systemInfo.windowWidth; this.setData({ statusBarHeight, screenHeight, customHeight, bottomNavHeight, contentHeight, navheight, }); this.setData({ title: options.id }) // 获取初始步数 // 获取初始步数 this.getWeRunData2() console.log(this.data.startsteps); // 地图 await this.Getlocation(); //开启后台定位 this.startbackgroumd() //创建开始数据 this.startdate() }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { if (!this.data.isRunning && !this.data.isstop) { this.startTimer(); } }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { if (this.data.isRunning) { this.stopTimer(); } }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { this.stopTimer(); }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, //获取当前位置信息 Getlocation() { // 获取当前位置信息 wx.getLocation({ type: 'gcj02', success: (res) => { const { latitude, longitude } = res; console.log('获取到的经纬度:', latitude, longitude); // 添加日志 //调用api解析地址 wx.request({ url: 'https://api.map.baidu.com/reverse_geocoding/v3/?ak=sHZTomd7grslfP7sPKB8tRgT49FK9TEu&output=json&coordtype=gcj02&location=' + latitude + ',' + longitude, data: {}, header: { 'Content-Type': 'application/json' }, success: (ops) => { // 使用箭头函数 const address = ops.data.result.formatted_address; this.setData({ address: address, latitude: latitude, // 保证 latitude 被设置 longitude: longitude, // 保证 longitude 被设置 markers: [{ // 设置 markers id: 1, latitude: latitude, longitude: longitude, iconPath: 'https://file-cloud.fmode.cn/13WZ0W7u3l/20240724/7ebg0k104325941.png?imageView2/1/w/200/h/200', // 自定义标记图标 width: 40, height: 40, // callout: { // content: address, // 可以显示解析出的地址 // color: '#ffffff', // bgColor: '#7F56B2', // padding: 10, // borderRadius: 5, // display: 'ALWAYS' // } }] }); }, fail: function (resq) { wx.showModal({ title: '信息提示', content: '请求失败', showCancel: false, confirmColor: '#f37938' }); }, complete: function () {} }) }, fail: (err) => { console.error(err); wx.showToast({ title: '获取位置失败', icon: 'none' }); } }); }, stop() { this.setData({ isstop: !this.data.isstop }) if (this.data.isstop) { this.stopTimer() } else { this.startTimer() } console.log(this.data.isstop); }, //结束光环展示 startIncrease() { // 记录开始时间 this.setData({ startTime: Date.now(), }); // 清除之前的定时器 if (this.data.timer) { clearInterval(this.data.timer); } // 设置定时器,每隔 40 毫秒更新一次 percentage this.setData({ timer: setInterval(() => { const currentTime = Date.now(); const elapsedTime = currentTime - this.data.startTime; const percentage = Math.min((elapsedTime / 4000) * 100, 100); this.setData({ percentage: `conic-gradient(from 0deg, #015EEA ${percentage}%, white 0%)`, }); if (percentage >= 100) { wx.showToast({ title: '运动已结束', icon: 'success', duration: 500 }); this.enddate() //结束数据 this.endActivitydate() setTimeout(() => { this.onConfirm() }, 500) } // 如果达到 100%,清除定时器 if (percentage >= 100) { clearInterval(this.data.timer); this.setData({ timer: null, }); } }, 40), }); }, stopIncrease() { // 清除定时器 if (this.data.timer) { clearInterval(this.data.timer); this.setData({ timer: null, }); // 如果未达到 100%,清零 percentage const elapsedTime = Date.now() - this.data.startTime; if (elapsedTime < 4000) { this.setData({ percentage: '', }); } } }, //点击返回按钮 goback() { this.setData({ show: true, isstop: false, }) }, //取消弹窗 onClose() { this.setData({ show: false }); }, //确认返回 onConfirm() { wx.navigateBack({ delta: 1 // 返回的页面层数,1 表示返回上一页 }); this.stopBackgroundLocation()// 停止后台定位和位置监听 }, //开始计时或继续计时 startTimer: function () { if (this.data.isRunning) return; // 如果已经在运行,则不再启动 const that = this; this.data.timer2 = setInterval(function () { that.data.totalSeconds += 1; // 增加总秒数 that.setData({ formattedTime: that.formatTime(that.data.totalSeconds) // 更新格式化后的时间 }); // 每30秒调用一次getWeRunData if (that.data.totalSeconds % 30 === 0) { that.getWeRunData(); // 调用获取微信步数的函数 } that.onLocationChange((res) => { // 这里可以处理位置变化的逻辑 console.log('位置已更新:', res); }); that.progressdate() that.progressActivitydate() }, 1000); this.setData({ isRunning: true // 设置为运行状态 }); }, //暂停 stopTimer: function () { clearInterval(this.data.timer2); this.setData({ isRunning: false // 设置为未运行状态 }); wx.offLocationChange(); }, formatTime: function (seconds) { const hours = Math.floor(seconds / 3600); const minutes = Math.floor((seconds % 3600) / 60); const secs = seconds % 60; // 格式化为两位数 const formattedHours = String(hours).padStart(2, '0'); const formattedMinutes = String(minutes).padStart(2, '0'); const formattedSeconds = String(secs).padStart(2, '0'); return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`; }, //获取初始步数 async getWeRunData2() { wx.getWeRunData({ success: (res) => { // 获取到的加密数据 const encryptedData = res.encryptedData; const iv = res.iv; const userInfo = wx.getStorageSync('userInfo'); const session_key = userInfo.session_key // 这里需要调用你的后端接口进行解密 // 假设你有一个解密函数 decryptData this.decryptData(encryptedData, iv, session_key).then(async steps => { console.log('再次赋值'); await this.setData({ startsteps: steps, }); console.log('用户步数:', this.data.steps); }).catch(err => { console.error('解密失败:', err); }); }, fail: (err) => { console.error('获取运动数据失败:', err); } }); }, //获取微信步数 async getWeRunData() { wx.getWeRunData({ success: (res) => { // 获取到的加密数据 const encryptedData = res.encryptedData; const iv = res.iv; const userInfo = wx.getStorageSync('userInfo'); const session_key = userInfo.session_key // 这里需要调用你的后端接口进行解密 // 假设你有一个解密函数 decryptData this.decryptData(encryptedData, iv, session_key).then(async steps => { console.log('再次赋值'); await this.setData({ steps: steps, defferentstep: steps - this.data.startsteps }); console.log('用户步数:', this.data.steps); }).catch(err => { console.error('解密失败:', err); }); }, fail: (err) => { console.error('获取运动数据失败:', err); } }); }, // 解密 decryptData(encryptedData, iv, session_key) { return new Promise((resolve, reject) => { // 发送请求到后端进行解密 wx.request({ url: 'https://server.fmode.cn/api/wxapp/decrypt_phone', // 替换为你的后端解密接口 method: 'get', data: { encryptedData: encryptedData, iv: iv, appId: 'wxe6ecc0193c09696c', sessionKey: session_key }, success: (res) => { // if (res.data && res.data.steps) { // console.log(res.data.steps); // // resolve(res.data.steps); // 返回步数 // // const steps = 123456 // resolve(steps); // } else { // reject('解密返回数据格式错误'); // } if (res.data.data) { const stepInfoList = res.data.data.stepInfoList const todaylist = stepInfoList.filter(item => { console.log(this.isToday(item)); return this.isToday(item); // 使用 isToday 函数判断是否是今天 }); const steps = todaylist[0].step; resolve(steps); } else { reject('解密返回数据格式错误'); } }, fail: (err) => { reject(err); } }); }); }, // 判断日期是否是今天 isToday(item) { const today = new Date(); const date = new Date(item.timestamp * 1000); // 假设时间戳是以秒为单位 // 比较年、月、日 return date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate(); }, // 开启后台定位 startbackgroumd() { wx.startLocationUpdateBackground({ success: (res) => { // 开始监听GPS数据 this.onLocationChange((res) => { // 在这里处理位置变化的逻辑 console.log('位置已更新:', res); }); }, fail: (res) => { // 授权失败后引导用户打开定位信息 // 可以添加提示或引导用户操作的代码 } }); }, // 监听位置变化 onLocationChange(callback) { console.log('运行了'); // 监听位置变化 // this.Getlocation2() wx.onLocationChange((res) => { // 计算距离 let distance = this.haversineDistance(this.data.longitude, this.data.latitude, res.longitude, res.latitude); // 更新总距离 const totalDistance = parseFloat((Number(this.data.distance) + Number(distance)).toFixed(3)); // 计算卡路里 const calorie = this.getCalorie(60, totalDistance); // 假设体重为60kg const pace = parseFloat(Number((totalDistance / (this.data.totalSeconds / 3600)).toFixed(2))); // 配速(km/h) console.log('总距离', totalDistance, '段距离', distance, '总卡路里', calorie, '配速', pace); // 更新状态 this.setData({ pace, distance: totalDistance, calorie: calorie, latitude: res.latitude, longitude: res.longitude }); // 打印更新后的经纬度(可选) console.log('更新后的经纬度:', this.data.latitude, this.data.longitude); // 调用回调函数(如果有提供的话) if (callback) { callback(res); } }); }, //位置变化 Getlocation2() { // 获取当前位置信息 wx.getLocation({ type: 'gcj02', success: (res) => { const { latitude, longitude } = res; if (this.data.longitude == res.longitude && this.data.latitude == res.latitude) { console.log('位置没变'); } else { // 计算距离 let distance = this.haversineDistance(this.data.longitude, this.data.latitude, res.longitude, res.latitude); // 更新总距离 const totalDistance = parseFloat((Number(this.data.distance) + Number(distance)).toFixed(3)); // 计算卡路里 const calorie = this.getCalorie(60, totalDistance); // 假设体重为60kg const pace = parseFloat(Number((totalDistance / (this.data.totalSeconds / 3600)).toFixed(2))); // 配速(km/h) console.log('总距离', totalDistance, '段距离', distance, '总卡路里', calorie, '配速', pace); // 更新状态 this.setData({ pace, distance: totalDistance, calorie: calorie, latitude: res.latitude, longitude: res.longitude }); console.log('更新经纬度:', latitude, longitude); // 添加日志 } }, fail: (err) => { console.error(err); wx.showToast({ title: '获取位置失败', icon: 'none' }); } }); }, //计算两点距离 haversineDistance(longitude1, latitude1, longitude2, latitude2) { let lat1 = latitude1 let lon1 = longitude1 let lat2 = latitude2 let lon2 = longitude2 function toRad(degree) { return degree * Math.PI / 180; } const R = 6371e3; // 地球半径,单位为米 const φ1 = toRad(lat1); const φ2 = toRad(lat2); const Δφ = toRad(lat2 - lat1); const Δλ = toRad(lon2 - lon1); const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); const distance = (R * c) / 1000; // 距离,单位为公里 console.log('计算出距离', distance); return parseFloat(distance.toFixed(3)); }, //计算卡路里 getCalorie(weight, distance) { weight = weight || 60 // 国人平均体重 60kg const Calorie = weight * distance * 0.75 console.log('卡路里为', Calorie); return parseFloat(Calorie.toFixed(2)); // 保留两位小数并转换为数字 }, //创建开始数据 async startdate() { const currentUser = Parse.User.current(); let Userquery = new Parse.Query('_User'); Userquery.equalTo('company', company); Userquery.equalTo('objectId', currentUser.id); Userquery.notEqualTo('isDeleted', true) let user = await Userquery.first(); let companyPointer = Parse.Object.extend('Company').createWithoutData(company); let query = new Parse.Object('ActivityRunLog'); query.set('user', user.toPointer()) query.set('company', companyPointer) query.set('stage', 'start ') query.set('steps', 0) //步数 query.set('distance', 0) //距离 query.set('matchSpeed', 0) //配速 query.set('sportDate', 0) //运动时间 query.set('burnCalories', 0) //卡路里 try { let saveDate2 = await query.save(); console.log(saveDate2); const id = saveDate2.id await this.startActivitdate(id) console.log("新数据保存成功"); } catch (error) { console.error("保存数据时出现错误:", error); } }, //创建ActivityData数据 async startActivitdate(objectId) { const currentUser = Parse.User.current(); let Userquery = new Parse.Query('_User'); Userquery.equalTo('company', company); Userquery.equalTo('objectId', currentUser.id); Userquery.notEqualTo('isDeleted', true) let user = await Userquery.first(); let Activitdate = new Parse.Query('ActivityRunLog'); Activitdate.equalTo('objectId', objectId); Activitdate.notEqualTo('isDeleted', true) let Activit = await Activitdate.first(); let companyPointer = Parse.Object.extend('Company').createWithoutData(company); let query = new Parse.Object('ActivityData'); query.set('user', user.toPointer()) query.set('company', companyPointer) query.set('runlog', Activit.toPointer()) try { let saveDate2 = await query.save(); this.setData({ activitdateid: saveDate2.id }) console.log("ActivityData数据", this.data.activitdate); } catch (error) { console.error("保存数据时出现错误:", error); } }, //创建过程数据 async progressdate() { if (this.data.totalSeconds % 4 != 0) { return } const currentUser = Parse.User.current(); let Userquery = new Parse.Query('_User'); Userquery.equalTo('company', company); Userquery.equalTo('objectId', currentUser.id); Userquery.notEqualTo('isDeleted', true) let user = await Userquery.first(); let companyPointer = Parse.Object.extend('Company').createWithoutData(company); let query = new Parse.Object('ActivityRunLog'); query.set('user', user.toPointer()) query.set('company', companyPointer) query.set('stage', 'progress ') query.set('steps', this.data.defferentstep) //步数 query.set('distance', this.data.distance) //距离 query.set('matchSpeed', this.data.pace) //配速 query.set('sportDate', this.data.totalSeconds) //运动时间 query.set('burnCalories', this.data.calorie) //卡路里 try { console.log('上传成功', this.data.defferentstep, this.data.distance, this.data.pace, this.data.totalSeconds, this.data.calorie); let saveDate2 = await query.save(); console.log("新数据保存成功"); } catch (error) { console.error("保存数据时出现错误:", error); } }, //上传ActivityData过程数据 async progressActivitydate() { if (this.data.totalSeconds % 4 != 0) { return } let query = new Parse.Query('ActivityData'); query.equalTo('objectId', this.data.activitdateid); query.notEqualTo('isDeleted', true) let Activit = await query.first(); console.log('Activit',Activit); if (Activit) { Activit.set('steps', this.data.defferentstep) //步数 Activit.set('distance', this.data.distance) //距离 Activit.set('matchSpeed', this.data.pace) //配速 Activit.set('sportDate', this.data.totalSeconds) //运动时间 Activit.set('burnCalories', this.data.calorie) //卡路里 try { let saveDate2 = await Activit.save(); console.log("ActivityData过程数据数据"); } catch (error) { console.error("保存数据时出现错误:", error); } } }, //创建结束数据 async enddate() { const currentUser = Parse.User.current(); let Userquery = new Parse.Query('_User'); Userquery.equalTo('company', company); Userquery.equalTo('objectId', currentUser.id); Userquery.notEqualTo('isDeleted', true) let user = await Userquery.first(); let companyPointer = Parse.Object.extend('Company').createWithoutData(company); let query = new Parse.Object('ActivityRunLog'); query.set('user', user.toPointer()) query.set('company', companyPointer) query.set('stage', 'end ') query.set('steps', this.data.defferentstep) //步数 query.set('distance', this.data.distance) //距离 query.set('matchSpeed', this.data.pace) //配速 query.set('sportDate', this.data.totalSeconds) //运动时间 query.set('burnCalories', this.data.calorie) //卡路里 try { console.log('上传成功', this.data.defferentstep, this.data.distance, this.data.pace, this.data.totalSeconds, this.data.calorie); let saveDate2 = await query.save(); console.log("新数据保存成功"); } catch (error) { console.error("保存数据时出现错误:", error); } }, //上传ActivityData结束数据 async endActivitydate() { let query = new Parse.Query('ActivityData'); query.equalTo('objectId', this.data.activitdateid); query.notEqualTo('isDeleted', true) let Activit = await query.first(); if (Activit) { Activit.set('steps', this.data.defferentstep) //步数 Activit.set('distance', this.data.distance) //距离 Activit.set('matchSpeed', this.data.pace) //配速 Activit.set('sportDate', this.data.totalSeconds) //运动时间 Activit.set('burnCalories', this.data.calorie) //卡路里 try { let saveDate2 = await Activit.save(); console.log("ActivityData结束数据数据"); } catch (error) { console.error("保存数据时出现错误:", error); } } }, // 停止后台定位和位置监听 stopBackgroundLocation() { wx.stopLocationUpdate({ success: (res) => { console.log('后台定位已停止'); }, fail: (res) => { console.error('停止后台定位失败', res); } }); wx.offLocationChange(); // 停止监听位置变化 }, })