Files
FreeERP.Applet/miniprogram/utils/util.ts

327 lines
7.7 KiB
TypeScript
Raw Normal View History

2025-11-28 16:49:36 +08:00
import { http } from "./config";
export const formatTime = (date: Date) => {
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();
return `${[year, month, day].map(formatNumber).join("-")} ${[
hour,
minute,
second,
]
.map(formatNumber)
.join(":")}`;
2025-11-28 16:49:36 +08:00
};
export const formatNumber = (n: number | string) => {
n = n.toString();
return n[1] ? n : `0${n}`;
};
// 对话框
export const showModal = (
title: string,
content: string,
showCancel = false
) => {
2025-11-28 16:49:36 +08:00
return new Promise<void>((resolve, reject) => {
wx.showModal({
title,
content,
showCancel,
success(res) {
if (res.confirm) {
resolve();
} else if (res.cancel) {
reject();
}
},
});
});
};
/** 判断数据是不是数组类型 */
export const isArray = (data: any) => data && Array.isArray(data);
2025-11-28 16:49:36 +08:00
/**
*
* @param {*} data
* @returns {Array}
*/
export const toArray = (data: any): any[] => (isArray(data) ? data : []);
2025-11-28 16:49:36 +08:00
/** 判断数据是不是对象类型 */
export const isObject = (data: any) => {
return data && `${Object.prototype.toString.call(data)}`.includes("Object");
};
export const toObject = (data: any) => (isObject(data) ? data : {});
2025-11-28 16:49:36 +08:00
export const reloadPage = () => {
let pages = getCurrentPages(); //获取加载的页面
let currentPage = pages[pages.length - 1]; //获取当前页面的对象
let url = currentPage.route; //当前页面url
// 关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。
wx.redirectTo({ url: "/" + url });
2025-11-28 16:49:36 +08:00
};
/** 判断是json数据 */
export const isJson = (str: any) => {
if (str && typeof str == "string") {
try {
const obj = JSON.parse(str);
return obj && typeof obj == "object";
} catch (_e) {
//
}
}
return false;
};
/**
* json数据
* @param data
* @returns array | object | null
*/
export const jsonParse = (data: any): any[] | object | null => {
if (data) {
if (typeof data == "string") {
try {
const obj = JSON.parse(data);
if (
["Array", "Object"].includes(
Object.prototype.toString.call(obj).slice(8, -1)
)
) {
2025-11-28 16:49:36 +08:00
return obj;
}
} catch (e) {
//
}
} else if (
["Array", "Object"].includes(
Object.prototype.toString.call(data).slice(8, -1)
)
) {
2025-11-28 16:49:36 +08:00
return data;
}
}
return null;
};
/**
*
* @param {*} value
* @returns Boolean
*/
export const isNumber = (value: any) => {
return !isNaN(parseFloat(value)) && isFinite(value);
};
/**
*
* @param {*} str
* @returns Number
*/
export const toNumber = (str: any) => {
return isNumber(str) ? Number(str) : 0;
};
/**
*
* @param {*} str
* @param {*} num
*/
export const formatToDecimals = (str: any, num: number = 2) => {
num = num === undefined ? 2 : toNumber(num);
return toNumber(str).toFixed(num);
};
/** 获取权限 */
export const getAuthInfo = () => toObject(wx.getStorageSync("auth_info"));
2025-11-28 16:49:36 +08:00
export const goIndexPage = () => {
wx.navigateTo({ url: "/pages/index/index" });
2025-11-28 16:49:36 +08:00
};
export const isImageFile = (path: string) => {
return /\.(jpe?g|png|gif|svg|webp|bmp)$/i.test(path);
};
/** 滚动到顶部 */
export const scrollToTop = () => {
wx.pageScrollTo({ scrollTop: 0 });
};
/** 设置tabs配置 */
export const tabsConfigSet = (key: string, value: any) => {
const tabsConfig = toObject(tabsConfigGet());
tabsConfig[key] = value;
setStorage("tabsConfig", tabsConfig);
};
/** 获取tabs配置 */
export const tabsConfigGet = () => {
return getStorage("tabsConfig");
};
/**
*
* @param {*} imageUrls
* @param {*} currentUrl
*/
export const mediaPreview = (imageUrls: any[], currentUrl: string) => {
console.log("媒体图片预览方法");
const lastLen =
`${currentUrl}`.indexOf("?") > -1
? `${currentUrl}`.indexOf("?")
: `${currentUrl}`.length;
2025-11-28 16:49:36 +08:00
const suffix: any = currentUrl
.substring(currentUrl.lastIndexOf(".") + 1, lastLen)
.toLocaleLowerCase();
2025-11-28 16:49:36 +08:00
if (isImageFile("." + suffix)) {
wx.previewImage({ urls: imageUrls, current: currentUrl, showmenu: true });
2025-11-28 16:49:36 +08:00
} else if (["mp3", "mp4", "m4a"].includes(suffix)) {
wx.previewMedia({
sources: [{ url: currentUrl, type: "video" }],
2025-11-28 16:49:36 +08:00
fail() {
wx.showToast({ title: "播放失败" });
2025-11-28 16:49:36 +08:00
},
});
} else if (
["doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"].includes(suffix)
) {
2025-11-28 16:49:36 +08:00
const downloadTask = wx.downloadFile({
url: currentUrl,
header: http.header,
success: (res) => {
2025-11-28 16:49:36 +08:00
const filePath = res.tempFilePath;
wx.openDocument({
filePath: filePath,
showMenu: true,
fileType: suffix,
success: () => {},
2025-11-28 16:49:36 +08:00
});
},
fail() {},
complete() {
wx.hideLoading();
},
});
downloadTask.onProgressUpdate((res) => {
wx.showLoading({
title: `${res.progress}%`,
});
if (res.progress == 100) {
wx.hideLoading();
}
});
} else {
wx.showToast({ title: "请前往网页端下载查看" });
2025-11-28 16:49:36 +08:00
}
};
/**
*
* @param {*} option {filePath: '文件路径', name: 'files', url:'上传url',formData: {data},success: (data)=>{}, complete:()=>{},fail: ()=>{} }
*/
export const uploadFile2 = (option: any) => {
console.log("文件上传封装");
option = toObject(option);
option.name = option.name || "files";
wx.showLoading({ title: "文件上传中..." });
2025-11-28 16:49:36 +08:00
wx.uploadFile({
filePath: option.filePath,
name: option.name,
header: {
...http.header,
cookie: "DFSESSID=" + wx.getStorageSync("session_id"),
},
formData: option.formData,
url: option.url,
success(res) {
const resData = jsonParse(res.data);
wx.showToast({ title: "上传成功" });
2025-11-28 16:49:36 +08:00
if (option.success) {
option.success(resData);
}
},
fail() {
wx.showToast({ title: "上传失败" });
2025-11-28 16:49:36 +08:00
if (option.fail) {
option.fail();
}
},
complete() {
wx.hideLoading();
if (option.complete) {
option.complete();
}
},
});
};
/**
* dataset
* @param {*} e
*/
export const getDataSet = (e: any) => {
return e.currentTarget.dataset;
};
export const toastSuccess = (title: string) => {
wx.showToast({ title: `${title}`, icon: "success" });
};
export const toastError = (title: string) => {
wx.showToast({ title: `${title}`, icon: "error" });
};
export const toastSuccessNotIcon = (title: string) => {
wx.showToast({ title: `${title}`, icon: "none" });
};
export const getEnvVersion = wx.getAccountInfoSync().miniProgram.envVersion;
/**
*
* @param key string
*/
export const getStorage = (key: string) => {
return wx.getStorageSync(`${getEnvVersion}_${key}`);
};
/**
*
* @param key string
* @param data any
*/
export const setStorage = (key: string, data: any) => {
return wx.setStorageSync(`${getEnvVersion}_${key}`, data);
};
/**
*
* @param key string
*/
export const removeStorage = (key: string) => {
return wx.removeStorageSync(`${getEnvVersion}_${key}`);
};
/**
*
*/
export const getCurrentPageRoute = () => {
const pages = getCurrentPages(); // 获取页面栈
const currentPage = pages[pages.length - 1]; // 获取当前页面对象
return `/${currentPage.route}`; // 获取当前页面路径
};