yfs/common/common.js
2025-06-16 21:30:14 +08:00

643 lines
13 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.

/*
* @Date: 2023-11-13 15:46:51
* @LastEditTime: 2024-01-17 17:20:50
* @Description: content
*/
import Vue from 'vue'
import config from '@/common/config.js'
import { navigateTo as routerNavigateTo, navigateBack as routerNavigateBack } from '@/common/router.js'
// 防止处理多次点击
function noMultipleClicks(methods, info) {
// methods是点击后需要执行的函数 info是函数需要传的参数
let that = this
if (that.noClick) {
// 第一次点击
that.noClick = false
if ((info && info !== '') || info == 0) {
// info是执行函数需要传的参数
methods(info)
} else {
methods()
}
setTimeout(() => {
that.noClick = true
}, 2000)
} else {
// 这里是重复点击的判断
}
}
//导出
export default {
data: {
loading: false,
timer: null
},
noMultipleClicks, // 禁止多次点击
/* 获取日期 */
getDateTime() {
const date = new Date()
const year = date.getFullYear().toString()
const monty = (date.getMonth() + 1).toString()
const day = date.getDate().toString()
return `${year}-${monty}-${day}`
},
/**
* 去除多余的0
* @param {*} numStr
* @returns
*/
removeTrailingZeros(numStr) {
// 判断传入参数是否为字符串,如果不是则转为字符串
if (typeof numStr !== 'string') {
numStr = String(numStr);
}
if (numStr.includes('.')) {
numStr = numStr.replace(/0+$/, ''); // 移除末尾的零
if (numStr.endsWith('.')) {
numStr = numStr.slice(0, -1); // 处理小数点后全零的情况
}
}
return numStr;
},
detailPageTitle(obj) {
if (!obj) {
return ''
}
let goods_info = config.getGoodTypeFind(obj.type);
if (goods_info != null) {
return goods_info.name;
}
const types = {
1: '一番赏',
2: '无限赏',
3: '擂台赏',
4: '抽卡机',
5: '积分赏',
6: '全局赏',
7: '福利盲盒',
8: '领主赏',
9: '连击赏'
}
const target = types[obj.type]
return target
},
navTo(item) {
switch (item.ttype) {
case 1:
/* 领券中心 */
this.to({
url: '/package/index/coupon-center',
query: {
coupon_id: item.coupon_id
}
})
break;
case 5: //达达券排行榜
console.log(item);
this.to({
url: item.url,
})
break;
}
if (item.goods_id > 0) {
if (item.ttype == 2) {
/* 一番赏 */
this.to({
url: '/pages/main/xq',
query: {
goods_id: item.goods_id
}
})
}
/* 无限赏 */
if (item.ttype == 3) {
this.to({
url: '/pages/main/xq_wx',
query: {
goods_id: item.goods_id
}
})
}
/* 连击赏 */
if (item.ttype == 4) {
this.to({
url: '/package/index/lian-ji',
query: {
goods_id: item.goods_id
}
})
}
}
},
/**
* @description: 微信支付(小程序)
* @param {*}
* @return {*}
*/
wxMpPay({
provider = 'weixin',
data
}) {
console.log('wxdata', data,this)
// #ifdef H5
console.log('进入h5支付', data)
return new Promise((resolve, reject) => {
WeixinJSBridge.invoke(
'getBrandWCPayRequest', data,
function (res) {
console.log('支付回调', res);
if (res.errMsg == 'requestPayment:fail cancel') {
uni.showToast({
title: '取消支付',
icon: 'none',
duration: 500,
success: () => {
/* 取消订单 */
}
})
resolve('cancel')
}
if (res.err_msg == "get_brand_wcpay_request:ok") {
// 使用以上方式判断前端返回,微信团队郑重提示:
//res.err_msg将在用户支付成功后返回ok但并不保证它绝对可靠。
uni.showToast({
title: '支付成功',
icon: 'success',
duration: 500,
success: () => {
resolve('success')
}
})
}
});
})
// #endif
// #ifdef MP-WEIXIN
return new Promise((resolve, reject) => {
uni.requestPayment({
provider,
...data,
success: res => {
// console.log(res)
},
fail: err => {
// console.log('common.wxMpPay-error', err)
},
complete: res => {
console.log('complete (res)', res)
if (res.errMsg == 'requestPayment:fail cancel') {
this.toast({
title: '取消支付',
icon: 'none',
duration: 500,
success: () => {
/* 取消订单 */
}
})
resolve('cancel')
}
if (res.errMsg == 'requestPayment:ok') {
this.toast({
title: '支付成功',
icon: 'success',
duration: 500,
success: () => {
resolve('success')
}
})
}
}
})
})
// #endif
},
/**
* @description: 规避连点
* @param {*}
* @return {*}
*/
noDouble(fun, data, loading = false) {
/**
* $common.noDouble(fun,data)
* fun 需要规避连点的方法
* data 该方法需要用到的参数
* loading 接口加载中状态
* 传入方法不要写括号
*/
/* 如果接口加载中,终止任何操作 */
if (loading) {
setTimeout(() => {
uni.showToast({
title: '请勿重复点击',
icon: 'none',
mask: false
})
}, 100)
return;
}
console.log("loadingloadingloadingloadingloading", loading);
loading = true;
console.log("loadingloadingloadingloadingloading", loading);
/* 如果定时器未结束 */
if (this.data.timer) {
setTimeout(() => {
uni.showToast({
title: '请勿重复点击',
icon: 'none',
mask: false
})
}, 100)
/* 清除之前的定时器 */
clearTimeout(this.data.timer)
/* 重新设置定时器 */
this.data.timer = setTimeout(() => {
this.data.timer = null
}, 200)
return
}
console.log(data && data)
/* 设置第一次点击的定时器 */
this.data.timer = setTimeout(() => {
this.data.timer = null
}, 200)
/* 如果有回调,使用回调并传入参数 */
fun && fun(data && data)
},
noDouble1(fun, data) {
/**
* $common.noDouble(fun,data)
* fun 需要规避连点的方法
* data 该方法需要用到的参数
* loading 接口加载中状态
* 传入方法不要写括号
*/
/* 如果接口加载中,终止任何操作 */
if (this.data.loading) {
uni.showToast({
title: '请勿重复点击',
icon: 'none',
mask: false
})
console.log("防抖", this.data.loading);
return;
}
this.data.loading = true;
try {
fun && fun(data && data);
} catch (e) {
//TODO handle the exception
}
var that = this;
setTimeout(() => {
that.data.loading = false;
console.log("方法执行结束", this.data.loading, this.data.loading);
}, 1000)
},
/**
* @description: tost提示
* @return {*}
*/
toast(opt) {
let title = opt.title || ''
let icon = opt.icon || 'none'
let mask = opt.mask || false
let duration = opt.duration || 1500
let position = opt.position || 'center'
setTimeout(() => {
uni.showToast({
title,
icon,
mask,
duration,
position,
success: () => {
if (opt.success) {
setTimeout(() => {
opt.success()
}, duration)
}
}
})
}, 100)
},
msg(msg) {
let title = msg || ''
let icon = 'none'
let mask = false
let duration = 1500
let position = 'center'
uni.showToast({
title,
icon,
mask,
duration,
position,
});
},
/**
* @description: 获取规则
* @param {*} type
* @return {*}
*/
getRule(id = '', loading = false) {
return new Promise((resolve, reject) => {
Vue.prototype.req({
url: 'danye',
Loading: !loading,
data: {
type: id
},
success: res => {
if (res.status == 1) {
if (res.data) {
res.data = res.data.replace(
/\<img/gi,
'<img style="width: 100%;vertical-align: middle;"'
)
}
resolve(res)
} else {
reject(res)
}
}
})
})
},
/**
* @description: 复制到剪切板
* @param {*} e
* @return {*}
*/
copy(e) {
uni.setClipboardData({
data: `${e}`
})
},
/**
* @description: obj转为queryString
* @param {*} e
* @return {*}
*/
qs(e) {
let str = Object.entries(e)
.map(([key, value]) => `${key}=${value}`)
.join('&')
return `?${str}`
},
/**
* @description: 跳转页面
* @param {*} type 跳转类型 1 navigate,2 redirect,3 switch,4 relaunch
* @param {*} url
* @param {*} query
* @return {*}
*/
to({
type = 1,
url,
query = {},
success,
fail,
complete
}) {
if (!url) {
this.toast({
title: '暂未开放'
})
return
}
// 确定跳转类型
let navigationType = 'navigateTo';
switch (type) {
case 2:
navigationType = 'redirectTo';
break;
case 3:
navigationType = 'switchTab';
break;
case 4:
navigationType = 'reLaunch';
break;
default:
navigationType = 'navigateTo';
}
// 使用导入的路由方法而不是this.$router
return routerNavigateTo(url, query, navigationType)
.then(res => {
if (typeof success === 'function') success(res);
return res;
})
.catch(err => {
if (typeof fail === 'function') fail(err);
throw err;
})
.finally(() => {
if (typeof complete === 'function') complete();
});
},
/**
* @description: 返回上一页
* @param {*} e
* @return {*}
*/
back(e) {
/* 判断传入的是否是数字 */
let delta = 1;
if (typeof e === 'number' && !isNaN(e)) {
delta = e;
}
// 使用导入的routerNavigateBack而不是this.$router
routerNavigateBack(delta)
.catch(() => {
// 如果返回失败,则回到首页
routerNavigateTo('/pages/main/index', {}, 'switchTab');
});
},
/**
* @description: 提取富文本文字
* @param {*} val
* @return {*}
*/
filterText(val) {
if (val) {
var replaceLbael = val.replace(/<[^>]+>/g, '')
return replaceLbael.replace(/&nbsp;/ig, '')
} else {
return ''
}
},
// 返回上一页
$navBack(num = 1, time = 0) {
// 页面返回
setTimeout(() => {
routerNavigateBack(num)
.catch(() => {
// 如果返回失败,则回到首页
routerNavigateTo('/pages/main/index', {}, 'reLaunch');
});
}, time * 1000)
},
/**
* 分享
* @param {Object} title
* @param {Object} desc
* @param {Object} link
* @param {Object} image
*/
$fenxiang(title, desc, link, image) {
// #ifdef H5
Vue.prototype.req({
url: 'getAccessTokenOffiaccountSign',
data: {
url: location.href.split('#')[0]
},
success: res => {
console.log(res);
if (res.status == 1) {
let _data = res.data;
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来若要查看传入的参数可以在pc端打开参数信息会通过log打出仅在pc端时才会打印。
appId: _data.appId,
timestamp: _data.timestamp,
nonceStr: _data.noncestr,
signature: _data.signature,
jsApiList: [
'checkJsApi',
'showMenuItems',
'updateAppMessageShareData',
'onMenuShareTimeline',
]
});
wx.ready(function () {
wx.checkJsApi({
jsApiList: [
'openAddress',
'onMenuShareTimeline',
],
success: function (res) {
if (link.indexOf('http:') < 0 &&
link.indexOf('https:') < 0) {
link = location.href.split('#')[0] + "#" + link;
}
// alert('a')
wx.updateAppMessageShareData({
title: title, // 分享标题
desc: desc, // 分享描述
link: link, // 分享链接该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: image, // 分享图标
success: function () {
// 设置成功
}
})
uni.setClipboardData({
data: `${link}`
})
// alert('a1')
// wx.showMenuItems({
// menuList: [
// "menuItem:share:appMessage",
// "menuItem:share:timeline",
// "menuItem:share:qq",
// ] // 要显示的菜单项所有menu项见附录3
// });
// alert('a3')
// wx.onMenuShareTimeline({
// title: title, // 分享标题
// link: link, // 分享链接该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
// imgUrl: image, // 分享图标
// success: function() {
// // 用户点击了分享后执行的回调函数
// alert('用户点击了分享后执行的回调函数')
// }
// })
}
});
});
wx.error(function (res) {
// config信息验证失败会执行error函数如签名过期导致验证失败具体错误信息可以打开config的debug模式查看也可以在返回的res参数中查看对于SPA可以在这里更新签名。
console.log("出现错误", res);
});
}
}
})
// #endif
},
nav(url) {
// 解析URL和参数
let urlPath = url;
let params = {};
if (url.includes('?')) {
const parts = url.split('?');
urlPath = parts[0];
// 解析参数
if (parts[1]) {
parts[1].split('&').forEach(param => {
const keyValue = param.split('=');
if (keyValue.length === 2) {
params[keyValue[0]] = decodeURIComponent(keyValue[1]);
}
});
}
}
// 使用导入的路由方法
return routerNavigateTo(urlPath, params);
},
red(url) {
uni.redirectTo({
url: url,
fail: () => {
uni.switchTab({
url: url
});
}
})
},
}