emis-app/common/untool.js
2024-10-09 15:46:21 +08:00

359 lines
7.0 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 qs from "@/common/libs/qs"
// #ifdef H5
import { saveAs } from "file-saver"
// #endif
// #ifdef APP-PLUS
const appCloudScanner = uni.requireNativePlugin('Ba-Scanner');
// #endif
const tabBarUrls = [
'/pages/tabBar/deal/deal',
'/pages/tabBar/home/home',
'/pages/tabBar/mine/mine',
'/pages/tabBar/order/order'
]
const goto = (url, type = 1)=> {
if(!url) {
console.error("goto 缺少入参 url=========")
return
}
url = url.replace(`/pages/`, '')
url = url.replace(`pages/`, '')
url = `/pages/${url}`
if(tabBarUrls.filter(t=> url.indexOf(t) > -1).length > 0) {
// tabBar 使用 reLaunch切换,防止页面不刷新
return uni.reLaunch({
url
});
}
if (type == 1){
uni.navigateTo({
url
});
} else if (type == 2){
uni.redirectTo({
url
});
}
}
const goBack = (opt = {})=> {
uni.navigateBack({
fail: ()=>{
goto(opt._finalUrl || `tabBar/home/home`, 2)
},
...opt,
})
}
const reLaunch = (opt = {})=> {
uni.reLaunch(opt)
}
const setClipboardData = (val)=> {
uni.setClipboardData({
data: val,
success: () => {
showToast('复制成功')
},
})
}
const showToast = (val)=> {
uni.showToast({ title: val, icon: 'none' })
}
const confirmModal = (title, opt = {}) => {
return new Promise((resolve)=> {
uni.showModal({ content: title, confirmColor: '#B12D29', ...opt }).then((res)=> {
if(res.confirm) {
resolve(true)
} else {
resolve(false)
}
})
})
}
const showLoading = (title)=> {
uni.showLoading({
mask: true,
title: title || '加载中'
});
}
const hideLoading = ()=> {
uni.hideLoading();
}
const customAppScanCode = ({resolve, reject})=> {
appCloudScanner.onScan(
{
// isContinuous: true,
barcodeFormats: [
// "QR Code"
],
// scanTimeSpace: 2000,
// isShowVibrate: true,
// isShowBeep: false,
hintText: '扫码',
},
(res) => {
console.log("scanCode res========", res)
let code = res.result
if (code) {
// 去除 扫码多出来的特殊字符
code = code.replace(//g, '')
resolve(code)
}
}
);
}
const scanCode = ()=> {
return new Promise((resolve, reject)=> {
// #ifdef APP-PLUS
customAppScanCode({resolve, reject})
// #endif
// #ifndef APP-PLUS
uni.scanCode({
onlyFromCamera: false,
success: (res) =>{
console.log("scanCode res========", res)
resolve(res.result)
},
fail: reject
})
// #endif0
})
}
const makePhoneCall = (phoneNumber)=> {
uni.makePhoneCall({
phoneNumber: phoneNumber
});
}
const downloadFile = (url, ext = {})=> {
return new Promise((resolve, reject)=> {
uni.downloadFile({
url: url,
...ext,
success: (res) => {
console.log("downloadFile:success:res======", res)
if (res.statusCode === 200 || res.statusCode === 400) {
console.log('下载成功');
resolve(res)
} else {
reject('下载失败')
}
},
fail: (err)=>{
console.log("downloadFile:err", err)
reject(err)
}
});
})
}
const saveNetFile = ({ url, header } = {}) => {
return new Promise(async (resolve, reject) => {
showLoading('正在保存文件')
console.log("下载文件====", url)
try {
let dRes = await downloadFile(url, { header })
console.log("saveNetFile:downloadFile==", dRes)
let {
tempFilePath,
path
} = dRes
path = path || tempFilePath
// #ifdef H5
saveAs(path)
// #endif
// let res = await saveFile({ path })
// #ifdef APP-PLUS
plus.io.convertLocalFileSystemURL(path);
plus.runtime.openFile(path); //选择软件打开文件
// #endif
// #ifdef MP-WEIXIN
await uniPromiseApi('openDocument', { filePath: path, showMenu: true, })
// #endif
hideLoading()
showToast('保存成功')
setClipboardData(url)
resolve(tempFilePath)
} catch (e) {
hideLoading()
showToast('保存失败')
reject(e)
}
})
}
const saveFile = ({ tempFilePath })=> {
return new Promise(async (resolve, reject)=> {
//保存到本地
uni.saveFile({
tempFilePath,//文件的临时路径
success: function(res) {
console.log("saveFile:success", res)
resolve(res)
},
fail: function(err) {
console.log("saveFile:err", err)
reject(err)
},
complete(res){
console.log("saveFile:complete", res)
}
});
})
}
const getImageInfo = (src)=> {
return new Promise(async (resolve, reject)=> {
uni.getImageInfo({
src,
success(res) {
resolve(res)
},
fail(e) {
console.log("获取图片信息失败=======", e)
reject(e)
}
})
})
}
const getImageTempFilePath = (options) => {
return new Promise(async (resolve, reject) => {
let { url, reqHeader, param } = options
if(param) {
let qsStr =qs.stringify(param)
url += `${url.indexOf("?")>-1?'&':'?'}${qsStr}`
}
let res = await downloadFile(url, { header: reqHeader })
resolve(res.tempFilePath)
})
}
const canvasGetImageData = (params = {})=> {
return new Promise((resolve, reject)=> {
uni.canvasGetImageData({
x: 0,
y: 0,
...params,
success(res) {
console.log("img====",res);
resolve(res)
if(res.data) {
let data = res.data
resolve(res);
} else {
showToast('canvasGetImageData:失败')
reject('canvasGetImageData:失败')
}
},
fail(err){
showToast('canvasGetImageData:失败')
console.log("canvasGetImageData:失败====", err);
}
})
})
}
const uniPromiseApi = (name, options = {}, extObj = { })=> {
return new Promise((resolve, reject)=> {
if(!(uni?.[name])) {
console.error(`uni.${name} api不存在 `)
return reject(`uni.${name} api不存在`)
}
uni?.[name]?.({
...options,
success(res){
console.log(`uni.${name} -execResult:success====`, res)
if(extObj.successText) {
showToast(successText)
}
resolve({ res })
},
fail(err){
console.error(`uni.${name} -execResult:fail====`, err)
if(extObj.failText) {
showToast(failText)
}
resolve({ err })
}
})
})
}
const promiseTimeout = (time = 300) => {
return new Promise((resolve, reject)=> {
setTimeout(()=> {
resolve()
}, time)
})
}
const setNavigationBarTitle = (title)=> {
uni.setNavigationBarTitle({
title
})
}
const reloadCurrentPage = (_thisPage)=> {
let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
let curPage = routes[routes.length - 1] // 获取当前页面路由,也就是最后一个打开的页面路由
_thisPage = curPage || _thisPage
let { fullPath } = _thisPage.$page
goto(fullPath, 2)
}
const playAudio = (src)=> {
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
innerAudioContext.src = src
innerAudioContext.onPlay(() => {
console.log('开始播放===');
});
innerAudioContext.onError((res) => {
console.log("playAudio onError ======", res);
});
}
export {
reLaunch,
goto,
goBack,
setClipboardData,
confirmModal,
showLoading,
hideLoading,
showToast,
scanCode,
makePhoneCall,
downloadFile,
saveNetFile,
saveFile,
getImageTempFilePath,
canvasGetImageData,
getImageInfo,
uniPromiseApi,
promiseTimeout,
setNavigationBarTitle,
reloadCurrentPage,
playAudio
}