import Vue from 'vue' // 工具函数错误处理包装器 function withErrorHandler(fn, fallback = null) { try { return fn(); } catch (error) { console.error('工具函数执行错误:', error); return fallback; } } // 异步操作超时包装器 function withTimeout(promise, timeoutMs = 10000) { return Promise.race([ promise, new Promise((_, reject) => setTimeout(() => reject(new Error('操作超时')), timeoutMs) ) ]).catch(err => { if (err.message === '操作超时') { console.warn('操作超时,自动忽略'); } throw err; }); } function setBar() { // 使用异步方式获取系统信息,避免阻塞 uni.getSystemInfoAsync ? uni.getSystemInfoAsync({ success: handleSystemInfo, fail: () => { // 默认值处理 Vue.prototype.StatusBar = 20; Vue.prototype.CustomBar = 64; } }) : uni.getSystemInfo({ success: handleSystemInfo, fail: () => { Vue.prototype.StatusBar = 20; Vue.prototype.CustomBar = 64; } }); } function handleSystemInfo(e) { // #ifndef MP Vue.prototype.usePort = 'h5'; Vue.prototype.StatusBar = e.statusBarHeight || 20; if (e.platform == 'android') { Vue.prototype.CustomBar = (e.statusBarHeight || 0) + 50; } else { Vue.prototype.CustomBar = (e.statusBarHeight || 0) + 45; }; // #endif // #ifdef MP-WEIXIN Vue.prototype.usePort = 'wechat'; Vue.prototype.StatusBar = e.statusBarHeight || 20; withErrorHandler(() => { let custom = wx.getMenuButtonBoundingClientRect(); Vue.prototype.Custom = custom; Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight; }); // #endif // #ifdef MP-ALIPAY Vue.prototype.StatusBar = e.statusBarHeight || 20; Vue.prototype.CustomBar = (e.statusBarHeight || 0) + (e.titleBarHeight || 0); // #endif } function setLink(systemclient = "marketingtool") { return Vue.prototype.qrCodePrefix = 'https://meida.cnyunl.com'; } function mount() { Vue.prototype.getLocation = (isHighAccuracy = false) => { return new Promise((resolve, reject) => { let that = this; handle() function handle() { uni.getLocation({ isHighAccuracy, highAccuracyExpireTime: isHighAccuracy ? 8000 : '', success: res => { console.log("获取定位", res) resolve(res) }, fail: err => { console.log("获取位置失败", err) uni.hideLoading(); if (["getLocation:fail 系统错误,错误码:-13000,meet frequency limit, please slowdown and try again later", "getLocation:fail auth deny"].includes(err.errMsg)) return resolve(); query() } }) } function query() { uni.getSetting({ success({ authSetting }) { if (authSetting['scope.userLocation']) { handle() } else { uni.showModal({ title: '提示', content: '需要获取您的地理位置,请确认授权,否则可能会定位门店不准确', cancelText: '下次再说', confirmText: '前去授权', success: ({ confirm }) => { if (confirm) { uni.openSetting({ success(res) { if (res.authSetting['scope.userLocation']) handle(); } }) } else { /* uni.showToast({ title: "您未授权地理位置,", icon: "none", }) */ resolve(); } } }) } } }) } }) }; Vue.prototype.cutoff = (msg, title = "", mask = false, exitTime = 0, icon = 'none', duration = 2000,) => { if (msg != '成功' || title) uni.showToast({ title: msg == '成功' ? title : msg, duration, icon, mask: mask || exitTime != 0 }) if (exitTime && msg == '成功') setTimeout(uni.navigateBack, exitTime) return msg != '成功'; }; Vue.prototype.paging = (content, init, update) => { if (update) { console.log("分页", content, init, update) let content1 = JSON.parse(JSON.stringify(content)); content1.pageSize = (content1.pageNumber - 1) * content1.pageSize; content1.pageNumber = 1; return content1 } else { if (content.pageTotal == undefined || !content.pageTotal) content.pageTotal = 1; if (content.pageNumber == undefined || !content.pageNumber) content.pageNumber = 1; if (content.pageSize == undefined || !content.pageSize) content.pageSize = 20; if (init) content.pageNumber = 1; return content.pageNumber > content.pageTotal; } } Vue.prototype.tovw = (num) => (num * 100 / 375).toFixed(3) + "vw"; Vue.prototype.getCity = (obj, isAll = true) => obj.province + obj.city + obj.county + (isAll ? obj.address : ''); Vue.prototype.getApps = (appRemark, route) => { const list = Object.values(uni.getStorageSync('authList')[appRemark]) return route ? list.find(v => v.path == route || v.pathDetail == route) : list }; Vue.prototype.getHeight = (even, that, calculate = true) => { return new Promise((resolve, reject) => { if (calculate) { uni.getSystemInfo({ success(s) { uni.createSelectorQuery().in(that).select(even).boundingClientRect().exec(res => (!res[0]) ? reject('没有查询到元素') : resolve(s.windowHeight - res[0].bottom)) } }); } else { uni.createSelectorQuery().in(that).select(even).boundingClientRect().exec(res => (!res[0]) ? reject('没有查询到元素') : resolve(res[0])) } }) }; //compressed压缩图;thumbnail缩略图,hls转码视频,cover封面 //maxSizeKB: 最大图片大小阈值(KB),默认200KB,大于此值则使用缩略图 Vue.prototype.getSpecifiedImage = (item, type = 'thumbnail', maxSizeKB = 500) => { if (!item) return ""; if (!item.subfiles || !item.subfiles.length) return item.url || ""; // 如果原图存在且大小小于等于阈值,使用原图 if (item.url && item.contentlength && item.contentlength <= maxSizeKB * 1024) { return item.url; } // 在 subfiles 中查找,优先级:compressed > thumbnail const priorityTypes = ['compressed', 'thumbnail']; let targetTypes = type === 'compressed' ? ['compressed'] : priorityTypes; for (const t of targetTypes) { const v = item.subfiles.find(v => v.type == t); if (v && v.url) return v.url; } return item.url || ""; } // 专门处理视频文件的函数:优先取hls,若未取到取原本的url Vue.prototype.getVideoUrl = (item) => { if (!item) return item; item.customCache = true; // 优先查找hls格式 if (item.subfiles && item.subfiles.length > 0) { const hlsFile = item.subfiles.find(v => v.type == 'hls'); if (hlsFile && hlsFile.url) { item.customCache = false; item.url = hlsFile.url; return item; } } return item; } Vue.prototype.formatTime = (date = new Date(), j1 = '-', j2 = ':') => { const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const second = date.getSeconds() const formatNumber = n => { n = n.toString() return n[1] ? n : `0${n}` } return `${[year, month, day].map(formatNumber).join(j1)} ${[hour, minute, second].map(formatNumber).join(j2)}` } Vue.prototype.getCustomClass = (typename) => { return new Promise((resolve, reject) => { Vue.prototype.$Http.basic({ "classname": "sysmanage.develop.optiontype.optiontype", "method": "optiontypeselect", "content": { typename } }).then(res => { console.log("获取自定义分类" + typename, res) if (res.msg != '成功') return resolve([]); resolve(res.data); }) }) } Vue.prototype.CNY = (sum, symbol = '¥', strict = true, precision = 2) => { const currency = require("./currency.js"); let num = currency(sum, { symbol, precision }).format(); if (strict) { let decimals = num.split("."); decimals[1] = ('0.' + decimals[1] - 0 + '').substring(2) num = decimals[1] ? decimals.join(".") : decimals[0] } return num } Vue.prototype.callPhone = phoneNumber => { uni.makePhoneCall({ phoneNumber: phoneNumber + '', complete: res => { console.log('makePhoneCall', res) } }) } Vue.prototype.dye = (list, colors, num = 2) => { let count = num - 1, index = 0; return list.map((v, i) => { if (i > count) { count += num; index += 1; } v.color = colors[index % colors.length] return v }) } Vue.prototype.getReg = name => { let obj = { phonenumber: { reg: '^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}$', errText: "请输入正确的11位手机号码!" }, email: { reg: '^([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,4})$', errText: "请输入正确的邮箱格式!" } } return obj[name] || '' } Vue.prototype.daysAgo = num => { let now = new Date().getTime() - 0, end = now + 86400000, beg = end - (num * 86400000); return { begindate: Vue.prototype.formatTime(new Date(beg)).split(' ')[0], enddate: Vue.prototype.formatTime(new Date(end)).split(' ')[0], } } Vue.prototype.getUrlParams = urlStr => { const url = decodeURIComponent(urlStr) let obj = {} let str = url.slice(url.indexOf('?') + 1), arr = str.split('&'); obj.funName = url.slice(0, url.indexOf('?')).split("/").pop(); for (let j = arr.length, i = 0; i < j; i++) { let arr_temp = arr[i].split('=') obj[arr_temp[0]] = arr_temp[1] } return obj } Vue.prototype.switchPage = app => { if (app.path) { uni.navigateTo({ url: app.path, fail: (fail) => { console.log("跳转失败原因", fail) } }) } else { if (app.name == 'index_design') { app.name = 'design'; } else if (['index_6C', 'index_freeDesign'].includes(app.name)) { app.name = 'longText'; }; if (app.name == 'index_design') app.name = 'design'; switch (app.name) { case 'design': Vue.prototype.$Http.changePage("index", "案例", { active: '实景案例' }) break; case 'index_product': Vue.prototype.$Http.changePage("cloud", "单品") break; case 'index_commodity': Vue.prototype.$Http.changePage("index", "活动") break; case 'index_imgs': Vue.prototype.$Http.changePage("index", "案例", { active: '图库' }) break; case 'index_dataBank': Vue.prototype.$Http.changePage("cloud", "资料库") break; case 'index_school': Vue.prototype.$Http.changePage("cloud", "商学院") break; case 'index_video': Vue.prototype.$Http.changePage("index", "视频") break; case 'index_cloud': Vue.prototype.$Http.changePage("cloud", "工作台") break; case 'longText': if (app.forms.path) { uni.navigateTo({ url: app.forms.path.formcols[0].title }) } else { console.log("长图文", app) } break; default: console.log("未配置路径", app.name) break; } } console.log(app); } Vue.prototype.isInitializeLogin = (fun) => { const systemInitIsComplete = getApp().globalData.systemInitIsComplete; if (!systemInitIsComplete || typeof systemInitIsComplete == 'object') { getApp().globalData.HomePageStartRendering.push(fun) } else { fun() } } const accountInfo = uni.getAccountInfoSync(); Vue.prototype.isShow = accountInfo.miniProgram.envVersion.includes('tri'); Vue.prototype.attinfosType = (postfix) => { postfix = postfix.toLowerCase() if (['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'tiff', 'tga', 'psd', 'svg', 'ico'].includes(postfix)) { return '图片' } else if (postfix == 'mp4' || postfix == 'avi' || postfix == 'mov' || postfix == 'wmv' || postfix == 'flv' || postfix == 'mkv') { return '视频' } else if (postfix == 'docx' || postfix == 'doc' || postfix == 'xlsx' || postfix == 'xls' || postfix == 'pptx' || postfix == 'ppt' || postfix == 'pdf' || postfix == 'txt') { return '文档' } else if (postfix == 'richtext') { return '图文' } else { return '文档' } } } module.exports = { mount, setBar, setLink }