You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1392 lines
36 KiB

/**
* tabBar页面路径列表 (用于链接跳转时判断)
* tabBarLinks为常量, 无需修改
*/
import Store from "@/store"
import util from "@/common/js/util.js"
// #ifdef H5
import wxApi from "@/common/js/wxApi.js"
// import manifest from "@/manifest.json"
// #endif
const tabBarLinks = [
'pages/mainPages/index/index',
'pages/mainPages/headline/index',
'pages/mainPages/userCenter/userCenter',
'pages/mainPages/index/diypage?type=1',
'pages/mainPages/index/diypage?type=2',
'pages/mainPages/index/diypage?type=3',
'pages/mainPages/index/diypage?type=4',
'pages/mainPages/index/diypage?type=5',
'pages/mainPages/index/diypage?type=6',
'pages/mainPages/index/diypage?type=7'
];
const Base64 = util.Base64;
// 工具类
let App = {
/**
* 全局变量
*/
globalData: {
user_id: null,
},
// api地址
api_root: '',
scanCode: false,
aid: '',
// 图片地址
img_root: '',
imgfix: '',
siteInfo: {},
postData: {},
loginstate:false,
base:null,
routers:null,
languageStatus:0,
/**
* 设置项目基础信息
*/
setSiteInfo() {
// uni.setStorageSync('head_id', '24')
let version = require("@/siteinfo.json");
this.base = version.base;
this.routers = version.routers;
// #ifdef H5
let url = location.href,
uniacid;
if (process.env.NODE_ENV === 'development') {
uni.setStorageSync("uniacid", 1);
this.siteInfo = {
"siteroot": "https://citydev.weliam.com.cn",
"uniacid": "1",
"name": "weliam_smartcity",
"weliamv": "1.0.0"
};
} else {
if (location.href.indexOf("/h5/?#/pages/") === -1) {
let reg = new RegExp("\/h5/.*?\#/");
url = url.replace(reg, "/h5/#/");
}
//获取当前请求域名
uniacid = util.getParams("i", url.split("#")[1], true);
let siteroot = location.protocol + "//" + location.hostname,
sitetoken = App.getClientType(),
name = location.href.split('/addons/')[1].split('/h5/')[0],
token = (sitetoken == 1) ? App.getCookie("weliam_user_token") : uni.getStorageSync('weliam_user_token'),
head_id = (location.href.indexOf("&token") === -1 ? location.href.split("head_id=")[1] : location.href.split("&")[
1].split("head_id=")[1]) || "";
let head_ids = head_id.split("&")[0];
if (head_id && !!head_id) {
// debugger
uni.setStorageSync('head_id', head_ids);
uni.setStorageSync('dating_head_id', head_ids);
};
this.siteInfo = {
siteroot,
name,
uniacid,
weliamv: version.weliamv,
token
}
url = url.split("&token=")[0];
history.replaceState(null, null, `${this.base}#` + url.split("#")[1]);
}
if(url.indexOf('pages/mainPages/postDetails/postDetails') != -1){
//
let urls = url.split('/#/')[1];
urls = urls.replace('mainPages', "subPages");
this.navigationTo({
url:urls
});
return
}
// #endif
// #ifndef H5
this.siteInfo = version;
// #endif
this.imgfix = uni.getStorageSync('imgPrefix');
},
/**
* 设置api地址
*/
setAppRoot(aids) {
this.aid = aids + ',';
let App = this,
siteroot = null,
postData = {
source: "1",
mode: "2",
},
weliam_user_token = this.getCookie("weliam_user_token");
siteroot = this.siteInfo.siteroot + `${this.routers}`;
this.aid = this.aid.replace(/,/g, '');
this.api_root = siteroot + 'uniapp.php?i=' + this.siteInfo.uniacid + (!!this.siteInfo.token ? '&token=' +
this.siteInfo.token : '');
if (this.api_root.indexOf('aid') === -1) {
this.api_root + '&aid=' + this.aid;
}
this.img_root = this.siteInfo.siteroot + `${this.base}/resource/image/`;
this.img_root_new = this.siteInfo.siteroot + `addons/weliam_smartcity/data/img/`;
let apiObj = this.urlToObj(this.api_root);
if (!!apiObj.token && apiObj.token !== "undefined") {
uni.setStorageSync('weliam_user_token', apiObj.token)
} else {
// this._post_form('&p=member&do=login&source=1&mode=2', {}, (res) => {
// console.log(res);
// });
}
},
/**
* 小程序启动场景
*/
onStartupScene(query) {
if (query && !!query.head_id) {
// debugger
uni.setStorageSync('head_id', query.head_id);
uni.setStorageSync('dating_head_id', query.head_id);
}
},
/**
* 获取小程序信息
*/
updateAppInfo() {
let App = this;
App._post_form('&do=GetPlatformInfor', {}, function(result) {
Store.commit("APPINFO", result.data);
App.languageStatus = result.data.languageStatus;
uni.setStorage({
key: 'phone',
data: result.data.phone,
success: function() {}
});
uni.removeStorageSync('platformInfor');
uni.setStorage({
key: 'platformInfor',
data: result.data,
success: function() {}
});
});
},
//更新提示
up(){
const updateManager = uni.getUpdateManager();
updateManager.onCheckForUpdate(function (res) {
// 请求完新版本信息的回调
console.log(res.hasUpdate);
});
updateManager.onUpdateReady(function (res) {
uni.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success(res) {
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate();
}
}
});
});
updateManager.onUpdateFailed(function (res) {
// 新的版本下载失败;
uni.showModal({
title: '升级失败',
content: '新版本下载失败,请检查网络!',
showCancel: false
});
});
},
//获取用户设置
userSettings(){
let App = this;
App._post_form('&do=CustomerService', {}, function(result) {
uni.removeStorageSync('CustomerService');
uni.removeStorageSync('btnleftAndbottom');
let ratio;
uni.getSystemInfo({
success: function(wh) {
ratio = wh.windowWidth / result.data.imgstyle.width;
}
});
let imgstyle = { //imgstyle为根据接口获取用户设置的宽高,根据设备进行比例转换,以达到无论多少宽高都要占满宽度。
width:ratio * result.data.imgstyle.width,
height:ratio * result.data.imgstyle.height
};
uni.setStorageSync('imgstyle',imgstyle);
let ratios;
uni.getSystemInfo({
success: function(wh) {
ratios = wh.windowWidth / result.data.listimgstyle.width;
}
});
//listimgstyle应用场景为内部页面的轮播图
let listimgstyle = {
width:ratios * result.data.listimgstyle.width,
height:ratios * result.data.listimgstyle.height
};
uni.setStorageSync('listimgstyle',listimgstyle);
uni.setStorageSync('CustomerService',result.data);
});
},
//SDK经纬度获取
wxApiCallback(path) {
let _this = this;
uni.removeStorageSync('memberCityAreaid');
// #ifdef H5
wxApi.wxRegister(() => {
jWeixin.getLocation({
type: 'gcj02',
success: function(res) {
uni.setStorageSync('curLoction', res);
let data = {
aid: this.aid,
lat: res.latitude,
lng: res.longitude
}
let curtimestamp = new Date().getTime(); //当前时间
let lastredpackeTime = uni.getStorageSync('locationGetTime'); // 最后次时间;
let now_packetTime = !!lastredpackeTime ? ((curtimestamp - lastredpackeTime) / 1000 / 60 % 60) : "";
if(!!now_packetTime && now_packetTime < 2) return
if(path == 'pages/mainPages/index/index'){
_this._post_form('&do=Aidtip', data, (reource) => {
if(reource.data.status == 1){
_this.showError(
`定位到您在${reource.data.memberCityName},是否切换到该地区?`,
data => {
if (data.confirm) {
uni.setStorageSync('memberCityAreaid',reource.data.memberCityAreaid);
_this.setAppRoot(reource.data.memberCityAid);
App.navigationToH5(false,`${this.base}#/?i=${_this.siteInfo.uniacid}&aid=${reource.data.memberCityAid}`);
window.location.reload();
}else{
let timestamp = (new Date()).getTime();
uni.setStorageSync('locationGetTime', timestamp)
}
},
true
);
}
return
})
}
}
});
})
// #endif
// #ifndef H5
App.getLocation().then(res => {
let data = {
aid: this.aid,
lat: res.latitude,
lng: res.longitude
}
let curtimestamp = new Date().getTime(); //当前时间
let lastredpackeTime = uni.getStorageSync('locationGetTime'); // 最后时间;
let now_packetTime = !!lastredpackeTime ? ((curtimestamp - lastredpackeTime) / 1000 / 60 % 60) : "";
if(!!now_packetTime && now_packetTime < 2) return
if(path == 'pages/mainPages/index/index'){
_this._post_form('&do=Aidtip', data, (reource) => {
uni.setStorageSync('curLoction', res);
if(reource.data.status == 1){
_this.showError(
`定位到您在${reource.data.memberCityName},是否切换到该地区?`,
data => {
if (data.confirm) {
uni.setStorageSync('memberCityAreaid',reource.data.memberCityAreaid);
_this.setAppRoot(reource.data.memberCityAid);
App.navigationTo({
url: 'pages/mainPages/index/index'
});
}else{
let timestamp = (new Date()).getTime();
uni.setStorageSync('locationGetTime', timestamp)
}
},
true
);
}
})
}
})
// #endif
},
/**
* 跳转链接转换
*/
navgatetoLink() {
let App = this;
App._post_form('&do=TransformationLink', {}, (res) => {
uni.setStorageSync('pagelinkList', res.data);
})
},
getCookie(cookieName) {
// #ifdef H5
let cookies = document.cookie,
cookiesArr = cookies.split(";");
for (let i = 0; i < cookiesArr.length; i++) {
let arr = cookiesArr[i].split("=");
arr[0] = arr[0].replace(/ /g, '')
if (arr[0] === cookieName) {
return arr[1];
}
}
return "";
// #endif
return "";
},
getuserToken() {
return uni.getStorageSync('weliam_user_token')
},
/**
* 获取tabBar页面路径列表
*/
getTabBarLinks() {
return tabBarLinks;
},
/**
* 执行用户登录
*/
doLogin() {
// 保存当前页面
let App = this,
clientType = App.getClientType(),
pages = getCurrentPages(),
url = "";
// if(App.loginstate){
// // return
// }
if (pages.length > 0) {
let currentPage = pages[pages.length - 1],
pageOptions = (clientType === "1" || clientType === "2" ? currentPage : currentPage.$vm).$mp.query;
("pages/mainPages/login/login" != currentPage.route) && uni.setStorageSync("currentPage", {
route: currentPage.route,
options: pageOptions
});
}
// // 跳转授权页面
// if (clientType === "2") {
// url = "pages/mainPages/login/login"
// } else if(clientType === "3") {
// url = "pages/mainPages/login/minLogin"
// }
App.navigationTo({
url
});
},
/**
* 微信公众号登陆
*/
openWxLogin(Navurl) {
let App = this;
// #ifdef H5
location.href = Navurl;
// #endif
},
/**
* 判断当前客户端类型
*/
getClientType() {
// 1 公众号 2h5 3微信
// #ifdef MP-WEIXIN
return "3";
// #endif
// #ifdef H5
let ua = navigator.userAgent.toLowerCase(); //获取判断用的对象
if (ua.match(/MicroMessenger/i) == "micromessenger") {
return "1";
}
return "2";
// #endif
//#ifdef APP-PLUS
return "3";
//#endif
},
// 获取浏览器内核版本号
getBrowser(n) {
// #ifdef H5
let ua = navigator.userAgent.toLowerCase(),
s,
name = '',
ver = 0;
//探测浏览器
(s = ua.match(/msie ([\d.]+)/)) ? _set("ie", _toFixedVersion(s[1])):
(s = ua.match(/firefox\/([\d.]+)/)) ? _set("firefox", _toFixedVersion(s[1])) :
(s = ua.match(/chrome\/([\d.]+)/)) ? _set("chrome", _toFixedVersion(s[1])) :
(s = ua.match(/opera.([\d.]+)/)) ? _set("opera", _toFixedVersion(s[1])) :
(s = ua.match(/version\/([\d.]+).*safari/)) ? _set("safari", _toFixedVersion(s[1])) : 0;
function _toFixedVersion(ver, floatLength) {
ver = ('' + ver).replace(/_/g, '.');
floatLength = floatLength || 1;
ver = String(ver).split('.');
ver = ver[0] + '.' + (ver[1] || '0');
ver = Number(ver).toFixed(floatLength);
return ver;
}
function _set(bname, bver) {
name = bname;
ver = bver;
}
return (n == 'n' ? name : (n == 'v' ? ver : name + ver));
//getBrowser("n"); // 所获得的就是浏览器所用内核。
//getBrowser("v");// 所获得的就是浏览器的版本号。
//getBrowser();// 所获得的就是浏览器内核加版本号。
// #endif
},
/**
* 验证是否存在user_info
*/
validateUserInfo() {
let user_info = uni.getStorageSync('userInfo');
return !!uni.getStorageSync('userInfo');
},
/**
* 显示成功提示框
*/
showSuccess(msg, callback) {
uni.showToast({
title: msg,
icon: 'success',
mask: true,
duration: 1500,
success() {
callback && (setTimeout(function() {
callback();
}, 1500));
}
});
},
/**
* 显示失败提示框
*/
showError(msg, callback, showCancel = false) {
uni.showModal({
title: '友情提示',
content: msg,
showCancel: showCancel,
success(res) {
callback && callback(res);
}
});
},
/**
* @param {Object} url 请求地址转换
*/
transformUrl(url) {
return this.api_root + url;
},
/**
* get请求
*/
_get(url, data, success, fail, complete) {
this.weRequest("GET", url, data, success, fail, complete);
},
/**
* post提交
*/
_post_form(url, data, success, fail, complete) {
this.weRequest("POST", url, data, success, fail, complete);
},
weRequest(method, url, data, success, fail, complete) {
let App = this,
// uniacid = App.getUniacid(),
requestUrl = App.transformUrl(url),
pages = getCurrentPages(),
currentRegion = uni.getStorageSync('currentRegion'),
agencyData = uni.getStorageSync('agencyData'),
token = uni.getStorageSync('weliam_user_token'),
source = App.getClientType(), //1公众号 2H5 3微信小程序
loginTimer = null;
// console.log(url.indexOf('&p=dating') == -1?requestUrl:requestUrl + '&dating_head_id=' + uni.getStorageSync('dating_head_id'),'当前请求');
// 构造请求参数
data = data || {};
data.wxapp_id = App.siteInfo.uniacid;
data.aid = this.aid || agencyData.aid || "";
data.token = uni.getStorageSync('weliam_user_token');
data.source = source;
// //#ifdef APP-PLUS
// data.source = "3";
// //#endif
// //#ifdef H5
// data.source = "4";
// //#endif
uni.request({
url:url.indexOf('&p=dating') == -1?requestUrl:requestUrl + '&dating_head_id=' + uni.getStorageSync('dating_head_id'),
header: {
'content-type': method === "POST" ? "application/x-www-form-urlencoded" : "application/json",
},
method: method,
data: data,
success(res) {
//#ifdef H5
let post = requestUrl.split('&do=')[1];
let local;
let onoption;
if(post == 'GetPlatformInfor'){
if(location.href.indexOf(".cn/") != -1){
local = location.href.split('.cn/')[0] + '.cn/';
onoption = location.href.split('.cn/')[1];
}else{
local = location.href.split('.com/')[0] + '.com/';
onoption = location.href.split('.com/')[1];
}
if(res.data.data.targetDmain.length > 0){
res.data.data.targetDmain.map(item=>{
if(item == local){
location.href = res.data.data.endDmain + onoption;
}
})
}
// location.href = 'https://yys.163.com/'
// App.openWxLogin('www.baidu.com');
};
//#endif
if (res.statusCode !== 200 || typeof res.data !== 'object') {
if(url == '&do=getItemParams') return
App.showError(`网络请求出错:${url}`, () => {
fail && fail(res);
});
return false;
}
//
if (res.data.errno === 5 || res.data.message == "请先登录"){
uni.showToast({
title: '请先登录',
icon:'none'
})
setTimeout(()=>{
uni.navigateTo({
url: '/pages/mainPages/login/minLogin'
})
}, 2000)
}
if (res.data.errno === 2 || res.data.data.relogin == 1) {
uni.removeStorage('weliam_user_token');
if (pages.length > 0) {
// #ifdef H5
if (source === "2") {
App.doLogin()
} else {
let currentPage = pages[pages.length - 1],
currentPageRoute = pages[pages.length - 1].route,
currentPageUrl,
pageQuery = currentPage.$mp.query,
referrer_id = pageQuery.head_id || App.siteInfo.head_id,
vueurl = currentPageRoute + '?' + App.urlEncode(pageQuery) + (!!referrer_id ? '&head_id=' + referrer_id : "");
currentPageUrl = res.data.data.weChat_login + '&vueurl=' + encodeURIComponent(vueurl);
App.openWxLogin(currentPageUrl);
}
return false
// #endif
}else{
App.doLogin()
}
} else if (res.data.errno === 0) {
success && success(res.data);
} else if (res.data.errno === 1) {
// debugger
let post = requestUrl.split('&do=')[1];
if(post == 'phoneDecrypt'){
fail && fail(res);
return false;
}
let type = uni.getStorageSync('TextSubstitution').flag074;
//#ifdef MP-WEIXIN
let pages = getCurrentPages(),
currentPageObj = pages[pages.length - 1],
currentPage = currentPageObj.route;
//#endif
//#ifdef H5
let currentPage = location.href.split('?')[0].split('#/')[1];
//#endif
if(res.data.message == '请先绑定手机号' && type == 1 && currentPage != 'pages/subPages2/cleanCustom/bindingPhone'){
// debugger
uni.showModal({
showCancel:false,
content:res.data.message,
success() {
// debugger
App.navigationTo({
url: 'pages/subPages2/cleanCustom/bindingPhone'
});
}
})
return
}
// debugger
//判断是否为会员特供,从而转入会员开卡页面,因error皆为1无法判断,只能用文字判断
if(res.data.message == '该商品会员特供,请先成为会员' || res.data.message == '当前商品为会员限定,请先成为会员!'|| res.data.message == '此商品会员特供,请先开通会员'){
// debugger
uni.showModal({
title:'温馨提示',
content:res.data.message,
success() {
if (res.confirm) {
App.navigationTo({
url: 'pages/mainPages/memberCard/getMembership/getMembership?card=nhave'
});
} else if (res.cancel) {
return
}
// debugger
}
})
return
}
if (!!res.data.data.mergeflag) {
//错误回调函数
fail && fail(res);
return false;
} else {
//
// let postis = requestUrl.split('&do=')[1];
// if(postis == 'useDiscountCard'){
// App.navigationTo({})
// }
// console.log(url);
//
if(url.indexOf('&p=distribution') != -1 && url.indexOf('&do=cashWithdrawalApply') == -1){
if(url.indexOf('&do=applyCondition') != -1){
return
}else if(url.indexOf('&do=disApply') != -1){
}else{
if(res.data.data.mustmobile != 1){
App.navigationTo({
url: res.data.data.url,
navType: 'reLaunch'
})
}
return false
}
}
// 相亲模块判断是否填写个人资料
if(url.indexOf('&p=dating') != -1 && res.data.data.is_perfect == 1) {
App.showError(res.data.message, () => {
uni.reLaunch({
url: '/pages/subPages2/blindDate/form/userInfo'
})
})
return
}
if(url.indexOf('&p=dating') != -1 && res.data.data.dating_is_matchmaker == 1) {
App.showError(res.data.message, () => {
uni.reLaunch({
url: '/pages/subPages2/blindDate/form/matchmakerApply'
})
})
return
}
// 相亲模块动态列表会员专区时,非会员跳转到开通会员 或者详情页面查看资料会员失效时跳转至开通页面
if(
(url.indexOf('&p=dating&do=dynamicList') != -1 && res.data.data.dating_is_vip == 1) ||
(url.indexOf('p=dating&do=seeMemberInfo') != -1 && res.data.errno == 1)
) {
App.showError(res.data.message,() => {
uni.reLaunch({
url: '/pages/subPages2/blindDate/member/open'
})
})
return
}
// 看不懂。。。
App.showError(res.data.message, function() {
fail && fail(res);
if(res.data.message == '该商品会员特供,请先成为会员' || res.data.message == '当前商品为会员限定,请先成为会员!'){
App.navigationTo({
url: 'pages/mainPages/memberCard/getMembership/getMembership?card=nhave'
});
return
}
uni.reLaunch({
url: '/' + res.data.data.url
})
})
return false;
}
} else if (res.data.errno === 5 && !App.loginstate) {
// #ifdef MP-WEIXIN || APP-PLUS
App.doLogin();
App.loginstate = true;
setTimeout(()=>{
App.loginstate = false;
},1000)
// #endif
}
},
fail(res) {},
complete(res) {
complete && complete(res);
}
});
},
// 推荐人id
saveRefereeId() {
if (!!Store.state.recomid) {
return Store.state.recomid
}
},
getImgUrl() {
let App = this;
let a = this.siteInfo.uniacid;
App._post_form('&do=GetimgPrefix', {}, res => {
App.imgfix = res.data.imgPrefix;
uni.setStorageSync('imgPrefix', res.data.imgPrefix);
return App.imgfix
});
},
clipboard(data){
const textarea = document.createElement('textarea');
textarea.value = data;
textarea.readOnly = 'readOnly';
document.body.appendChild(textarea);
textarea.select();
textarea.setSelectionRange(0, data.length);
document.execCommand('copy');
textarea.remove();
textarea.style.display="none";
uni.showToast({
icon:'none',
title:'复制成功'
})
},
getSetInfo() {
let data = {
type:0
}
uni.setStorageSync('getSetInfo',data);
let App = this;
App._post_form('&p=Im&do=getSetInfo', {}, res => {
console.log(res)
uni.setStorageSync('getSetInfo', res.data);
});
},
getAreaId(location = "", cityname = "", areaid = "", callback, isSwitchCity = false) {
let memberCityAreaid = uni.getStorageSync('memberCityAreaid');
let App = this,
pages = getCurrentPages(),
navType = pages.length > 1 ? 'reLaunch' : 'navigate',
// requestData = {
// lat: !!location.lat ? (location.lat || location.latitude) : "",
// lng: !!location.lng ? (location.lng || location.longitude) : "",
// cityname,
// areaid,
// };
requestData = {
lat: location.lat || location.latitude || "",
lng: location.lng || location.longitude || "",
cityname,
areaid: areaid || memberCityAreaid
};
App._post_form('&do=GetAid', requestData, res => {
this.aid = res.data.aid;
if (res.data.status === 1 || res.data.status === 2) {
let agencyData = {
areaname: res.data.areaname,
aid: "",
lat: res.data.lat,
lng: res.data.lng
};
if (location) {
uni.setStorageSync('agencyData', res.data);
} else {
uni.setStorageSync('agencyData', agencyData);
}
App.setAppRoot(agencyData.aid);
App.getImgUrl();
App.navigationTo({
url: `pages/mainPages/notOpen/notOpen?city_agent_status=${res.data.status}&city_agent_name=${res.data.name}&joinPhone=${res.data.phone}`,
navType
})
return false;
} else if (res.data.status === 3) {
App.navigationTo({
url: `pages/subPages/city/city`,
navType
})
} else {
if (!isSwitchCity) {
uni.setStorageSync('agencyData', res.data);
App.setAppRoot(res.data.aid);
}
callback && callback(res)
}
})
},
wxShareInfo() {
let App = this;
App._post_form('&do=Shareinfo', {}, res => {
Store.commit('MPSHAREINFO', res.data)
})
},
dealershareInfo(callback, type = "11") {
let App = this;
App._post_form('&do=Shareinfo', {
type
}, res => {
callback && callback(res)
})
},
/**
* 清除登录缓存
*/
removeCurrentPage() {
uni.removeStorageSync("currentPage");
},
/**
* 对象转URL
*/
urlEncode(data) {
var _result = [];
for (var key in data) {
var value = data[key];
if (value.constructor == Array) {
value.forEach(function(_value) {
_result.push(key + "=" + _value);
});
} else {
_result.push(key + '=' + value);
}
}
return _result.join('&');
},
/**
* url转对象
*/
urlToObj(str) {
var obj = {};
var arr1 = str.split("?");
var arr2 = arr1[1].split("&");
for (var i = 0; i < arr2.length; i++) {
var res = arr2[i].split("=");
obj[res[0]] = res[1];
}
return obj;
},
/**
* 获取url参数
*/
getQueryString(name,url) {
let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
let r = url.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
8 },
/**
* 通用指定跳转链接方法
* url:跳转链接 navType:{navigate,rediRect,reLaunch,wxParse富文本}跳转方法, pageUrl 是否使用接口路径 success跳转成功回调
*/
navigationTo({
url,
navType = 'navigate',
success
}) {
let App = this,
tabBarLinks = App.getTabBarLinks(),
isTabBar = tabBarLinks.includes(url),
pageUrl = url.indexOf('http') !== -1 || url.indexOf('./index') !== -1,
isprogram = url.indexOf('appid') !== -1 || url.indexOf('appurl') !== -1,
istel = url.indexOf('tel') !== -1,
indet = url.indexOf('indet') !== -1;
// #ifdef H5
let pagetitle = uni.getStorageSync('TextSubstitution');
document.title = pagetitle.sysname || '⁣​';
// #endif
// #ifndef H5
// debugger
if (isprogram) {
let parmsArr = url.split(','),
appId = parmsArr[0].split('appid:')[1],
path = parmsArr[1].split('appurl:')[1];
if (!!appId && !!path) {
uni.navigateToMiniProgram({
appId,
path,
success(res) {
console.log('success', res)
// 打开成功
},
fail(err) {
console.log('err', err)
}
})
}
};
// #endif
if (istel) {
let tel = url.split("tel:")[1];
uni.makePhoneCall({
phoneNumber: tel
})
};
if (navType === 'wxParse') {
location.href = url
};
if (pageUrl) {
// #ifndef H5
url = encodeURIComponent(url)
uni.redirectTo({
url: `/pages/subPages/webview/webview?urlsrc=${url}`
});
// #endif
// #ifdef H5
let pagelink_list = uni.getStorageSync('pagelinkList'),
isPageIndex = url.indexOf('./index') !== -1,
isParms = url.indexOf('?') !== -1;
if (isParms) {
let params = App.urlToObj(url),
pageLine_name = `${params.p}/${params.ac}/${params.do}`;
if (!!params['p'] && !!params['ac'] && !!params['do']) {
for (let key in pagelink_list) {
let isPage_link = pageLine_name.indexOf(key) !== -1;
if (isPage_link) {
let navUrl = pagelink_list[pageLine_name],
newParams = params;
delete newParams['p'];
delete newParams['ac'];
delete newParams['do'];
delete newParams['c'];
delete newParams['m'];
navUrl += (navUrl.indexOf("?") !== -1 ? "&" : "?") + App.urlEncode(newParams);
// tabBar页面
if (isTabBar) {
uni.redirectTo({
url: '/' + navUrl
})
} else {
// 普通页面
uni.navigateTo({
url: '/' + navUrl
});
}
}
}
} else {
location.href = url
}
} else {
App.navigationToH5(isPageIndex, url)
}
// #endif
} else {
// #ifdef H5
if (url.indexOf("i=") === -1) {
url += (url.indexOf("?") !== -1 ? "&i=" : "?i=") + App.siteInfo.uniacid;
}
// #endif
if (navType === 'navigate') {
if (isTabBar) {
uni.redirectTo({
url: '/' + url
})
} else {
// 普通页面
uni.navigateTo({
url: '/' + url
});
}
} else if (navType === 'rediRect') {
uni.redirectTo({
url: '/' + url,
success
})
} else if (navType === 'reLaunch') {
uni.reLaunch({
url: '/' + url,
success
})
}
}
},
// h5跳转
navigationToH5(isPageIndex, url) {
let App = this;
// debugger
if (isPageIndex) {
// #ifdef H5
let pageIndexUrl = `${App.api_root}${url.split("./")[1]}`;
location.href = pageIndexUrl
// #endif
} else {
// #ifdef H5
location.href = url
// #endif
}
},
/**
* 记录formId
*/
saveFormId(temp_type) {
let App = this;
App._post_form('&do=TempId', {
temp_type
}, res => {
let formList = res.data,
idsArray = [];
if (formList.length > 0) {
formList.map((val => {
idsArray.push(val.temp_id)
}))
let encodeFormList = JSON.stringify(formList),
base = new Base64,
encodeStr = base.encode(encodeFormList);
uni.requestSubscribeMessage({
tmplIds: idsArray,
success(idsres) {
let tmpIdsArray = [];
for (let [key, val] of Object.entries(idsres)) {
if (val === 'accept') {
tmpIdsArray.push(key)
}
}
App._post_form('&do=SetFromId', {
form_id: tmpIdsArray,
info: encodeStr
}, res => {
console.log(res)
});
},
fail(err) {
console.log(err)
}
})
}
})
},
//浏览器上传图片
browser_upload(number = 1){
return new Promise((resolve, reject) => {
let imageData;
uni.chooseImage({
count: number, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album','camera'], //从相册选择
success: function (res) {
// let imageData = await App._upLoad(filePaths);
// return
resolve(res)
}
});
})
},
//上传图片
_upLoad(url) {
let App = this;
return new Promise((resolve, reject) => {
uni.uploadFile({
url: App.api_root + '&do=uploadFiles',
filePath: url,
fileType: "image",
name: 'file',
success(res) {
console.log(res, 'success')
if (res.statusCode !== 200 || typeof res.data !== 'string') {
App.showError('网络请求出错');
return false;
} else {
if (res.code === 0) {
App.showError(res.data.msg);
return false;
} else {
resolve(JSON.parse(res.data));
}
}
},
fail(res) {
console.log(res, 'fail')
uni.hideLoading();
uni.showModal({
title: "上传失败",
content: JSON.stringify(res),
showCancel: false
});
reject();
},
complete() {
uni.hideToast(); //隐藏Toast
}
})
});
},
_MYupLoad(url) {
let App = this;
return new Promise((resolve, reject) => {
uni.uploadFile({
url: App.api_root + '&do=StudentUploadFiles',
filePath: url,
fileType: "image",
name: 'file',
success(res) {
if (res.statusCode !== 200 || typeof res.data !== 'string') {
App.showError('网络请求出错');
return false;
} else {
if (res.code === 0) {
App.showError(res.data.msg);
return false;
} else {
resolve(JSON.parse(res.data));
}
}
},
fail(res) {
uni.hideLoading();
uni.showModal({
title: "上传失败",
content: JSON.stringify(res),
showCancel: false
});
reject();
},
complete() {
uni.hideToast(); //隐藏Toast
}
})
});
},
/**
* 获取当前页面栈
*/
getCurrentPage() {
//1-导入 2-微信小程序 3-H5 4-公众号 5-安卓 6-苹果 7-渠道1小程序 8-百度小程序 9-头条小程序
let App = this,
pages = getCurrentPages(),
clientType = App.getClientType(),
currentPage = pages[pages.length - 1],
pageInstance = null;
if (clientType === "2" || clientType === "7" || clientType === "9") {
pageInstance = currentPage.$vm;
} else if (clientType === "3" || clientType === "4") {
pageInstance = currentPage;
} else {
pageInstance = currentPage.rootVM;
}
return pageInstance;
},
/**
* 全屏加载
*/
// showLoading() {
// let App = this,
// page = App.getCurrentPage();
// !!page.$refs.loading && page.$refs.loading.showLoading();
// },
// hideLoading(time = 500) {
// let App = this,
// page = App.getCurrentPage();
// setTimeout(() => {
// !!page.$refs.loading && page.$refs.loading.hideLoading();
// }, time);
// },
/**
* 获取当前经纬度
*/
getLocation() {
let App = this,
clientType = App.getClientType();
return new Promise((resolve, reject) => {
let LocationType = clientType === "3" ? uni : wxApi;
LocationType.getLocation({
type: "gcj02", // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success(res) {
resolve(res);
},
fail(res) {
resolve({
latitude: "",
longitude: ""
});
},
complete(res) {
console.log(res);
}
});
})
},
/**
* 查看位置
*/
openLocation(options) {
let App = this;
if (!!options.location) {
// let gps = util.baidu_To_qq(options.latitude, options.longitude);
uni.openLocation({
name: options.storename,
address: options.address,
latitude: Number(options.location.lat),
longitude: Number(options.location.lng),
success() {
options.success && options.success();
}
});
} else {
App.showError("经纬度信息不完整,请确认后重试");
}
},
/**
* 商品富文本数据切割,避免一次性加载数据量超大
* @param {type}
*/
// wxParseLazyLoad(padding = 0, content, dataKey) {
// //商品富文本数据切割,避免一次性加载数据量超大
// let sliceLen = 20, //懒加载数据切割长度
// currentPage = this.getCurrentPage(),
// transData = {}, //存放转化后的数据
// bindData = {}, //存放当前绑定的数据
// nodePage = 0,
// nodesList = [],
// imageProp = {
// mode: 'aspectFit',
// padding,
// lazyLoad: false,
// domain: '',
// };
// transData = HtmlToJson(content, {}, imageProp);
// if (transData.nodes.length > sliceLen) {
// let nodes = transData.nodes;
// for (let i = 0, len = nodes.length; i < len; i += sliceLen) {
// nodesList.push(nodes.slice(i, i + sliceLen));
// }
// bindData.imageUrls = transData.imageUrls;
// bindData.nodes = nodesList[0];
// } else {
// bindData = transData;
// }
// currentPage[dataKey] = bindData;
// if (nodesList.length > 0) {
// for (let i = 1; i < nodesList.length; i++) {
// setTimeout(() => {
// currentPage[dataKey].nodes.push(...nodesList[i]);
// }, 800);
// }
// }
// },
// 获取地址和个人信息
getInt() {
let _this = this,
user_token = uni.getStorageSync('weliam_user_token');
if (user_token && !!user_token) {
_this._post_form('&p=member&do=memberInfo', {}, res => {
uni.setStorageSync('userinfo', res.data);
});
};
if (uni.getStorageSync('cityList') == undefined || uni.getStorageSync('cityList') == '') {
let data = {}
_this._post_form('&do=CityInfo', data, res => {
uni.setStorageSync('cityList', res.data);
})
}
// #ifdef H5
let pagetitle = uni.getStorageSync('TextSubstitution');
document.title = pagetitle.sysname || '⁣​';
// #endif
_this._post_form('&do=TextSubstitution', {}, res => {
uni.setStorageSync('TextSubstitution', res.data);
// #ifndef H5
let pages = getCurrentPages(),
curPage = pages[pages.length - 1],
filterList = [
'pages/mainPages/Settled/Settled',
'pages/subPages/merchant/sendDynamic/sendDynamic',
'pages/subPages/postRelease/postRelease',
'pages/mainPages/comment/comment'
];
if (res.data.examineing === "1") {
Store.commit("ISWXAUDIT", false);
if (!!curPage && filterList.includes(curPage.route)) {
_this.navigationTo({
url: 'pages/mainPages/index/index',
navType: 'reLaunch'
})
}
}
if(res.data.sysname && curPage.route.indexOf('pages/subPages2/redClothes/redClothes') == -1){
// 不需要吧
// uni.setNavigationBarTitle({
// title: res.data.sysname
// });
}
// #endif
// #ifdef H5
let locations = location.href;
if(res.data.sysname && locations.indexOf('pages/subPages2/redClothes/redClothes') == -1){
console.log('app.js执行',res.data.sysname)
// uni.setNavigationBarTitle({
// title:
// });
document.title = res.data.sysname
}
// #endif
})
}
}
export default {
...App
}