import Decimal from 'decimal.js' import { allowedNodeEnvironmentFlags } from 'process' import { toast } from './toast' /** * 页面跳转方法 * @param url 跳转地址 * @param time 延迟时间(毫秒),默认0 */ export const router = { //跳转至非table页面 navigateTo: (url: string, time = 0) => { setTimeout(function() { uni.navigateTo({ url }) }, time); }, //跳转至 table switchTab: (url: string, time = 0) => { setTimeout(function() { uni.switchTab({ url }) }, time); }, //返回上页面 navigateBack: (delta: number = 1, time = 0) => { return new Promise((resolve, reject) => { setTimeout(function() { uni.navigateBack({ delta, success: () => { resolve(); }, fail: (err) => { reject(err); } }) }, time); }); }, //关闭所有页面,打开到应用内的某个页面 reLaunch: (url: string, time = 0) => { setTimeout(function() { uni.reLaunch({ url }) }, time); }, //关闭当前页面跳转至非table页面 redirectTo: (url: string, time = 0) => { setTimeout(function() { uni.redirectTo({ url }) }, time); }, } /** * 乘法,避免浮点数精度问题,不进行四舍五入,直接截断 * @param num1 乘数1 * @param num2 乘数2 * @returns 乘积 */ export function toTimes(num1: number, num2: number) { const value1 = new Decimal(num1) const value2 = new Decimal(num2) const result = value1.times(value2).toDecimalPlaces(2, Decimal.ROUND_DOWN) return result.toString() } /** * 加法,避免浮点数精度问题,不进行四舍五入,直接截断 * @param args 任意数量的加数 * @returns 求和结果字符串,保留2位小数(向下截断) */ /** * 加法,支持对象参数(如 {0: '128', 1: '128'}),避免浮点数精度问题,不进行四舍五入,直接截断 * @param args 任意数量的加数或对象 * @returns 求和结果字符串,保留2位小数(向下截断) */ export function toPlus(...args: any[]): string { // 支持 toPlus({0: '128', 1: '128'}) 或 toPlus('128', '128') let arr: any[] = [] if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null) { // 传入的是对象,取所有值 arr = Object.values(args[0]) } else { arr = args } let sum = new Decimal(0) for (const num of arr) { // 自动转为数字 const n = Number(num) if (!isNaN(n)) { sum = sum.plus(new Decimal(n)) } } // 截断2位小数,不四舍五入 const result = sum.toDecimalPlaces(2, Decimal.ROUND_DOWN) return result.toString() } /** * 减法,支持对象参数(如 {0: '128', 1: '28'}),避免浮点数精度问题,不进行四舍五入,直接截断 * @param args 任意数量的被减数和减数或对象 * @returns 结果字符串,保留2位小数(向下截断) */ export function toMinus(...args: any[]): string { // 支持 toMinus({0: '128', 1: '28'}) 或 toMinus('128', '28') let arr: any[] = [] if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null) { arr = Object.values(args[0]) } else { arr = args } if (arr.length === 0) return '0.00' let result = new Decimal(Number(arr[0]) || 0) for (let i = 1; i < arr.length; i++) { const n = Number(arr[i]) if (!isNaN(n)) { result = result.minus(new Decimal(n)) } } return result.toDecimalPlaces(2, Decimal.ROUND_DOWN).toString() } /** * 复制内容到剪贴板 * @param data 复制的内容 */ export function copy(data: any) { uni.setClipboardData({ data: data, success: () => { toast.info('已复制到剪贴板') } }) } /** * 随机标签颜色 * @param index 索引 * @returns */ export function randomLabelColor (index: number) { const tagColors = ['#40AE36', '#F55726'] return tagColors[index % tagColors.length] }