wujingjing
2025-04-14 1df71bdd7fc5b35be1447c9cc574bf610666f436
src/utils/util.ts
@@ -10,6 +10,7 @@
import FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
import { MAIN_URL } from '../constants';
import { saveAs } from 'file-saver';
/**
 * 普通对象转为 formData
@@ -284,7 +285,7 @@
   callback: (value: T, index?, array?, parent?) => any,
   parent: any = null,
   markParent = false,
   childrenKey = 'Children'
   childrenKey = 'children'
) => {
   if (!treeData || treeData.length === 0) return;
   if (!parent) parent = treeData;
@@ -541,11 +542,13 @@
 * 最近 n 天的 startDate、endDate
 * @param dates
 */
export const getRecentDateRange = (dates: number) => {
export const getRecentDateRange = (dates: number, includesCurrent = true) => {
   dates = includesCurrent ? dates - 1 : dates;
   // 获取当前日期
   const endDate = new Date();
   const startDate = new Date();
   startDate.setTime(startDate.getTime() - 3600 * 1000 * 24 * dates);
   endDate.setHours(23, 59, 59, 59);
   startDate.setHours(0, 0, 0, 0);
   return [startDate, endDate];
};
@@ -619,11 +622,26 @@
export const toPercent = (num: number, havePercentSymbol = true, decimalPlaces = 1, defaultValue = '-') => {
   if (num == null) return `${defaultValue} %`;
   let percent = Number(num * 100).toFixed(decimalPlaces);
   const factor = Math.pow(10, decimalPlaces);
   let percent = Math.round(Number(num) * 100 * factor) / factor + '';
   if (havePercentSymbol) {
      percent += '%';
   }
   return percent;
};
/**
 * 保留指定精度小数位,且不补零
 * @param num
 * @param precision
 * @returns
 */
export const toMyFixed = (num, precision) => {
   if (num == null) return '';
   if (!precision) return num + '';
   const factor = Math.pow(10, precision);
   return Math.round(Number(num) * factor) / factor + '';
};
/**
@@ -722,3 +740,50 @@
   document.body.removeChild(spanEle);
   return width;
}
export function decodeFormData(formDataString) {
   const params = new URLSearchParams(formDataString);
   const decodedData = {};
   for (const [key, value] of params) {
      decodedData[key] = decodeURIComponent(value);
   }
   return decodedData;
}
/**
 * 休眠指定秒数
 * @param seconds 休眠秒数
 * @returns Promise
 */
export const sleep = (seconds: number): Promise<void> => {
   return new Promise((resolve) => {
      setTimeout(resolve, seconds * 1000);
   });
};
/**
 * 下载文件
 * @param url 文件地址
 * [{
      类型: item.OTYPE,
      名称: item.ONAME,
      位置: item.WKT,
}]
 * @param fileName 文件名
 */
export const downloadExcel = (tableData: any[], fileName: string) => {
   // 创建工作簿
   const wb = XLSX.utils.book_new();
   // 创建工作表
   const ws = XLSX.utils.json_to_sheet(tableData);
   // 将工作表添加到工作簿
   XLSX.utils.book_append_sheet(wb, ws, '查询结果');
   // 生成 Excel 文件
   const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
   const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
   // 下载文件
   saveAs(blob, `${fileName}_${new Date().toLocaleDateString()}.xlsx`);
};