//app.js
|
const QQMapWX = require("./utils/qqmap-wx-jssdk");
|
const GdMap = require("./utils/amap-wx");
|
// const apiHost = 'http://221.182.45.100:5000/user'
|
// const apiHost = "https://test-qncx.sitechcloud.com/chuxing/user-server"; //本地
|
// const apiHost = "http://192.168.110.111:5000/user-server";
|
// const apiHost = 'http://123.56.89.63:8080/user-server'
|
// 上面地址不管用,下面的地址才用
|
// const apiHost = 'http://221.182.45.100:7894/user'; //本地
|
const apiHost = 'https://ride.cbyzx.com/user' //线上
|
const SOCKET_URL = "wss://ride.cbyzx.com/websocket";
|
const SOCKET_HEARTBEAT_INTERVAL = 10000;
|
const SOCKET_RECONNECT_DELAY = 3000;
|
|
App({
|
// 这里这么写,是要在其他界面监听,而不是在app.js中监听,而且这个监听方法,需要一个回调方法。
|
watch(method) {
|
if (typeof method !== "function") {
|
return;
|
}
|
const socketWatchers = this.globalData.socketWatchers || [];
|
if (socketWatchers.indexOf(method) === -1) {
|
socketWatchers.push(method);
|
}
|
this.globalData.socketWatchers = socketWatchers;
|
},
|
unwatch(method) {
|
if (typeof method !== "function") {
|
return;
|
}
|
this.globalData.socketWatchers = (this.globalData.socketWatchers || []).filter(
|
(item) => item !== method
|
);
|
},
|
registerSocketCallback(method) {
|
if (typeof method !== "function") {
|
return;
|
}
|
const socketCallbacks = this.globalData.socketCallbacks || [];
|
if (socketCallbacks.indexOf(method) === -1) {
|
socketCallbacks.push(method);
|
}
|
this.globalData.socketCallbacks = socketCallbacks;
|
},
|
unregisterSocketCallback(method) {
|
if (typeof method !== "function") {
|
return;
|
}
|
this.globalData.socketCallbacks = (this.globalData.socketCallbacks || []).filter(
|
(item) => item !== method
|
);
|
},
|
notifySocketMessage(res) {
|
this.globalData.lastSocketActiveAt = Date.now();
|
if (typeof this.globalData.callback === "function") {
|
try {
|
this.globalData.callback(res);
|
} catch (error) {
|
console.log("legacy socket callback error", error);
|
}
|
}
|
(this.globalData.socketCallbacks || []).forEach((method) => {
|
try {
|
method(res);
|
} catch (error) {
|
console.log("socket callback error", error);
|
}
|
});
|
(this.globalData.socketWatchers || []).forEach((method) => {
|
try {
|
method(res.data);
|
} catch (error) {
|
console.log("socket watcher error", error);
|
}
|
});
|
this.globalData.resData = res.data;
|
},
|
clearSocketHeartbeat() {
|
if (this.globalData.socketHeartbeatTimer) {
|
clearInterval(this.globalData.socketHeartbeatTimer);
|
this.globalData.socketHeartbeatTimer = null;
|
}
|
},
|
clearSocketReconnectTimer() {
|
if (this.globalData.socketReconnectTimer) {
|
clearTimeout(this.globalData.socketReconnectTimer);
|
this.globalData.socketReconnectTimer = null;
|
}
|
},
|
startSocketHeartbeat() {
|
this.clearSocketHeartbeat();
|
const msg = {
|
code: 200,
|
method: "PING",
|
msg: "SUCCESS",
|
data: {
|
type: 1,
|
userId: wx.getStorageSync("userId"),
|
token: wx.getStorageSync("token") || "",
|
businessType: 1,
|
},
|
};
|
this.sendSocketMessage(JSON.stringify(msg));
|
this.globalData.socketHeartbeatTimer = setInterval(() => {
|
this.sendSocketMessage(JSON.stringify(msg));
|
}, SOCKET_HEARTBEAT_INTERVAL);
|
},
|
scheduleSocketReconnect() {
|
const token = wx.getStorageSync("token");
|
if (!token || token === "quit" || this.globalData.socketReconnectTimer) {
|
return;
|
}
|
this.globalData.socketReconnectTimer = setTimeout(() => {
|
this.globalData.socketReconnectTimer = null;
|
this.initSocket();
|
}, SOCKET_RECONNECT_DELAY);
|
},
|
resetSocketState() {
|
this.globalData.sockTaskStatus = false;
|
this.globalData.isSocketConnecting = false;
|
this.clearSocketHeartbeat();
|
},
|
refreshSocketConnection() {
|
const currentSocket = this.globalData.localSocket;
|
this.clearSocketReconnectTimer();
|
this.resetSocketState();
|
this.globalData.localSocket = null;
|
if (
|
currentSocket &&
|
typeof currentSocket.close === "function" &&
|
(currentSocket.readyState === 0 || currentSocket.readyState === 1)
|
) {
|
try {
|
currentSocket.close({});
|
} catch (error) {
|
console.log("close current socket error", error);
|
}
|
}
|
return this.initSocket();
|
},
|
//初始化socket
|
initSocket() {
|
const token = wx.getStorageSync("token");
|
if (!token || token == "quit") {
|
this.clearSocketReconnectTimer();
|
this.resetSocketState();
|
this.globalData.localSocket = null;
|
return null;
|
}
|
const currentSocket = this.globalData.localSocket;
|
const readyState =
|
currentSocket && typeof currentSocket.readyState !== "undefined" ?
|
currentSocket.readyState :
|
-1;
|
if (this.globalData.sockTaskStatus && readyState === 1) {
|
return currentSocket;
|
}
|
if (this.globalData.isSocketConnecting || readyState === 0) {
|
return currentSocket;
|
}
|
console.log("初始化");
|
this.clearSocketReconnectTimer();
|
this.clearSocketHeartbeat();
|
this.globalData.isSocketConnecting = true;
|
const socketTask = wx.connectSocket({
|
url: SOCKET_URL,
|
});
|
this.globalData.localSocket = socketTask;
|
socketTask.onOpen((res) => {
|
if (this.globalData.localSocket !== socketTask) {
|
return;
|
}
|
console.log("/////////////", res);
|
this.globalData.sockTaskStatus = true;
|
this.globalData.isSocketConnecting = false;
|
this.globalData.lastSocketActiveAt = Date.now();
|
this.startSocketHeartbeat();
|
});
|
socketTask.onMessage((res) => {
|
if (this.globalData.localSocket !== socketTask) {
|
return;
|
}
|
this.notifySocketMessage(res);
|
});
|
socketTask.onError((res) => {
|
if (this.globalData.localSocket !== socketTask) {
|
return;
|
}
|
console.log("readyState=" + socketTask.readyState, res);
|
this.globalData.sockTaskStatus = false;
|
this.globalData.isSocketConnecting = false;
|
this.clearSocketHeartbeat();
|
this.scheduleSocketReconnect();
|
});
|
socketTask.onClose((res) => {
|
if (this.globalData.localSocket !== socketTask) {
|
return;
|
}
|
this.resetSocketState();
|
this.globalData.localSocket = null;
|
console.log(
|
"WebSocket连接已关闭!readyState=" + socketTask.readyState,
|
res
|
);
|
this.scheduleSocketReconnect();
|
});
|
return socketTask;
|
},
|
//统一发送消息
|
sendSocketMessage: function (msg) {
|
if (
|
this.globalData.localSocket &&
|
this.globalData.localSocket.readyState === 1
|
) {
|
this.globalData.localSocket.send({
|
data: msg,
|
});
|
this.globalData.lastSocketActiveAt = Date.now();
|
}
|
},
|
|
//关闭socket
|
closeSocket() {
|
const currentSocket = this.globalData.localSocket;
|
this.clearSocketReconnectTimer();
|
this.resetSocketState();
|
this.globalData.localSocket = null;
|
if (
|
currentSocket &&
|
typeof currentSocket.close === "function" &&
|
(currentSocket.readyState === 0 || currentSocket.readyState === 1)
|
) {
|
currentSocket.close({});
|
}
|
},
|
getFloatStr: function (num) {
|
num += "";
|
num = num.replace(/[^0-9|\.]/g, ""); //清除字符串中的非数字非.字符
|
if (/^0+/)
|
//清除字符串开头的0
|
num = num.replace(/^0+/, "");
|
if (!/\./.test(num))
|
//为整数字符串在末尾添加.00
|
num += ".00";
|
if (/^\./.test(num))
|
//字符以.开头时,在开头添加0
|
num = "0" + num;
|
num += "00"; //在字符串末尾补零
|
num = num.match(/\d+\.\d{2}/)[0];
|
console.log(num);
|
},
|
onShow(options) {
|
//socket
|
if (wx.getStorageSync("token")) {
|
const hiddenDuration = this.globalData.appHideAt ?
|
Date.now() - this.globalData.appHideAt :
|
0;
|
const needRefresh =
|
hiddenDuration >= SOCKET_HEARTBEAT_INTERVAL ||
|
!this.globalData.localSocket ||
|
this.globalData.localSocket.readyState !== 1;
|
if (needRefresh) {
|
this.refreshSocketConnection();
|
} else {
|
this.startSocketHeartbeat();
|
}
|
}
|
var obj = wx.getEnterOptionsSync();
|
if (options.scene == 1069) {
|
return false;
|
}
|
clearInterval(this.globalData.comparisonToken);
|
var comparisonToken = setInterval(() => {
|
this.globalData.comparisonToken = comparisonToken;
|
if (wx.getStorageSync("token") !== "") {
|
this.getsetTime();
|
}
|
}, 5000);
|
},
|
onHide() {
|
this.globalData.appHideAt = Date.now();
|
clearInterval(this.globalData.comparisonToken);
|
this.globalData.comparisonToken = "";
|
},
|
|
//单点登录接口
|
getsetTime() {
|
let token = wx.getStorageSync("token");
|
let header = {
|
"Content-Type": "application/json;charset=UTF-8,",
|
Authorization: "Bearer" + " " + token,
|
};
|
wx.request({
|
url: this.globalData.Url + "/api/user/comparisonToken",
|
header,
|
method: "POST",
|
success: (res) => {
|
if (res.data.code == 600 && token !== "" && token !== "quit") {
|
wx.setStorageSync("token", "");
|
wx.showModal({
|
title: "提示",
|
content: "您在其他地方登录了,是否重新登录",
|
showCancel: false,
|
confirmText: "确定", //默认是“确定”
|
confirmColor: "#00BF30", //确定文字的颜色
|
success: (res) => {
|
if (res.cancel) {
|
//点击取消,默认隐藏弹框
|
} else {
|
wx.redirectTo({
|
url: "/pages/home/home",
|
});
|
clearInterval(this.globalData.comparisonToken);
|
}
|
},
|
fail: function (res) {}, //接口调用失败的回调函数
|
complete: function (res) {}, //接口调用结束的回调函数(调用成功、失败都会执行)
|
});
|
}
|
},
|
});
|
},
|
onLaunch: function (options) {
|
wx.getSystemInfo({
|
success: (res) => {
|
console.log(res);
|
// console.log('手机信息res'+res.model)
|
let modelmes = res.model;
|
if (
|
modelmes.search("iPhone X") != -1 ||
|
modelmes.search("iPhone 11") != -1
|
) {
|
this.globalData.isIphoneX = true;
|
}
|
},
|
});
|
// // 展示本地存储能力
|
|
wx.setStorageSync("height", wx.getSystemInfoSync().windowHeight || "");
|
// 登录
|
wx.login({
|
success: (res) => {
|
// 发送 res.code 到后台换取 openId, sessionKey, unionId
|
},
|
});
|
// 获取用户信息
|
wx.getSetting({
|
success: (res) => {
|
if (res.authSetting["scope.userInfo"]) {
|
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
|
wx.getUserInfo({
|
success: (res) => {
|
// 可以将 res 发送给后台解码出 unionId
|
this.globalData.userInfo = res.userInfo;
|
|
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
|
// 所以此处加入 callback 以防止这种情况
|
if (this.userInfoReadyCallback) {
|
this.userInfoReadyCallback(res);
|
}
|
},
|
});
|
}
|
},
|
});
|
},
|
|
getQQMap() {
|
return new GdMap.AMapWX({
|
key: "0a4ecc86729b8d18661abd5d0686e42c",
|
// key:"be262c006216c542747fce766130cee3"
|
});
|
// return new QQMapWX({
|
// key: "UHWBZ-6NM3U-DHCVH-2NMFG-XWCIH-WUBYM",
|
// });
|
},
|
|
getQQMaps() {
|
// return new GdMap.AMapWX({
|
// key: "0a4ecc86729b8d18661abd5d0686e42c",
|
// });
|
return new QQMapWX({
|
key: "UHWBZ-6NM3U-DHCVH-2NMFG-XWCIH-WUBYM",
|
});
|
},
|
//showToast--弹出框
|
showToastSuccess: function (value, images, status, time) {
|
try {
|
let image = images || "";
|
wx.showToast({
|
title: value,
|
image,
|
icon: status,
|
duration: time,
|
});
|
} catch (err) {
|
console.log(err);
|
}
|
},
|
|
//正则手机号验证
|
testPhone: function (phoneNum) {
|
var myreg = /^1[3456789]\d{9}$/;
|
if (phoneNum.length == 0) {
|
wx.showToast({
|
title: "输入手机号",
|
icon: "none",
|
duration: 1500,
|
});
|
return false;
|
} else if (phoneNum.length < 11 || phoneNum.length > 11) {
|
wx.showToast({
|
title: "手机号有误",
|
icon: "none",
|
duration: 1500,
|
});
|
return false;
|
} else if (!myreg.test(phoneNum)) {
|
wx.showToast({
|
title: "手机号错误1",
|
icon: "none",
|
duration: 1500,
|
});
|
return false;
|
} else {
|
return true;
|
}
|
},
|
//验证码手机号验证
|
testPhoneCode: function (phoneNum) {
|
var myreg = /^1[3456789]\d{9}$/;
|
if (phoneNum.length == 0) {
|
wx.showToast({
|
title: "输入手机号",
|
icon: "none",
|
duration: 1500,
|
});
|
return false;
|
} else if (phoneNum.length < 11 || phoneNum.length > 11) {
|
wx.showToast({
|
title: "手机号有误",
|
icon: "none",
|
duration: 1500,
|
});
|
return false;
|
} else if (!myreg.test(phoneNum)) {
|
wx.showToast({
|
title: "手机号错误",
|
icon: "none",
|
duration: 1500,
|
});
|
return false;
|
} else {
|
console.log("1");
|
return true;
|
}
|
},
|
//request请求
|
apiRequest(url, data, method, upload) {
|
let that = this;
|
let token = wx.getStorageSync("token");
|
let header = "";
|
let havePhone = wx.getStorageSync("havePhone");
|
if (!havePhone) {
|
wx.redirectTo({
|
url: "/pages/wxChatPhone/wxChatPhone",
|
});
|
return false;
|
}
|
if (token) {
|
header = {
|
"Content-Type": "application/json;charset=UTF-8,",
|
Authorization: "Bearer" + " " + token,
|
};
|
if (method == "PUT" || method == "POST") {
|
if (upload == 1) {
|
header = {
|
"content-type": "multipart/form-data",
|
Authorization: "Bearer" + " " + token,
|
};
|
} else {
|
header = {
|
"content-type": "application/x-www-form-urlencoded",
|
Authorization: "Bearer" + " " + token,
|
};
|
}
|
}
|
} else {
|
header = {
|
"Content-Type": "application/json;charset=UTF-8,",
|
Authorization: "",
|
};
|
if (method == "PUT" || method == "POST") {
|
header = {
|
"content-type": "application/x-www-form-urlencoded",
|
Authorization: "",
|
};
|
}
|
}
|
|
return new Promise((resolve, reject) => {
|
if (upload != 2) {
|
wx.showLoading({
|
mask: true,
|
});
|
}
|
|
// 上传图片文件
|
if (upload == 1) {
|
// console.log(data);
|
wx.uploadFile({
|
url: apiHost + url,
|
header: header,
|
filePath: data,
|
name: "file",
|
formData: {},
|
success: (res) => {
|
let data = JSON.parse(res.data);
|
//do something
|
resolve(data);
|
},
|
fail: (res) => {
|
reject(res);
|
},
|
});
|
} else {
|
wx.request({
|
url: apiHost + url,
|
data: data || {},
|
header: header,
|
method: method || "GET",
|
dataType: "json",
|
responseType: "text",
|
success: (res) => {
|
// console.log(res);
|
if (upload != 2) {
|
wx.hideLoading();
|
}
|
|
console.log(res);
|
if (res.data.code == 500) {
|
reject();
|
return wx.showToast({
|
title: res.data.msg,
|
icon: "none",
|
duration: 1500,
|
mask: true,
|
});
|
}
|
resolve(res);
|
if (res.data.code == 200) {} else if (res.data.code == 500) {
|
if (res.data.msg == "Token失效") {
|
// 清空本地token
|
wx.setStorageSync("token", "");
|
wx.showModal({
|
title: "登录失效,是否登录",
|
content: "",
|
showCancel: true,
|
cancelText: "取消",
|
cancelColor: "#000000",
|
confirmText: "确定",
|
confirmColor: "#00BF30",
|
success: (result) => {
|
if (result.confirm) {
|
wx.navigateTo({
|
url: "/pages/index/index",
|
});
|
}
|
},
|
});
|
} else if (res.data.msg == "验证码已失效") {
|
wx.setStorageSync("token", "");
|
wx.showToast({
|
title: "验证码有误,请重新输入",
|
icon: "none",
|
duration: 1500,
|
mask: true,
|
});
|
} else {}
|
} else if (res.data.code == 600 || res.data.code == 700) {
|
// 清空本地token
|
if (wx.getStorageSync("token") == "") {
|
wx.showModal({
|
title: "您还未登录,是否登录",
|
content: "",
|
showCancel: false,
|
cancelColor: "#000000",
|
confirmText: "确定",
|
confirmColor: "#00BF30",
|
success: (result) => {
|
if (result.confirm) {
|
wx.navigateTo({
|
url: "/pages/index/index",
|
});
|
}
|
},
|
});
|
setTimeout(() => {
|
this.setData({
|
btnDisabled: false,
|
});
|
}, 2000);
|
return;
|
} else {
|
wx.showModal({
|
title: "登录失效,是否登录",
|
content: "",
|
showCancel: false,
|
cancelColor: "#000000",
|
confirmText: "确定",
|
confirmColor: "#00BF30",
|
success: (result) => {
|
if (result.confirm) {
|
wx.navigateTo({
|
url: "/pages/index/index",
|
});
|
}
|
},
|
});
|
setTimeout(() => {
|
this.setData({
|
btnDisabled: false,
|
});
|
}, 2000);
|
return;
|
}
|
} else {
|
// wx.showToast({
|
// title: res.data.msg,
|
// icon: "none",
|
// duration: 1500,
|
// });
|
}
|
},
|
fail: (res) => {
|
console.log(res);
|
if (upload != 2) {
|
wx.hideLoading();
|
}
|
wx.showToast({
|
title: "网络异常,请检查网络",
|
icon: "none",
|
duration: 1500,
|
});
|
reject(res);
|
},
|
complete: (res) => {},
|
});
|
}
|
});
|
},
|
|
// 弹出弹窗
|
|
globalData: {
|
userInfo: null,
|
cityName: wx.getStorageSync("cityName") || "",
|
userLatitude: wx.getStorageSync("latitude") || "",
|
userLongitude: wx.getStorageSync("longitude") || "",
|
|
// Url:'https://okyueche.com:443/user',
|
// Url: 'http://221.182.45.100:5000/user-server',
|
// Url: "https://test-qncx.sitechcloud.com/chuxing/user-server", //本地
|
// Url: "http://192.168.110.64:8006",
|
// Url: 'http://192.168.0.80:8080/user-server',
|
|
|
// 上面地址不管用,下面的地址才用
|
// Url: 'http://221.182.45.100:7894/user', //本地
|
Url : 'https://ride.cbyzx.com/user',
|
|
|
localSocket: {},
|
callback: function () {},
|
sockTaskStatus: false,
|
isSocketConnecting: false,
|
resData: {},
|
socketWatchers: [],
|
socketCallbacks: [],
|
socketHeartbeatTimer: null,
|
socketReconnectTimer: null,
|
lastSocketActiveAt: 0,
|
appHideAt: 0,
|
isIphoneX: false,
|
state: 0,
|
comparisonToken: "",
|
driveTimer: "",
|
drivelat: "",
|
drivelon: "",
|
timer: require("./utils/wxTime"),
|
},
|
});
|