330 lines
8.8 KiB
TypeScript
330 lines
8.8 KiB
TypeScript
import CryptoJS from 'crypto-js';
|
||
import { Uni } from '@dcloudio/uni-app'
|
||
declare const uni : Uni
|
||
|
||
/**
|
||
* 将分转换为元(保留2位小数,带千分位)
|
||
* @param cent 分为单位的金额
|
||
* @returns 元为单位的金额字符串(带千分位)
|
||
*/
|
||
export const centToYuanWithComma = (cent : number) : string => {
|
||
if (!cent && cent !== 0) return '0.00'
|
||
return (cent / 100).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
|
||
}
|
||
|
||
/**
|
||
* 将秒转换为小时(保留2位小数)
|
||
* @param seconds 秒数
|
||
* @returns 小时数(字符串格式,保留2位小数)
|
||
*/
|
||
export const secondsToHours = (seconds : number) : string => {
|
||
if (!seconds && seconds !== 0) return '0.00'
|
||
return (seconds / 3600).toFixed(2)
|
||
}
|
||
|
||
|
||
|
||
|
||
// 检查app是否开启了通知权限 安卓苹果通用
|
||
export const checkNotificationAuthorized = () => {
|
||
const notificationAuthorized = uni.getAppAuthorizeSetting().notificationAuthorized
|
||
if (notificationAuthorized !== 'authorized') {
|
||
uni.showModal({
|
||
title: '通知权限',
|
||
content: '您还没有开启通知权限,无法接受到消息通知,请前往设置!',
|
||
confirmText: '去设置',
|
||
showCancel: false,
|
||
success: (res) => {
|
||
if (res.confirm) uni.openAppAuthorizeSetting()
|
||
},
|
||
})
|
||
}
|
||
}
|
||
|
||
|
||
|
||
// 监听消息推送
|
||
export const pushListener = () => {
|
||
//收到透传消息
|
||
//只有APP在线时,才会触发receive事件,透传消息不会触发系统消息,需要创建本地消息
|
||
plus.push.addEventListener(
|
||
'receive',
|
||
function (msg) {
|
||
console.log('111')
|
||
console.log('(receive):' + JSON.stringify(msg))
|
||
if (plus.os.name == 'Android') {
|
||
plus.push.createMessage(msg.content, msg.payload, {
|
||
title: msg.title,
|
||
})
|
||
if (msg.payload.audio) {
|
||
audioPlayer(msg.payload.audio)
|
||
}
|
||
// getApp().globalData.msgReadNum++
|
||
// plus.runtime.setBadgeNumber(getApp().globalData.msgReadNum)
|
||
} else if (plus.os.name == 'iOS') {
|
||
// ios
|
||
if (msg.aps == null && msg.type == 'receive') {
|
||
var option = {
|
||
cover: true,
|
||
title: msg.title,
|
||
}
|
||
plus.push.createMessage(msg.payload.body, msg.payload, option)
|
||
// getApp().globalData.msgReadNum++
|
||
// plus.runtime.setBadgeNumber(getApp().globalData.msgReadNum)
|
||
}
|
||
}
|
||
},
|
||
false,
|
||
)
|
||
|
||
//消息点击事件
|
||
//【APP在线】,收到透传消息通过,不会提醒至通知栏目,需要发送本地消息,再进行点击触发的点击事件。
|
||
//【APP离线】,收到离线透传消息,必须通过Java后台的Intent字符串携带payload,且符合格式才能触发click事件,格式不符合不会触发。
|
||
plus.push.addEventListener(
|
||
'click',
|
||
function (msg) {
|
||
console.log('2222')
|
||
console.log('(click):' + JSON.stringify(msg))
|
||
if (plus.os.name == 'iOS') {
|
||
//如果是IOS
|
||
var payload
|
||
if (msg.type == 'click') {
|
||
//APP离线点击包含click属性,这时payload是JSON对象
|
||
payload = msg.payload
|
||
} else {
|
||
//APP在线,收到消息不会包含type属性,这时的payload是JSON字符串,需要转为JSON对象
|
||
payload = JSON.parse(msg.payload)
|
||
}
|
||
if (payload != null || payload != undefined) {
|
||
var messageType = payload.messageType
|
||
// messageClick(messageType, payload);
|
||
}
|
||
}
|
||
if (plus.os.name == 'Android') {
|
||
console.log('Android', msg.payload)
|
||
if (msg.payload) {
|
||
uni.navigateTo({
|
||
url: msg.payload.url,
|
||
})
|
||
}
|
||
}
|
||
},
|
||
false,
|
||
)
|
||
}
|
||
|
||
/*
|
||
获取城市编码
|
||
*/
|
||
export const getCityCode = async (longitude : number, latitude : number) : Promise<any> => {
|
||
const apiKey = '' // 高德地图 API Key
|
||
const url = `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${longitude},${latitude}&output=json`
|
||
|
||
return new Promise((resolve, reject) => {
|
||
uni.request({
|
||
url,
|
||
success: (res) => {
|
||
console.log(res.data, 'res.data')
|
||
if (res.data && res.data.regeocode && res.data.regeocode.addressComponent) {
|
||
// console.log(res.data.regeocode.addressComponent,'res.data.regeocode.addressComponent');
|
||
const cityCode = res.data.regeocode.addressComponent.citycode // 获取城市编码
|
||
resolve({ data: res.data, cityCode })
|
||
} else {
|
||
reject('无法获取当前城市位置')
|
||
}
|
||
},
|
||
fail: (err) => {
|
||
console.error('获取城市位置失败:', err)
|
||
reject(err)
|
||
},
|
||
})
|
||
})
|
||
}
|
||
|
||
|
||
// 检测小程序是否更新
|
||
export const VersionUpdate = () => {
|
||
// 判断应用的 getUpdateManager 是否在当前版本可用
|
||
console.log(uni.canIUse('getUpdateManager'));
|
||
if (uni.canIUse('getUpdateManager')) {
|
||
const updateManager = uni.getUpdateManager()
|
||
// 向小程序后台请求完新版本信息
|
||
updateManager.onCheckForUpdate(function (res) {
|
||
if (res.hasUpdate) {
|
||
//小程序有新版本,静默下载新版本,新版本下载完成
|
||
updateManager.onUpdateReady(function () {
|
||
//模态弹窗(确认、取消)
|
||
uni.showModal({
|
||
title: '更新提示',
|
||
content: '小程序已发布新版本,是否重启?',
|
||
success: function (res) {
|
||
//用户点击确定
|
||
if (res.confirm) {
|
||
//当新版本下载完成,调用该方法会强制当前小程序应用上新版本并重启
|
||
updateManager.applyUpdate()
|
||
}
|
||
//用户点击取消
|
||
else if (res.cancel) {
|
||
//强制用户更新,弹出第二次弹窗
|
||
uni.showModal({
|
||
title: '提示',
|
||
content: '小程序已发布新版本,是否重启',
|
||
showCancel: false, //隐藏取消按钮
|
||
success: function (res) {
|
||
//第二次提示后,强制更新
|
||
if (res.confirm) {
|
||
// 当新版本下载完成,调用该方法会强制当前小程序应用上新版本并重启
|
||
updateManager.applyUpdate()
|
||
} else if (res.cancel) {
|
||
//重新回到版本更新提示
|
||
VersionUpdate()
|
||
}
|
||
},
|
||
})
|
||
}
|
||
},
|
||
})
|
||
})
|
||
// 当新版本下载失败
|
||
updateManager.onUpdateFailed(function () {
|
||
uni.showModal({
|
||
title: '提示',
|
||
content: '请您删除当前小程序,重新打开小程序',
|
||
})
|
||
})
|
||
}
|
||
})
|
||
} else {
|
||
// 提示用户在最新版本的客户端上体验
|
||
uni.showModal({
|
||
title: '温馨提示',
|
||
content: '当前微信版本过低,可能无法使用该功能,请升级到最新版本后重试。',
|
||
})
|
||
}
|
||
}
|
||
|
||
/*
|
||
base64编码
|
||
*/
|
||
export const base64_encrypt = (data : String) => {
|
||
return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data))
|
||
}
|
||
|
||
/*
|
||
base64解码
|
||
*/
|
||
export const base64_decrypt = (cipher : any) => {
|
||
return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8)
|
||
}
|
||
|
||
/*
|
||
md5加密
|
||
*/
|
||
export const md5 = (data : String) => {
|
||
return CryptoJS.MD5(data).toString()
|
||
}
|
||
|
||
/**
|
||
* 节流函数:规定时间内只执行一次
|
||
* @param fn 需要执行的函数
|
||
* @param delay 延迟时间(ms)
|
||
* @returns 节流后的函数
|
||
*
|
||
* // 使用示例
|
||
import { throttle } from '@/utils/common'
|
||
|
||
// 在setup中使用
|
||
const handleClick = throttle(() => {
|
||
// 你的业务逻辑
|
||
console.log('点击事件被触发')
|
||
}, 500)
|
||
|
||
// 在模板中使用
|
||
<button @click="handleClick">点击</button>
|
||
*/
|
||
export const throttle = (fn : Function, delay : number = 500) : Function => {
|
||
let timer : number | null = null;
|
||
let lastTime : number = 0;
|
||
|
||
return function (this : any, ...args : any[]) {
|
||
const currentTime = Date.now();
|
||
|
||
if (!lastTime) {
|
||
lastTime = currentTime;
|
||
}
|
||
|
||
if (currentTime - lastTime >= delay) {
|
||
fn.apply(this, args);
|
||
lastTime = currentTime;
|
||
} else {
|
||
if (timer) {
|
||
clearTimeout(timer);
|
||
}
|
||
timer = setTimeout(() => {
|
||
fn.apply(this, args);
|
||
lastTime = Date.now();
|
||
}, delay - (currentTime - lastTime));
|
||
}
|
||
};
|
||
};
|
||
|
||
/**
|
||
* 防抖函数:在一定时间内,多次触发同一个函数,只执行最后一次
|
||
* @param fn 需要执行的函数
|
||
* @param delay 延迟时间(ms)
|
||
* @returns 防抖后的函数
|
||
*
|
||
* // 使用示例
|
||
import { debounce } from '@/utils/common'
|
||
|
||
// 在setup中使用
|
||
const handleSearch = debounce((value: string) => {
|
||
// 你的搜索逻辑
|
||
console.log('搜索:', value)
|
||
}, 300)
|
||
|
||
// 在模板中使用
|
||
<input @input="handleSearch" />
|
||
*/
|
||
export const debounce = (fn : Function, delay : number = 500) : Function => {
|
||
let timer : number | null = null;
|
||
|
||
return function (this : any, ...args : any[]) {
|
||
if (timer) {
|
||
clearTimeout(timer);
|
||
}
|
||
timer = setTimeout(() => {
|
||
fn.apply(this, args);
|
||
}, delay);
|
||
};
|
||
};
|
||
|
||
|
||
|
||
function getBaseUrl() {
|
||
// @ts-ignore
|
||
return uni.$globalData?.BASE_URL + 'v1/upload'
|
||
}
|
||
|
||
export const fileUpload = (data : any) => {
|
||
uni.showLoading({
|
||
title: '上传中...'
|
||
})
|
||
return new Promise((resolve, reject) => {
|
||
uni.uploadFile({
|
||
url: getBaseUrl(),
|
||
filePath: data,
|
||
name: 'file',
|
||
method: 'POST',
|
||
header: {
|
||
'Authorization': 'Bearer ' + uni.$store.state.token
|
||
},
|
||
success: (res) => {
|
||
resolve(JSON.parse(res.data).data.filePath);
|
||
},
|
||
complete:() =>{
|
||
uni.hideLoading()
|
||
}
|
||
});
|
||
})
|
||
} |