import axios from "axios"; export const uuid = (len = 16, radix = 10) => { const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""); const uuid = []; let i; radix = radix || chars.length; if (len) { // Compact form for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]; } else { // rfc4122, version 4 form let r; // rfc4122 requires these characters uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-"; uuid[14] = "4"; // Fill in random data. At i==19 set the high bits of clock sequence as // per rfc4122, sec. 4.1.5 for (i = 0; i < 36; i++) { if (!uuid[i]) { r = 0 | (Math.random() * 16); uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r]; } } } return uuid.join(""); }; export const copy = (data) => { var copy = document.createElement("p"); copy.innerText = data; document.body.append(copy); var range = document.createRange(); range.selectNode(copy); var selection = window.getSelection(); if (selection) { if (selection.rangeCount > 0) selection.removeAllRanges(); selection.addRange(range); } document.execCommand("copy"); document.body.removeChild(copy); }; /** * * @param {object} positionData { * centerPosition:{x: x, y: y} 圆心坐标 * originPosition:{x: x, y: y} 初始坐标 * rotate: rotate 旋转角度 * } * @description 根据圆心坐标、旋转角度计算旋转后的坐标 */ export const getRotatePosition = (positionData) => { const radian = (Math.PI / 180) * positionData.rotate; return { x: (positionData.originPosition.x - positionData.centerPosition.x) * Math.cos(radian) - (positionData.originPosition.y - positionData.centerPosition.y) * Math.sin(radian) + positionData.centerPosition.x, y: (positionData.originPosition.y - positionData.centerPosition.y) * Math.cos(radian) + (positionData.originPosition.x - positionData.centerPosition.x) * Math.sin(radian) + positionData.centerPosition.y, }; }; /** * @description 防抖 * @param {*} fn * @param {*} wait * @returns */ export function _debounce(fn, wait = 500) { let timer; return function () { const context = this; const args = arguments; if (timer) clearTimeout(timer); timer = setTimeout(() => { fn.apply(context, args); }, wait); }; } /** * @description 节流 * @param {*} fn * @param {*} wait * @returns */ export function _throttle(fn, wait = 500) { let last, timer, now; return function () { now = Date.now(); if (last && now - last < wait) { clearTimeout(timer); timer = setTimeout(function () { last = now; fn.call(this, ...arguments); }, wait); } else { last = now; fn.call(this, ...arguments); } }; } /** * @param {Array} permissionList * @param {String} routerName * @description 判断是否有权限 */ export const hasPermission = (permissionList, routerName) => { return permissionList.some((permission) => { if (permission.code === routerName) { return true; } else { return ( permission.children && permission.children.length && permission.children.find((child) => { if (child.code === routerName) { return true; } }) ); } }); }; export const downloadPDF = (url, fileName) => { axios({ url: url, method: "GET", responseType: "blob", // 将响应类型设置为 blob }) .then((response) => { const blob = new Blob([response.data], { type: "application/pdf" }); const link = document.createElement("a"); link.href = URL.createObjectURL(blob); link.download = fileName || "download.pdf"; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(link.href); // 释放 Blob URL 资源 }) .catch((error) => { console.error("下载失败:", error); }); }; // 后端返回二进制流下载文件 export const downloadBlob = (blob, fileName = "download") => { const reader = new FileReader(); reader.readAsDataURL(blob); reader.onload = (e) => { const a = document.createElement("a"); a.download = fileName; a.href = e.target.result; document.body.appendChild(a); a.click(); document.body.removeChild(a); }; }; /** * @description base64下载word */ export const downloadWord = (base64Data, filename) => { // 创建Blob对象 var blob = base64ToBlob( base64Data, "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ); // 创建下载链接 var url = URL.createObjectURL(blob); var downloadLink = document.createElement("a"); // 设置下载链接属性 downloadLink.href = url; downloadLink.download = filename; // 触发下载 document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); URL.revokeObjectURL(url); // 清理 }; export const base64ToBlob = (base64, mimeType) => { // 解码Base64字符串 var byteCharacters = atob(base64.replace(/^data:\w+\/\w+;base64,/, "")); // 将解码的字符串转换为类型化数组 var byteNumbers = new Array(byteCharacters.length); for (var i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } // 创建Blob对象 var byteArray = new Uint8Array(byteNumbers); return new Blob([byteArray], { type: mimeType }); }; export const downloadExcel = (base64Data, filename, type) => { const blobs = type ? "application/vnd.ms-excel" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; // 创建Blob对象 var blob = base64ToBlob(base64Data, blobs); // 创建下载链接 var url = URL.createObjectURL(blob); var downloadLink = document.createElement("a"); // 设置下载链接属性 downloadLink.href = url; downloadLink.download = filename; // 触发下载 document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); URL.revokeObjectURL(url); // 清理 }; // 时间戳转化为时间 export function convertTimestamp(timestamp) { const date = new Date(timestamp); const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, "0"); const day = String(date.getDate()).padStart(2, "0"); const hours = String(date.getHours()).padStart(2, "0"); const minutes = String(date.getMinutes()).padStart(2, "0"); const seconds = String(date.getSeconds()).padStart(2, "0"); return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; } // 格式化时间 export function formatDate(timestamp, formate) { const date = new Date(); date.setTime(parseInt(timestamp)); // 传入formate形式 yyyy-MM-dd yyyy-MM-dd hh:mm formate = formate != null ? formate : "yyyy-MM-dd"; const Format = function (fmt) { var o = { "M+": date.getMonth() + 1, // 月 "d+": date.getDate(), // 日 "h+": date.getHours(), // 小时 "m+": date.getMinutes(), // 分 "s+": date.getSeconds(), // 秒 "q+": Math.floor((date.getMonth() + 3) / 3), // 季度 S: date.getMilliseconds(), // 毫秒 }; if (/(y+)/.test(fmt)) { fmt = fmt.replace( RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length) ); } // if (/(y+)/.test(fmt)) // fmt = fmt.replace( // RegExp.$1, // (date.getFullYear() + '').substr(4 - RegExp.$1.length) // ) for (var k in o) { if (new RegExp("(" + k + ")").test(fmt)) { fmt = fmt.replace( RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length) ); } } return fmt; }; return Format(formate); } export const jsonToFormData = (json) => { const formData = new FormData(); for (const key in json) { if (Object.prototype.hasOwnProperty.call(json, key)) { const value = json[key]; if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) { let item; if (typeof value[i] === "string") { item = value[i]; formData.append(`${key}[${i}]`, item); } else if (value[i] instanceof File) { item = value[i]; formData.append(`${key}`, item); } else { item = JSON.stringify(value[i]); formData.append(`${key}[${i}]`, item); } } } else if (value instanceof File) { formData.append(key, value); } else { const item = typeof value === "string" ? value : JSON.stringify(value); formData.append(key, item); } } } return formData; }; //下载图表json 文件 export const downLoadChartsJsonFile = (selectJson) => { // 创建Blob对象,将selectJson数据转化为JSON字符串 const jsonStr = JSON.stringify(selectJson, null, 2); // 格式化JSON const blob = new Blob([jsonStr], { type: "application/json" }); // 创建a元素,用于下载Blob内容 const link = document.createElement("a"); link.href = URL.createObjectURL(blob); link.download = selectJson.layout.title + "_selected_data.json"; // 设置下载的文件名 // 触发下载 link.click(); // 释放URL对象 URL.revokeObjectURL(link.href); }; //生成新的图表数据 export const creatNewChartsJson = (selectedPoints, fullLayout) => { const groupedData = {}; const addedPoints = {}; // 用于跟踪已添加的 (x, y) 组合 selectedPoints.forEach((item) => { const { name } = item.data; if (!groupedData[name]) { groupedData[name] = { x: [], y: [], mode: item.data.mode, color: item.fullData.marker.color || item.fullData.line.color, // 获取颜色信息 }; } // 使用 (x, y) 作为键来跟踪是否已添加 const pointKey = `${item.x}-${item.y}`; if (!addedPoints[pointKey]) { groupedData[name].x.push(item.x); groupedData[name].y.push(item.y); addedPoints[pointKey] = true; } }); const newPlotlyData = Object.keys(groupedData).map((name) => ({ x: groupedData[name].x, y: groupedData[name].y, mode: groupedData[name].mode, marker: { color: groupedData[name].color, size: 10 }, // 使用原始颜色 line: { color: groupedData[name].color }, // 使用原始颜色 name: name, })); // 配置新的图表布局 const layout = { title: fullLayout.title.text, xaxis: { title: fullLayout.xaxis.title.text }, yaxis: { title: fullLayout.yaxis.title.text }, legend: { orientation: "h", y: -0.2, x: 0.5, xanchor: "center", }, }; return { newPlotlyData, layout }; }; export const downLoadCsvFile = (csvContent, fileName) => { // 创建 Blob 对象 const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" }); // 创建下载链接 const link = document.createElement("a"); const url = URL.createObjectURL(blob); link.setAttribute("href", url); link.setAttribute("download", `${fileName}.csv`); link.style.visibility = "hidden"; // 将链接添加到 DOM 并触发点击事件 document.body.appendChild(link); link.click(); // 清除 URL 和移除链接 document.body.removeChild(link); URL.revokeObjectURL(url); }; export const downloadDocx = (url, fileName) => { axios({ url: url, method: "GET", responseType: "blob", // 将响应类型设置为 blob }) .then((response) => { const blob = new Blob([response.data], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", }); const link = document.createElement("a"); link.href = URL.createObjectURL(blob); link.download = fileName || "download.docx"; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(link.href); // 释放 Blob URL 资源 }) .catch((error) => { console.error("下载失败:", error); }); }; export default { uuid, copy, jsonToFormData, getRotatePosition, _debounce, _throttle, hasPermission, downloadBlob, downloadWord, base64ToBlob, downloadExcel, convertTimestamp, formatDate, downLoadChartsJsonFile, creatNewChartsJson, downLoadCsvFile, downloadDocx, };