wechat_yxcl/common/utils.js
2024-09-03 18:19:25 +08:00

323 lines
9.0 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.

import store from '../store/store.js'
import request from '@/util/index.js'
// const QQMapWX = require('./qqmap-wx-jssdk.min.js')
// const qqmapsdk = new QQMapWX({
// key: "SVKBZ-P6QCJ-NH7F7-KOPJW-CBNEV-FUBRT"
// })
// /**
// * 地图两点之间的距离
// * @doc 文档参考https://lbs.qq.com/qqmap_wx_jssdk/method-search.html
// * @export
// * @param {*} to 坐标 { latitude: 39.984060, longitude: 116.307520 }
// * @param {*} location 坐标:{ latitude: 39.984060, longitude: 116.307520 }
// * @returns
// */
// function calculateDistance (fromp, to) {
// return new Promise((resolve, reject) => {
// qqmapsdk.calculateDistance({
// mode: 'straight',
// to: [{
// latitude: to.latitude,
// longitude: to.longitude
// }],
// 'from': {
// latitude: fromp.latitude,
// longitude: fromp.longitude
// },
// success: res => {
// resolve(res)
// },
// fail: err => {
// reject(err)
// uni.showToast({
// title: err.message,
// icon: 'none',
// duration: 3000
// })
// }
// })
// })
// }
// /**
// * 坐标转换,百度地图坐标转换成腾讯地图坐标
// * lng 腾讯经度pointy
// * lat 腾讯纬度pointx
// * 经度>纬度
// */
// function bMapToQQMap(lng, lat) {
// if (lng == null || lng == '' || lat == null || lat == '')
// return [lng, lat];
// var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
// var x = parseFloat(lng) - 0.0065;
// var y = parseFloat(lat) - 0.006;
// var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
// var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
// var lng = (z * Math.cos(theta)); //.toFixed(7);
// var lat = (z * Math.sin(theta)); //.toFixed(7);
// return [lng, lat];
// }
const netChange = () => {
uni.onNetworkStatusChange(function(res) {
// console.log(res.isConnected)
store.mutations.isConnect(res.isConnected)
if (!res.isConnected) {
uni.showToast({
title: '网络未连接',
icon: 'none'
})
}
})
}
const cutDate = (dd, type, daynum) => {
dd = new Date(dd) || new Date();
type = type || 'YYYY/MM/DD' //hh:mm:ss
daynum = daynum * 24 * 60 * 60 * 1000 || 0
// console.log(daynum,dd,dd.getTime()+daynum)
dd = new Date(dd.getTime() + daynum) // 获取AddDayCount天后的日期
var y = dd.getFullYear()
var m = (dd.getMonth() + 1) < 10 ? '0' + (dd.getMonth() + 1) : (dd.getMonth() + 1) // 获取当前月份的日期不足10补0
var d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号不足10补0
var h = dd.getHours() < 10 ? '0' + dd.getHours() : dd.getHours()
var mi = dd.getMinutes() < 10 ? '0' + dd.getMinutes() : dd.getMinutes()
var s = dd.getSeconds() < 10 ? '0' + dd.getSeconds() : dd.getSeconds()
return type.replace('YYYY', y).replace('MM', m).replace('DD', d).replace('hh', h).replace('mm', mi).replace('ss', s)
}
// 金额格式化处理方法
const fmoney = (s, n) => {
/*
* 参数说明:
* s要格式化的数字
* n保留几位小数
* */
n = n > 0 && n <= 20 ? n : 2;
var fuhao = ''; //如果数字小于零则值为-
if (s < 0) {
s = Math.abs(s);
fuhao = '-'
}
s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
var l = s.split(".")[0].split("").reverse(),
r = s.split(".")[1];
let t = "";
for (let i = 0; i < l.length; i++) {
t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
}
return fuhao + [...t].reverse().join("") + "." + r;
}
/**
* 将数据转成日期格式
* @param {string} s: 要格式化的日期数据
*/
function changeStringToDate(s) {
if (s.length === 14) {
return s.substring(0, 4) + '-' + s.substring(4, 6) + '-' + s.substring(6, 8) + ' ' +
s.substring(8, 10) + ':' + s.substring(10, 12) + ':' + s.substring(12, 14);
}
else if (s.length === 8) {
return s.substring(0, 4) + '-' + s.substring(4, 6) + '-' + s.substring(6, 8);
}
}
function toNextRoute(type, url) {
uni[type]({
url: url,
success: (result) => {
addUserBehaviorNew({
intoRoute: url
})
}
})
}
function addUserBehavior(obj) {
var pages = getCurrentPages() // 获取加载的页面
let len = pages.length
if (len) {
var currentPage = pages[len - 1] // 获取当前页面的对象
var nowRoute = '/' + currentPage.route // 当前页面url
if (obj) {
obj.outtoRoute = (obj.outtoRoute === '' || obj.outtoRoute) ? obj.outtoRoute : nowRoute
obj.intoRoute = obj.intoRoute ? obj.intoRoute.split('?')[0] : ''
} else {
obj = {}
obj.outtoRoute = nowRoute
obj.intoRoute = len > 1 ? '/' + pages[len - 2].route : '/pages/index/index'
}
}
obj.visitChannels = store.state.visitChannels
// request.$webGet('WeChat/AddUserBehaviorNew',obj).then(res => {
request.$webGet('WeChatPushAPI/Member/AddUserBehaviorNew', obj).then(res => {
// console.log(obj)
})
}
/*
根据关键字获取相应的枚举选项,文档见 https://api.eshangtech.com/EShangApiMain/swagger/ui/index#!/FrameWork/FrameWork_GetFieldEnumByField
params:{FieldExplainField,FieldEnumStatus}
*/
// 记录用户行为的方法 每个页面的onUnload里面要调用
function addUserBehaviorNew(obj) {
var pages = getCurrentPages() // 获取加载的页面
let len = pages.length
if (len) {
var currentPage = pages[len - 1] // 获取当前页面的对象
var nowRoute = '/' + currentPage.route // 当前页面url
if (obj) {
obj.outtoRoute = (obj.outtoRoute === '' || obj.outtoRoute) ? obj.outtoRoute : nowRoute
obj.intoRoute = obj.intoRoute ? obj.intoRoute.split('?')[0] : ''
} else {
obj = {}
obj.outtoRoute = nowRoute
obj.intoRoute = len > 1 ? '/' + pages[len - 2].route : '/pages/index/index'
}
}
obj.visitChannels = store.state.visitChannels
let userDate = store.state.userData
console.log('userDate123',userDate)
let baseInfo = uni.getStorageSync('userInfo')
let req = {
userName:userDate.UserName,
phoneNumber:userDate.Membership_Phone,
userId:userDate.UserId ? userDate.UserId:'',
wechatAppId:'wxa99ef047735c031e',
intoRoute:obj.intoRoute,
outtoRoute:obj.outtoRoute,
visitChannels:obj.visitChannels,
behaviorRecordDesc:'',
LoginIP: baseInfo.ip || '',
LoginPlace: (baseInfo.prov ? baseInfo.prov : '' ) + (baseInfo.prov && baseInfo.city ? '-' : '') + (baseInfo.city ? baseInfo.city : ''),
SOURCE_PLATFORM: '驿行畅旅'
}
console.log('req',req)
request.$webGet('CommercialApi/UserBehavior/AddUserBehavior',req).then(() => {
})
}
async function getFieldEnumByField(params) {
if (!params.FieldExplainField) return null
// 缓存了上次请求的数据 如果字段一致 则直接返回缓存数据 否则请求
// 可优化:根据有效期判断是否再次请求
if (!this.dataMap) {
this.dataMap = {}
}
if (this.dataMap[params.FieldExplainField]) {
return this.dataMap[params.FieldExplainField]
}
const data = await request.$webGet('EShangApiMain/FrameWork/GetFieldEnumByField', params)
if (data.Result_Code == 100) {
let typeMap = {}
data.Result_Data.List.map(n => {
typeMap[n.value] = n.label
})
this.dataMap[params.FieldExplainField] = typeMap
return typeMap
}
}
// 不四舍五入 保留两位小数的金额化方法
function getMoney(money){
if (!money || isNaN(money)) return "0.00";
let num = parseFloat(money + '') + '';
num = parseInt(money * 100 + '') / 100 + ''
let reg = /(-?\d+)(\d{3})/;
while (reg.test(num)) {
num = num.replace(reg, "$1,$2");
}
let idx = num.indexOf('.')
if (idx === -1) {
num = num + '.00'
}
if (idx > 0) {
let num_per = num.substring(0, idx) + '.'
let num_next = num.substring(idx + 1).padEnd(2, '0')
num = num_per + num_next
}
return num;
}
function getMoneyTest(money){
console.log('money',money)
if (!money || isNaN(money)) return "0.00";
let realMoney = 0
if(money.toString().indexOf('.')>0){
let num_per = money.toString().substring(0, money.toString().indexOf('.'))
let num_next = money.toString().substring(money.toString().indexOf('.') + 1).padEnd(2, '0')
console.log('num_per',num_per)
console.log('num_next',num_next)
realMoney = Number(num_per + '.' + num_next).toFixed(2)
}else{
realMoney = money
}
console.log('realMoney',realMoney)
let num = realMoney
// let num = parseFloat(realMoney + '') + '';
// num = (parseInt(realMoney * 100 + '') / 100).toFixed(2) + ''
console.log('num',num)
let reg = /(-?\d+)(\d{3})/;
while (reg.test(num)) {
num = num.replace(reg, "$1,$2");
}
let idx = num.indexOf('.')
console.log('idx',idx)
if (idx === -1) {
num = num + '.00'
}
if (idx > 0) {
let num_per = num.substring(0, idx) + '.'
let num_next = num.substring(idx + 1).padEnd(2, '0')
console.log('num_per',num_per)
console.log('num_next',num_next)
num = num_per + num_next
}
return num;
}
// 视频播放
const EZUIPlayer = require('./ezuikit.js');
function playVideo(opt) {
return new EZUIPlayer(opt)
}
export default {
netChange,
cutDate,
fmoney,
changeStringToDate,
toNextRoute,
addUserBehavior,
addUserBehaviorNew,
getMoney,
getMoneyTest,
getFieldEnumByField, // 获取枚举参数
// calculateDistance,
// bMapToQQMap,
playVideo
}