738 lines
24 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var initial_url = 'https://app.gter.net/tenement';
var app = null;
function initial(self) {
app = self;
getUserInfo(function (code) {
sendData(code)
self.globalData.code = code;
});
return true;
}
function sendData(code) {
let Authorization = wx.getStorageSync('Authorization')
if (!Authorization) {
Authorization = app.randomString(32)
wx.setStorageSync('Authorization', Authorization)
wx.setStorageSync('session', Authorization)
}
wx.request({
url: initial_url,
data: {
session: wx.getStorageSync('Authorization') || "",
Authorization: wx.getStorageSync('Authorization') || "",
code: code,
options: app.globalData.options || '',
},
method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: {
'content-type': 'application/json',
'Accept': 'application/json, text/plain',
'Cookie': 'miucms_session=' + wx.getStorageSync('Authorization'),
'Authorization': wx.getStorageSync('Authorization') || ''
},
success: function (res) {
var data = typeof res.data == 'string' ? JSON.parse(res.data) : res.data;
bindingUser(data.user || {})
// 将配置与用户session存于本地
// if (!data.session) {
// // 这里报错.用户授权不成功
// return false;
// }
// wx.setStorageSync('session', data.user.session)
app.globalData.session = data.user.session;
// wx.setStorageSync('Authorization', data.user.session)
app.globalData.Authorization = data.user.session;
app.globalData.isUserAuthorization = data.user.session && data.user.session.length > 0 ? 2 : 1;
app.globalData.expiration_day = data.expiration_day;
app.globalData.config = data.config;
app.globalData.notice = data.notice;
app.globalData.title = data.title;
app.globalData.initialState = true;
app.globalData.user = data.user;
app.globalData.status = data.status;
app.globalData.StudentapartmentNew = data.StudentapartmentNew;
app.globalData.listTab = data.listTab;
app.globalData.wechat = data.wechat;
app.globalData.isMapFindState = data.isMapFindState;
app.globalData.isShowVideo = data.reviewmode == 1 ? false : true;
// app.globalData.isShowVideo = false
// console.log(data.popwindow);
app.globalData.popwindow = data.popwindow;
app.globalData.header = {
'content-type': 'application/json',
'Accept': 'application/json, text/plain',
'Cookie': 'miucms_session=' + wx.getStorageSync('Authorization'),
'Authorization': wx.getStorageSync('Authorization') || ''
};
// count()
app.globalData.offerkaipingadvertisement = data.popup || {}
const openAdTimer = wx.getStorageSync("openAdTimer")
if (openAdTimer && isToday(openAdTimer)) app.globalData.offerkaipingadvertisementState = true
},
fail: function () {
// fail
},
complete: function () {
// complete
useSocket()
}
})
}
function isToday(timestamp) {
const date = new Date(timestamp)
const today = new Date()
return date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate()
}
// 发送未读消息数请求
function count() {
return new Promise((resolve, reject) => {
request(app.globalData.baseURL + "/tenement/message/count").then(res => {
if (res.code == 200) {
app.globalData['unreadMessages'] = res.data.count
app.globalData['unreadMessagesState'] = true
} else {
wx.showModal({
title: '提示',
content: res.message
})
}
resolve(res)
}).catch(error => {
reject(error)
})
})
}
// 发送验证码
function verify() {
// 得到 uniqid 和过期时间
}
// 验证验证码并注册
function register(o) {
var config = wx.getStorageSync('config')
var self = this;
wx.request({
url: config.user.register,
data: {
session: wx.getStorageSync('session'),
data: wx.getStorageSync('rawData'),
uniqid: null, //上一步获取的ID
code: null, //接收到的验证码
},
method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: {
'content-type': 'application/json',
'Accept': 'application/json, text/plain'
},
success: function (res) {
var data = typeof res.data == 'string' ? JSON.parse(res.data) : res.data;
console.log('登录/注册成功')
initial(initial_url, app)
},
fail: function () {
// fail
},
complete: function () {
// complete
}
})
}
//用户登录
function login() {
return new Promise((resolve, reject) => wx.login({
success: resolve,
fail: reject
}))
}
//获取用户信息
function getUserInfo(o) {
login().then(res => {
var code = res.code;
o(code);
}).catch(res => {
console.log(res)
})
}
function share(app, name) {
if (!app.globalData.config.stat || !app.globalData.config.stat.share) {
return false
}
wx.request({
url: app.globalData.config.stat.share,
data: {
page: name
},
method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: app.globalData.header,
success: function (res) {},
fail: function (res) {},
})
}
function html2wxml(str, index, that) {
var arr = [];
if (str.indexOf('</a>') != -1) {
// 有a标签
that.data.newFunction.text[index].push({
text: str.substring(0, str.indexOf('<a')),
node: 'text'
})
var rest = str.substring(str.indexOf('<a'));
// a标签后面剩下的字符串
// 第一个出现href的位置
var href1 = rest.indexOf('href="') + 6;
// 第二个“出现的位置
var href2 = (rest.substring(href1)).indexOf('"')
// 链接地址
var href = rest.substring(href1, href1 + href2)
rest = rest.substring(rest.indexOf('>'));
var text1 = rest.substring(1, rest.indexOf('</a>'))
that.data.newFunction.text[index].push({
text: text1,
node: 'a',
href: href
})
rest = rest.substring(rest.indexOf('</a>') + 4)
if (rest.length > 0) {
// a标签后还有字符串
if (rest.indexOf('</a>') != -1) {
// 还有A标签存在再一次调用
that.html2wxml(rest, index)
} else {
that.data.newFunction.text[index].push({
text: rest,
node: 'text',
})
}
}
} else {
that.data.newFunction.text[index] = [{
text: str,
node: 'text',
}]
}
}
function change_data(that, newFunction) {
var arr = newFunction.split('\n');
var arr2 = [];
for (var i = 0; i < arr.length; i++) {
var str = arr[i];
that.data.newFunction.text[i] = [];
that.html2wxml(str, i)
}
that.setData({
newFunction: that.data.newFunction
})
}
function copy(content, hintText) {
return new Promise((resolve, reject) => {
wx.setClipboardData({
data: content,
success: function (res) {
wx.showToast({
icon: "none",
title: hintText || '复制成功!',
})
resolve()
},
fail(err) {
reject(err)
}
})
})
}
//封装Request请求方法
function request(url, data = {}, ishint = true) {
return new Promise((resolve, reject) => {
// if (!app.globalData.config || !app.globalData.config.list) {
// reject()
// return false
// }
let Authorization = wx.getStorageSync('Authorization')
if (!Authorization) {
Authorization = app.randomString(32)
wx.setStorageSync('Authorization', Authorization)
wx.setStorageSync('session', Authorization)
}
let sendData = Object.assign({
session: wx.getStorageSync('session'),
}, app.globalData.options, data)
wx.request({
url: url,
data: sendData,
timeout: data.timeout || 60000,
header: {
'content-type': 'application/json',
'Accept': 'application/json, text/plain',
'Cookie': 'miucms_session=' + Authorization,
'Authorization': Authorization || ''
},
method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
success: function (res) {
var json = res.data;
if (typeof json != 'object') {
if (json != null) {
json = json.replace("\ufeff", "");
try {
var jj = JSON.parse(json);
res.data = jj;
} catch (error) {
if (ishint) {
wx.showModal({
title: '提示',
content: '请求失败'
})
}
}
}
}
var data = res.data;
resolve(data)
},
fail: function (msg) {
wx.hideLoading();
if (ishint) {
wx.showToast({
title: msg,
icon: 'none',
duration: 2000,
mask: true
})
}
reject('fail')
}
})
})
}
const wxget = function (url, data = {}) {
data = Object.assign({}, app.globalData.options, data)
return new Promise((resolve, reject) => {
var authorization = wx.getStorageSync('Authorization');
if (!authorization) {
authorization = app.randomString(32)
wx.setStorageSync('Authorization', authorization)
wx.setStorageSync('session', authorization)
}
wx.request({
url: url,
data: data,
header: {
'Cookie': 'miucms_session=' + authorization,
Authorization: authorization
},
method: 'GET',
success: (res) => {
if (res.data.code == 200) {
resolve(res.data)
} else if (res.data.code == 401) {
// 需要授权
app.globalData.user.uid = 0;
wx.showToast({
icon: 'none',
title: res.data.message
})
reject(res)
} else {
wx.hideLoading()
wx.showModal({
title: '提示',
content: res.message || res.data.message,
})
reject(res.data)
}
},
fail(res) {
wx.showModal({
title: '提示',
content: res,
})
reject(res)
}
});
})
}
function closeAD(id) {
if (!app.globalData.config || !app.globalData.config.adv) return false
request(app.globalData.config.adv.close, {
advid: id
}).then(res => {})
}
function clickAD(id) {
if (!app.globalData.config || !app.globalData.config.adv) {
return false
}
request(app.globalData.config.adv.click, {
advid: id
}).then(res => {})
}
function getTopTitle(that, app) {
let topTitle = app.globalData.topTitle
if (topTitle) {
that.setData({
topTitle: app.globalData.topTitle,
miniProgram: app.globalData.miniProgram,
})
} else {
setTimeout(() => {
that.getTopTitle()
}, 300)
}
}
function getTimeAgo(Time) {
const now = new Date();
let time = new Date(Time)
const diff = now - time;
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (seconds < 60) return `${seconds}秒前`;
else if (minutes < 60) return `${minutes}分钟前`;
else if (hours < 24) return `${hours}小时前`;
else if (days < 7) return `${days}天前`;
else return Time;
}
// 开启socket
let socketCount = 0 // 链接次数,判断失败
const useSocket = () => {
if (app.globalData.isConnected) {
console.log("已经连接,不再重复连接")
return // 如果已经连接,则不再创建新的 socketTask
}
app.globalData.socketTask = wx.connectSocket({
url: `wss://socket.gter.net/socket?token=${wx.getStorageSync('Authorization') || ''}`,
success: function (res) {
app.globalData.isConnected = true // 连接成功,设置为 true
},
fail: function (err) {
app.globalData.isConnected = false // 连接成功,设置为 true
console.log(err, "err");
}
})
app.globalData.socketTask.onOpen(function () {
// 初始化发消息
if (wx.getStorageSync('Authorization')) {
let getAccountInfoSync = wx.getAccountInfoSync();
let dataToSend = {
type: 'bind',
data: {
token: wx.getStorageSync('Authorization') || '',
app: getAccountInfoSync.miniProgram.appId
// uid: user.uid || 0
}
}
app.globalData.socketTask.send({
data: JSON.stringify(dataToSend),
})
}
// 开始定时发
setTimeout(() => timedTransmission(), 50000)
})
app.globalData.socketTask.onClose(function () {
// console.log('socket关闭了', new Date())
socketCount++
if (socketCount > 3) return
setTimeout(() => useSocket(), 3000);
app.globalData.isConnected = false // 连接关闭,重置为 false
})
}
// 定时发送
const timedTransmission = () => {
if (app.globalData.socketTask.readyState != 1) return
var dataToSend = {
type: 'ping'
}
app.globalData.socketTask.send({
data: JSON.stringify(dataToSend),
complete: () => setTimeout(() => timedTransmission(), 50000)
})
}
// 专门在初始化 获取筛选全局的值和传入的值
const updateProperty = (key, options, brandSelectionObj) => {
if (options[key] != undefined) return options[key]
else if (brandSelectionObj[key] != undefined) return brandSelectionObj[key]
}
// 字符串转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 goPage(url) {
wx.navigateTo({
url,
fail: function (err) {
if (err.errMsg = "navigateTo:fail webview count limit exceed") {
wx.redirectTo({
url,
})
}
}
})
}
function getTitleName(url) {
const obj = {
"pages/index/index": "首页",
"pages/appeal/appeal": "申诉",
"pages/needHousing/needHousing": "求房源",
"pages/personList/personList": "个人房源列表",
"pages/agentList/agentList": "中介房源列表",
"pages/brandApartmentList/brandApartmentList": "公寓房源列表",
"pages/report/report": "举报",
"pages/irentPark/irentPark": "学生公寓",
"pages/user/user": "我的",
"pages/search/search": "搜索",
"pages/edit/edit": "发布",
"pages/ad/ad": "广告模板展示",
"pages/brandApartmentDetail/brandApartmentDetail": "公寓详情",
"pages/show/show": "房源详情",
"pages/share/share": "分享海报",
"pages/messageCenter/messageCenter": "系统通知",
"pages/webViewwebweb/index": "H5",
"pages/circularize/circularize": "申诉",
"pages/askHousing/askHousing": "发布求房源",
"pages/transfer/transfer": "中转页面",
"pages/video_show/video_show": "媒体展示页面",
"pagesLoginRequired/pages/setAvatarNickname/setAvatarNickname": "设置头像昵称",
"mapFind/pages/placeMap/index": "地图找房",
};
return obj[url] || "首页";
}
// 调用 统计接口
function statistics(obj) {
return
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
options = currentPage.options
}
// // 当页面显示时执行
// const pages = getCurrentPages(); // 获取当前页面栈
// const currentPage = pages[pages.length - 1]; // 当前页面对象
// const url = currentPage.route; // 当前页面url
// 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,
hostname: accountInfo.miniProgram.appId,
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 = {}) {
if (user.uid <= 0) return;
wx.xstat && wx.xstat.setUserid(user.uid); // 登录后手动设置用户id , 如果有
// 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 : '';
}
// 返回上一页或者首页
function backOrIndex() {
wx.navigateBack({
fail: function () {
wx.redirectTo({
url: '/pages/index/index',
})
}
})
}
module.exports = {
initial: initial,
share: share,
change_data: change_data,
html2wxml: html2wxml,
copy,
sendData,
request,
wxget,
closeAD,
clickAD,
count,
getTopTitle,
getTimeAgo,
useSocket,
updateProperty,
goPage,
https: function (url, data, success, fail) {
wx.request({
url: url,
data: data,
method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: {
'content-type': 'application/json',
'Accept': 'application/json, text/plain',
'Cookie': 'miucms_session=' + wx.getStorageSync('Authorization'),
'Authorization': wx.getStorageSync('Authorization') || ''
},
success: function (res) {
typeof success == 'function' && success(res);
},
fail: function () {
typeof fail == 'function' && fail(res);
},
complete: function () {
typeof fail == 'function' && fail(res);
}
})
},
statistics,
bindingUser,
objectToQueryString,
gtergreenonionqrcode: "https://oss.x-php.com/Zvt57TuJSUvkyhw-xG7Y2l-d_pIqcXjqqsgFptxhcq_cQnrlcvd3DQYcBq_D-81qNDQyOQ~~",
backOrIndex,
}