304 lines
7.8 KiB
JavaScript
Raw Normal View History

2025-06-06 15:17:30 +08:00
/*
* 各种工具方法
*
* @Alphaair
* 20190519 create.
**/
const { refreshMyToken } = require("./serve/user");
function uploadImageToAliyun(filePath) {
const fileName = `avatar/${Date.now()}_${Math.random().toString(36).substr(2, 9)}${filePath.match(/\.(\w+)$/)[1]}`;
const ossPath = `https://oss.console.aliyun.com/bucket/oss-cn-shanghai/yuedong-wechatapplet/object?path=Upload%2FUser%2Favater%2F/${fileName}`;
// 上传文件到阿里云 OSS
this.ossClient.put(fileName, filePath).then((result) => {
console.log('上传成功:', result);
return result;
// 可选:将头像 URL 保存到服务器或本地存储
}).catch((err) => {
console.error('上传失败:', err);
wx.showToast({
title: '上传失败',
icon: 'none',
duration: 2000
});
});
}
async function refreshToken() {
let token = wx.getStorageSync('token')
const res = await refreshMyToken(token)
if(res.data.token){
wx.setStorageSync('token', res.data.token)
2025-06-09 17:19:11 +08:00
wx.setStorageSync('roleId', res.data.role_Id)
2025-06-06 15:17:30 +08:00
}
}
2025-06-13 14:39:20 +08:00
/**
* 根据年月日获取星期几
* @param {number} year - 年份例如 2023
* @param {number} month - 月份1-12
* @param {number} day - 日期1-31
* @returns {string} 星期几的名称或错误信息
*/
function getWeekdayWithValidation(year, month, day) {
// 参数验证
if (typeof year !== 'number' || typeof month !== 'number' || typeof day !== 'number') {
return '参数必须是数字';
}
if (month < 1 || month > 12) {
return '月份必须在1到12之间';
}
if (day < 1 || day > 31) {
return '日期必须在1到31之间';
}
try {
const date = new Date(year, month - 1, day);
const weekday = date.getDay();
const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
return weekdays[weekday];
} catch (error) {
return '无效的日期';
}
}
2025-06-06 15:17:30 +08:00
function formatDate(date, format) {
if (!date)
return;
if (!format)
format = "yyyy-MM-dd";
switch (typeof date) {
case "string":
let reg = /^\/Date\((\-?\d+)\)\/$/;
if (reg.test(date)) {
let m = reg.exec(date);
date = parseInt(m[1]);
date = new Date(date);
} else if (date.indexOf('T') !== -1) {
//无时区时加入GMT+8
if (date.indexOf('+08:00') === -1)
date += '+08:00';
date = new Date(date);
} else {
date = new Date(Date.parse(date.replace(/-/g, "/")));
}
break;
case "number":
date = new Date(date);
break;
}
if (!date instanceof Date)
return;
let dict = {
"yyyy": date.getFullYear(),
"M": date.getMonth() + 1,
"d": date.getDate(),
"H": date.getHours(),
"m": date.getMinutes(),
"s": date.getSeconds(),
"MM": ("" + (date.getMonth() + 101)).substr(1),
"dd": ("" + (date.getDate() + 100)).substr(1),
"HH": ("" + (date.getHours() + 100)).substr(1),
"mm": ("" + (date.getMinutes() + 100)).substr(1),
"ss": ("" + (date.getSeconds() + 100)).substr(1)
};
return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g, function() {
return dict[arguments[0]];
});
}
/**
* 复制数组
*
* @param {Array} array 要复制克隆的数组
* @returns {Array} 复制好的数组
*/
function cloneArray(array) {
if (array instanceof Array === false)
return array;
let dest = array.map(item => {
if (item instanceof Array)
return cloneArray(item);
else if (item instanceof Date)
return item;
else if (typeof item === 'object')
return clone(item);
else
return item;
});
return dest;
}
/**
* 深拷贝对象
* @param {Object,Array} 要复制的源对象
* @param {Object} 合并的目前对象为空是新建对象
* */
function clone(source, dest) {
if (source instanceof Array)
return cloneArray(source);
if (!dest)
dest = {};
if (!source || typeof source !== 'object')
return null;
let keys = Object.keys(source);
keys.forEach(key => {
if (source[key] instanceof Array)
dest[key] = cloneArray(source[key]);
else if (source[key] instanceof Date)
dest[key] = source[key];
else if (typeof source[key] === 'object')
dest[key] = clone(source[key]);
else
dest[key] = source[key];
});
return dest;
}
/**
* 安全方式调用fn
*
* @param {Function} fn 要调用的方法
* @returns 如果fn存在则返回其引用否则返回一个空函数
*/
function invoke(fn) {
if (fn instanceof Function)
return fn;
return function() {};
}
/**
* 生成一个GUID
*
*/
function guid() {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
/**
* 判断obj是否为一个nullundefind''的空对象
* 而不是以!obj形式判断以增加安全性
*
* @param {Object} obj 接受判断的对象
*/
function isNone(obj) {
if (obj === null || obj === undefined || obj === '')
return true;
return false;
}
/**
* 判断arr是否为null或undefind或空数组
*
* @param {Object} arr 接受判断的数组
* @return {Boolean} true为空nullundefind)反之为false
*/
function isEmptyArray(arr) {
if (arr instanceof Array === false)
return true;
if (arr.length < 1)
return true;
return false;
}
/**
* 将秒数转换为 "HH:MM:SS" 格式的字符串
* @param {number} totalSeconds - 总秒数
* @returns {string} - 格式化后的时间字符串
*/
function formatTimeStr(totalSeconds) {
if (typeof totalSeconds !== 'number' || isNaN(totalSeconds)) {
throw new Error('请提供一个有效的数字');
}
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = Math.floor(totalSeconds % 60);
const formattedHours = String(hours).padStart(2, '0');
const formattedMinutes = String(minutes).padStart(2, '0');
const formattedSeconds = String(seconds).padStart(2, '0');
return `${formattedMinutes}:${formattedSeconds}`;
}
module.exports = {
/**
* 深拷贝对象
*
* @param {Object} source 拷贝的源对象
* @param {Object} desc 目标对象,为空时完全复制一个source对象
* @returns {Object} 新的对象
*/
clone,
/**
* 格式化日期
*
* @param {Object} date 要格式化的日期
* @param {String} format 格式化字符串,yyyy|MM|dd|HH|ss|mm
*
* @returns {String} 格式化后的字符串
*/
formatDate,
/**
* 获取当前时间戳
*
* @returns {Number} 当前时间戳
* */
timestamp() {
let stamp = (new Date()).getTime() / 1000;
stamp = parseInt(stamp);
return stamp;
},
/**
* 安全方式调用fn
*
* @param {Function} fn 要调用的方法
* @returns 如果fn存在则返回其引用否则返回一个空函数
*/
invoke,
/**
* 生成一个GUID
*/
guid,
/**
* 判断obj是否为一个nullundefind''的空对象
* 而不是以!obj形式判断以增加安全性
*
* @param {Object} obj 接受判断的对象
*/
isNone,
/**
* 判断arr是否为null或undefind或空数组
*
* @param {Object} arr 接受判断的数组
* @return {Boolean} true为空nullundefind)反之为false
*/
isEmptyArray,
formatTimeStr,
2025-06-13 14:39:20 +08:00
refreshToken,
getWeekdayWithValidation
2025-06-06 15:17:30 +08:00
};