// let app = null; let app = getApp(); // const websiteUrl = 'https://app.gter.net'; const websiteUrl = "https://offer.gter.net"; const time = (date) => { const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); return `${[year, month, day]}`; }; const formatTime = (date) => { const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); const hour = date.getHours(); const minute = date.getMinutes(); const second = date.getSeconds(); return `${[year, month, day].map(formatNumber).join("-")} ${[hour, minute].map(formatNumber).join(":")}`; }; const formatNumber = (n) => { n = n.toString(); return n[1] ? n : `0${n}`; }; function setapp(o) { app = o; } function getUserProfile(e) { let that = this; return new Promise((resolve, reject) => { if (app.globalData.canIUseGetUserProfile) { wx.getUserProfile({ desc: "用于完善会员资料", // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写 success: (res) => { app.globalData.getUserInfoData = res; // let {userInfo} = res; // app.sendUserinfo(res).then(res => { // resolve() // }) }, fail(res) { console.log("faiil", res); } }); } else { // console.log('getUserInfo', e); if (e.detail.errMsg == "getUserInfo:ok") { // app.sendUserinfo(e.detail).then(res => { // resolve() // }) } } }); reject(); } // 验证 Authorization 存不存再 ,如不存在创建一个 const haveAuthorization = () => { let Authorization = wx.getStorageSync("Authorization"); if (!Authorization) { const app = getApp(); Authorization = app.randomString(32); wx.setStorageSync("Authorization", Authorization); wx.setStorageSync("session", Authorization); } }; const wxpost = function (url, data = {}, ishint = true) { haveAuthorization(); return new Promise((resolve, reject) => { if (url.indexOf("http") != 0) url = websiteUrl + url; const Authorization = wx.getStorageSync("Authorization"); let send_data = Object.assign({}, getApp().globalData.options, { session: wx.getStorageSync("session") }, data ); wx.request({ url, method: "POST", data: send_data, timeout: data.timeout || 60000, header: { "content-type": "application/json;charset=utf-8", Authorization, envVersion: getApp().globalData["envVersion"] }, success: (res) => { if (res.data.code == 200) { resolve(res.data); } else if (res.data.code == 401) { // 需要授权 getApp().globalData.user.uid = 0; wx.showModal({ title: "提示", content: res.data.message }); reject(res.data); } else { if (ishint) { wx.showModal({ title: "提示", content: res.data.message, complete: function (res) { if (url == "/peer/topical/subjectDetails") { wx.navigateBack({ delta: 1 }); } } }); } reject(res.data); } }, fail(res) { requestFail(res); reject(res); } }); }); }; const wxget = function (url, data = {}) { if (url.indexOf("http") != 0) url = websiteUrl + url; haveAuthorization(); return new Promise((resolve, reject) => { var Authorization = wx.getStorageSync("Authorization"); wx.request({ url, method: "GET", data: data, header: { Authorization, envVersion: getApp().globalData["envVersion"] }, success: (res) => { if (res.data.code == 200) { resolve(res.data); } else if (res.data.code == 401) { // 需要授权 // console.log(app) // app.globalData.user.uid = 0; wx.showToast({ icon: "none", title: res.data.message }); reject(res); } else { wx.hideLoading(); wx.showModal({ title: "提示", content: res.data.message }); reject(res.data); } }, fail(res) { wx.showModal({ title: "提示", content: res }); reject(res); } }); }); }; // 处理请求网络错误 const requestFail = (res) => { if (res.errMsg.indexOf("time out") > -1 || res.errMsg.indexOf("timeout") > -1) { wx.showToast({ title: "请求超时,请检查您的网络", icon: "none" }); } else if (res.errMsg.indexOf("connect error") > -1) { wx.showToast({ title: "当前网络不佳,请稍后重试", icon: "none" }); } else { wx.showToast({ title: "加载数据失败,请稍后尝试", icon: "none" }); } }; // 字符串转base64 function base64_encode(str) { var c1, c2, c3; var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var i = 0, len = str.length, string = ""; while (i < len) { c1 = str.charCodeAt(i++) & 0xff; if (i == len) { string += base64EncodeChars.charAt(c1 >> 2); string += base64EncodeChars.charAt((c1 & 0x3) << 4); string += "=="; break; } c2 = str.charCodeAt(i++); if (i == len) { string += base64EncodeChars.charAt(c1 >> 2); string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xf0) >> 4)); string += base64EncodeChars.charAt((c2 & 0xf) << 2); string += "="; break; } c3 = str.charCodeAt(i++); string += base64EncodeChars.charAt(c1 >> 2); string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xf0) >> 4)); string += base64EncodeChars.charAt(((c2 & 0xf) << 2) | ((c3 & 0xc0) >> 6)); string += base64EncodeChars.charAt(c3 & 0x3f); } return string; } // 数值每三位加逗号 function formatNumberComma(num) { return num.toString().replace(/\d+/, function (n) { return n.replace(/(\d)(?=(?:\d{3})+$)/g, "$1,"); }); } // 公共的复制api 注意 value 一定要字符串 hintText 为提示文本 空时默认提示 function copy(value, hintText) { wx.setClipboardData({ data: value, success(res) { if (!hintText) return; wx.showToast({ icon: "none", title: hintText }); }, }); } // 清除前后空格 function trim(str) { return str.trim(); } // 回退并判断返回首页 function rollback() { wx.navigateBack({ delta: 1, fail: function () { wx.navigateTo({ url: "/pages/newIndex/index" }); } }); } //dateTimeStamp是一个时间毫秒,注意时间戳是秒的形式,在这个毫秒的基础上除以1000,就是十位数的时间戳。13位数的都是时间毫秒。 function timeago(dateTimeStamp, type = 1) { if (!dateTimeStamp) return "刚刚"; // 判断位数 if (dateTimeStamp.toString().length !== 13) dateTimeStamp = dateTimeStamp * 1000; var minute = 1000 * 60; //把分,时,天,周,半个月,一个月用毫秒表示 var hour = minute * 60; var day = hour * 24; var now = new Date().getTime(); //获取当前时间毫秒 var diffValue = now - dateTimeStamp; //时间差 if (diffValue < 0) return "刚刚"; var minC = diffValue / minute; //计算时间差的分,时,天,周,月 var hourC = diffValue / hour; var dayC = diffValue / day; let result = ""; if (dayC >= 7) { var datetime = new Date(dateTimeStamp); var Nyear = datetime.getFullYear(); var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1; var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate(); var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours(); var Nmin = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes(); if (type == 1) result = Nyear + "-" + Nmonth + "-" + Ndate; if (type == 2) { result = `${Nmonth}月${Ndate}日 ${Nhour}:${Nmin}`; if (new Date().getFullYear() !== Nyear) result = `${Nyear}年${result}`; } } else if (dayC >= 1) result = parseInt(dayC) + "天前"; else if (hourC >= 1 && hourC <= 24) result = parseInt(hourC) + "小时前"; else if (minC >= 1 && minC <= 60) result = parseInt(minC) + "分钟前"; else result = "刚刚"; return result; } // type 1 是超过七天后 返回年月日 2 是返回月日时间 3 返回几年前 几个月前 function strtimeago(dateStr, type = 1) { dateStr = dateStr + ""; // 反之传入的不是字符串 dateStr = dateStr.replaceAll("-", "/"); // 修改格式 var minute = 1000 * 60; //把分,时,天,周,半个月,一个月用毫秒表示 var hour = minute * 60; var day = hour * 24; var now = new Date().getTime(); //获取当前时间毫秒 let objectTime = new Date(dateStr).getTime(); var diffValue = now - objectTime; //时间差 if (diffValue < 0) return "刚刚"; var minC = diffValue / minute; //计算时间差的分,时,天,周,月 var hourC = diffValue / hour; var dayC = diffValue / day; const diffInMilliseconds = now - objectTime; const diffInYears = diffInMilliseconds / (1000 * 60 * 60 * 24 * 365); const diffInMonths = diffInYears * 12; let result = ""; if (dayC >= 7) { var datetime = new Date(dateStr); var Nyear = datetime.getFullYear(); var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1; var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate(); var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours(); var Nmin = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes(); if (type == 1) result = Nyear + "-" + Nmonth + "-" + Ndate; if (type == 2) { result = `${Nmonth}月${Ndate}日 ${Nhour}:${Nmin}`; if (new Date().getFullYear() !== Nyear) result = `${Nyear}年${result}`; } if (type == 3) { if (diffInYears >= 1) result = Math.floor(diffInYears) + "年前" else if (diffInMonths >= 1) result = Math.floor(diffInMonths) + "个月前" } } else if (dayC >= 1) result = parseInt(dayC) + "天前"; else if (hourC >= 1 && hourC <= 24) result = parseInt(hourC) + "小时前"; else if (minC >= 1 && minC <= 60) result = parseInt(minC) + "分钟前"; else result = "刚刚"; return result; } function changeTime(date) { return [date.getFullYear(), date.getMonth() + 1, date.getDate()] .map(function (item) { return item > 9 ? item : "0" + item; }) .join("-"); } function changeTimeago(date) { let now = new Date(); var days = Math.ceil((date.getTime() - now.getTime()) / (24 * 60 * 60 * 1000)) + " 天"; if (days == 0) days = Math.ceil(((date.getTime() - now.getTime()) / (60 * 60 * 1000)) % 24) + " 小时"; return days; } // 传入字符串时间 转为 其他时间格式的 xxxx年xx月xx日 时:分 // 1. xxxx年xx月xx日 时:分 // 2. xxxx-xx-xx 时:分 // 3. xxxx年xx月xx日 时:分 同年不显示年 function timeformat(time, type = 1) { time = time.replaceAll("-", "/"); // 修改格式 let result = ""; var datetime = new Date(time); var Nyear = datetime.getFullYear(); var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1; var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate(); var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours(); var Nmin = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes(); if (type == 1) result = `${Nyear}年${Nmonth}月${Ndate}日 ${Nhour}:${Nmin}`; else if (type == 2) result = `${Nyear}-${Nmonth}-${Ndate} ${Nhour}:${Nmin}`; else if (type == 3) { result = `${Nmonth}月${Ndate}日 ${Nhour}:${Nmin}`; if (new Date().getFullYear() != Nyear) result = `${Nyear}年` + result; } else if (type == 4) result = `${Nyear}-${Nmonth}-${Ndate} ${Nhour}:${Nmin}`; return result; } // 公共的统计代码 function statistical(data) { return new Promise((resolve, reject) => { wxpost("/miniprogramApi/offer/stat", data).then((res) => resolve(res)); }); } // rpx转px function rpxTopx(value) { let deviceWidth = wx.getWindowInfo().windowWidth let px = Math.floor((deviceWidth / 750) * value); return px; } // px转rpx function pxToRpx(value) { let deviceWidth = wx.getSystemInfoSync().windowWidth; // 获取设备屏幕宽度 let rpx = Math.floor((750 / deviceWidth) * value); return rpx; } function changeNum(num) { return num > 9 ? num : "0" + num; } // 获取当前时间 格式xxxx-xx-xx function getCurrentDate() { const now = new Date(); const year = now.getFullYear(); const month = (now.getMonth() + 1).toString().padStart(2, "0"); // 月份从0开始,需要加1,并确保两位数 const day = now.getDate().toString().padStart(2, "0"); // 确保两位数 return `${year}-${month}-${day}`; } function getTitleName(url) { const obj = { "pages/newIndex/index": "首页", "pages/more_offer/index/index": "首页-旧", "pages/mj/mj_details/index": "面经详情-旧", "pages/vote/voteDetails/voteDetails": "投票详情-旧", "pages/report/report": "举报", "pages/index/comment/index": "填写页面", "pages/accredit/accredit": "欢迎回来", "pages/victoryDetails/victoryDetails": "Offer详情", "pages/summaryDetails/summaryDetails": "总结详情", "pages/setAvatarNickname/setAvatarNickname": "设置头像昵称", "pages/signIn/signIn": "签到", "pages/personalHomepage/personalHomepage": "个人主页", "pages/privateLetter/privateLetter": "私信", "pages/victoryList/victoryList": "Offer列表", "pages/summaryList/summaryList": "总结列表", "pages/admissionList/admissionList": "招生官列表", "pages/mjList/mjList": "面经列表", "pages/mjDetails/mjDetails": "面经详情", "pagesSquare/pages/mjIssue/mjIssue": "发布面经", "pages/voteList/voteList": "投票列表", "pages/voteDetails/voteDetails": "投票详情", "pagesSquare/pages/voteCcreate/voteCcreate": "发布投票", "pages/questionsList/questionsList": "问答列表", "pages/questionsDetails/questionsDetails": "问答详情", "pagesSquare/pages/publishBeforeLeaving/publishBeforeLeaving": "发布问答", "pagesSquare/pages/quizAnswer/quizAnswer": "回答提问", "pages/search/search": "搜索", "pages/user/user": "我的", "pages/webview/webview": "H5", "pages/summaryPost/summaryPost": "报总结", "pages/projectLibrary/projectLibrary": "港校项目库", "pages/projectSchoolHomepage/projectSchoolHomepage": "院校详情", "pages/projectSubjectList/projectSubjectList": "按学科排列", "pages/projectComparison/projectComparison": "项目对比", "pages/projectList/projectList": "榜单", "pages/projectMy/projectMy": "我的项目", "pages/projectDetails/projectDetails": "项目详情", "pages/treeList/treeList": "笔记列表", "pages/treeDetails/treeDetails": "笔记详情", "pages/treeIssue/treeIssue": "笔记发布", "pages/topicSearch/topicSearch": "笔记话题", "pagesSquare/pages/draft/draft": "草稿箱", "pagesLoginRequired/pages/my/myCollect/myCollect": "我的收藏", "pagesLoginRequired/pages/my/myLike/myLike": "我的回应", "pagesLoginRequired/pages/my/myDiscussion/myDiscussion": "我的讨论", "pagesLoginRequired/pages/my/myCreation/myCreation": "我的创作", "pagesLoginRequired/pages/wechatReminder/wechatReminder": "微信提醒", "pagesLoginRequired/pages/postOffer/postOffer": "报Offer", "pagesLoginRequired/pages/inform/inform": "通知", "pagesLoginRequired/pages/messageCenter/messageCenter": "消息中心", "pagesLoginRequired/pages/interact/interact": "互动", "pagesLoginRequired/pages/footprint/footprint": "足迹", "pages/findList/findList": "找飞友列表", "pagesSquare/pages/lookingforfeiyou/lookingforfeiyou": "找飞友详情", "pagesSquare/pages/publish/publish": "发布找飞友", "pagesSquare/pages/selectcity/selectcity": "找飞友选择城市", "pagesSquare/pages/selectschool/selectschool": "找飞友选择院校", "pagesSquare/pages/PCAuthorization/PCAuthorization": "PC扫码登录", }; return obj[url]; } // 调用 统计接口 function statistics(obj) { let url = "" let options = {} let pages = null if (obj.path) { url = obj.path options = obj.query || {} } else { pages = getCurrentPages(); // 获取当前页面栈 const currentPage = pages[pages.length - 1]; // 当前页面对象 url = currentPage?.route || 'pages/newIndex/index' // console.log("url", url); if (currentPage) options = currentPage.options } // 当页面显示时执行 // const pages = getCurrentPages(); // 获取当前页面栈 // console.log(pages); // const currentPage = pages[pages.length - 1]; // 当前页面对象 // console.log("currentPage", currentPage); // if (obj.path) url = obj.path // else url = currentPage.route // // const url = currentPage.route; // 当前页面url // if (obj.query) options = obj.query // else options = currentPage.options // const options = currentPage.options; // 当前页面url的参数 const launchOptions = wx.getLaunchOptionsSync() || {}; // 构建带参数的URL let urlWithArgs = url + objectToQueryString(options); // 缓存 systemInfo let systemInfo = wx.getStorageSync("xstatSystemInfo"); if (!systemInfo) { const accountInfo = wx.getAccountInfoSync(); const deviceInfo = wx.getDeviceInfo(); const windowInfo = wx.getWindowInfo(); const base = wx.getAppBaseInfo(); systemInfo = { website: accountInfo.miniProgram.appId || 'wxa9296b07391c2bc7', hostname: accountInfo.miniProgram.appId || 'wxa9296b07391c2bc7', screen: `${windowInfo.windowWidth}x${windowInfo.windowHeight}`, language: base.language || '', os: deviceInfo.system || '', platform: deviceInfo.platform || '', device: deviceInfo.model || '', session: wx.getStorageSync("xstatSession") || '', scene: launchOptions.scene || '', }; wx.setStorageSync("xstatSystemInfo", systemInfo); } let payload = { title: getTitleName(url), url: "/" + urlWithArgs, }; if (Object.keys(launchOptions.referrerInfo).length > 0) payload.referrer = launchOptions.referrerInfo.appId + objectToQueryString(launchOptions.referrerInfo.extraData); if (obj.name) payload.name = obj.name; if (obj.data && Object.keys(obj.data).length > 0) payload.data = obj.data; try { wx.request({ url: 'https://stat.gter.net/api/send', method: "POST", data: { payload, type: obj.type || 'event', }, timeout: 5000, header: { 'Content-Type': 'application/json', 'x-stat-token': base64_encode(JSON.stringify(systemInfo)), }, success: (res) => { if (res.data.code == 200 && res.data.data && res.data.data.session && res.data.data.session != systemInfo.session) { wx.setStorageSync("xstatSession", res.data.data.session); wx.setStorageSync("xstatSystemInfo", { ...systemInfo, session: res.data.data.session }); } }, }); } catch (error) { console.error('发送失败:', error); } } // 判断是否登录 如果登录需要发送 绑定微信信息埋点 function bindingUser(user = {}) { return if (user.uid <= 0) return; setTimeout(() => { statistics({ data: { uid: user.uid, uin: user.uin }, type: "identify" }); }, 600); } // 将一个JavaScript对象转换为路由参数的形式将键值对转换为key=value的形式 function objectToQueryString(obj = {}) { const queryString = Object.keys(obj).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])).join('&'); return queryString ? '?' + queryString : ''; } module.exports = { formatTime, getUserProfile, wxpost, wxget, setapp, websiteUrl, time, base64_encode, formatNumberComma, copy, trim, rollback, timeago, statistical, strtimeago, rpxTopx, changeTime, changeTimeago, changeNum, timeformat, getCurrentDate, statistics, bindingUser, objectToQueryString, pxToRpx, };