import axios from "axios"; import { ElMessage } from "element-plus"; var utils = { uniqueInArray(arr) { if (arr == null || arr.length == 0) return arr; //去重 var n = {}, r = []; for (var i = 0; i < arr.length; i++) { if (!n[arr[i]]) { n[arr[i]] = true; r.push(arr[i]); } } return r; }, uniqueArrayByObj(array, key) { const _set = [...new Set(array.map((e) => e[key]))]; let deArray = []; _set.map((item) => { deArray.push(array[array.findIndex((val) => val[key] === item)]); }); return deArray; }, getLabelInArray(arr, key) { let label = null; arr.forEach((item) => { if (item.value == key) { label = item.label; } }); return label; }, getValueInArray(arr, key) { let value = null; arr.forEach((item) => { if (item.label == key) { value = item.value; } }); return value; }, //给图片添加水印 getImgWaterMark({ url = "", cb = null } = {}) { if (url == null || url == "") return; // 创建所需要添加水印的img图片 const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); const img_origin = new Image(); img_origin.src = url; img_origin.crossOrigin = "anonymous"; img_origin.onload = function () { // 创建canvas,并将创建的img绘制成canvas canvas.width = img_origin.width; canvas.height = img_origin.height; ctx.drawImage(img_origin, 0, 0); //textAlign = 'left', //textBaseline = 'middle', //font = '18px Microsoft Yahei', //fillStyle = 'rgba(0, 0, 0, 0.15)', // fillStyle = '#aaaaaa', //content = 'Eventech', //ctx.textAlign = textAlign //ctx.textBaseline = textBaseline //ctx.font = font //ctx.fillStyle = fillStyle //ctx.globalAlpha = 0.3; // ctx.rotate((Math.PI / 180) * 15) // 循环绘制水印 // ctx.fillText(content, img_origin.width - textX, img_origin.height - textY) let watermark = new Image(); watermark.src = "./static/img/watermark.png"; ctx.drawImage(watermark, img_origin.width / 2, img_origin.height / 2); // 将绘制完成的canvas转换为base64的地址 const base64Url = canvas.toDataURL(); cb && cb(base64Url); }; }, /** * 防抖 * @param {*} fn * @param {*} delay * @returns */ _debounce(func, wait) { let timeout; return function (...args) { const context = this; clearTimeout(timeout); timeout = setTimeout(() => { func.apply(context, args); }, wait); }; }, /** * 节流函数 * @param {*} func * @param {*} delay * @returns */ _throttle(func, delay) { let lastCall = 0; return function (...args) { const now = new Date().getTime(); if (now - lastCall < delay) return; lastCall = now; return func(...args); }; }, /** *树形数据扁平化 * @param {Array} arrs 树形数据 * @param {string} childs 树形数据子数据的属性名,常用'children' * @param {Array} attrArr 需要提取的公共属性数组(默认是除了childs的全部属性)(可不写) * @returns */ extractTree(arrs, childs, attrArr) { let attrList = []; if (!Array.isArray(arrs) && !arrs.length) return []; if (typeof childs !== "string") return []; if ( !Array.isArray(attrArr) || (Array.isArray(attrArr) && !attrArr.length) ) { attrList = Object.keys(arrs[0]); attrList.splice(attrList.indexOf(childs), 1); } else { attrList = attrArr; } let list = []; let getObj = (arr, pid = 0) => { arr.forEach(function (row, index) { let obj = {}; obj.ParentID = pid; attrList.forEach((item) => { obj[item] = row[item]; }); list.push(obj); if (row[childs] && row[childs].length > 0) { obj.ParentID = 0; getObj(row[childs], (pid = row.AssemConfigID)); } }); return list; }; return getObj(arrs); }, /** *树形数据扁平化 * @param {Array} arrs 树形数据 * @param {string} childs 树形数据子数据的属性名,常用'children' * @param {Array} attrArr 需要提取的公共属性数组(默认是除了childs的全部属性)(可不写) * @returns */ extractTreeByHasParent(arrs, childs, attrArr) { let attrList = []; if (!Array.isArray(arrs) && !arrs.length) return []; if (typeof childs !== "string") return []; if ( !Array.isArray(attrArr) || (Array.isArray(attrArr) && !attrArr.length) ) { attrList = Object.keys(arrs[0]); attrList.splice(attrList.indexOf(childs), 1); } else { attrList = attrArr; } let list = []; let getObj = (arr, pid = 0) => { arr.forEach(function (row, index) { let obj = {}; attrList.forEach((item) => { obj[item] = row[item]; }); list.push(obj); if (row[childs] && row[childs].length > 0) { getObj(row[childs], (pid = row.AssemConfigID)); } }); return list; }; return getObj(arrs); }, arrayToTree(arr, pid, idField = "ID", pidField = "ParentID") { return arr.reduce((res, current) => { if (current[pidField] === pid) { current.children = this.arrayToTree(arr, current[idField]); return res.concat(current); } return res; }, []); }, /** * 获取数据类型 * @param {All} [o] 需要检测的数据 * @returns {String} */ getType(o) { return Object.prototype.toString.call(o).slice(8, -1); }, /** * 判断是否是指定数据类型 * @param {All} [o] 需要检测的数据 * @param {String} [type] 数据类型 * @returns {Boolean} */ isKeyType(o, type) { return utils.getType(o).toLowerCase() === type.toLowerCase(); }, /** * 深拷贝,支持常见类型 object Date Array等引用类型 * @param {Any} sth * @return {Any} */ deepClone(sth) { let copy; if (null == sth || "object" != typeof sth) return sth; if (utils.isKeyType(sth, "date")) { copy = new Date(); copy.setTime(sth.getTime()); return copy; } if (utils.isKeyType(sth, "array")) { copy = []; for (let i = 0, len = sth.length; i < len; i++) { copy[i] = utils.deepClone(sth[i]); } return copy; } if (utils.isKeyType(sth, "object")) { copy = {}; for (let attr in sth) { if (sth.hasOwnProperty(attr)) copy[attr] = utils.deepClone(sth[attr]); } return copy; } return null; }, /** * 判断服务的文件是否存在 * @param filepath 文件地址 * @param filename * @returns {Boolean} */ isExistFile(filepath) { if (filepath == null || filepath === "") { return false; } let xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET", filepath, false); xmlhttp.send(); if (xmlhttp.readyState === 4) { if (xmlhttp.status === 200) return true; //url存在 else if (xmlhttp.status === 404) return false; //url不存在 else return false; //其他状态 } }, /** * 生成随机的GUID * @returns */ getGUID() { let guid = ""; for (let i = 1; i <= 32; i++) { let flag = Math.floor(Math.random() * 10); //如果是偶数就设置成为 if (flag % 2 == 0) { //全大写 let n = Math.floor(flag * 2.4) + 65; n = String.fromCharCode(n); guid += n; } else { guid += flag; } } return guid; }, /** 校验特殊字符 */ validateSpecialSymbol(str) { const reg = /['()*]/; return reg.test(str); }, /* 手机号码和固定电话 */ validatePhTelNumber(str) { const reg = /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/; return reg.test(str); }, /* 电子邮箱 */ validateEmail(str) { const reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/; return reg.test(str); }, /** * 检查图片资源是否存在 * @param {String} ImgPath //图片路径 */ isExistImgPath(ImgPath) { if (ImgPath == null || ImgPath === "") { return false; } return new Promise(async (resolve, reject) => { try { const response = await fetch(ImgPath, { method: "HEAD" }); // 如果状态码是200-399之间,通常表示成功获取到了资源 if (response.ok) { resolve(true); } else { // 其他状态码可能表示资源未找到(404)或其他错误 resolve(false); } } catch (error) { // 网络错误或其他问题 console.error("Error:", error); resolve(false); } }); }, // 根据语言检查是否有对应的图片 async checkImgPathByLang(lang, path, cb = null) { if (lang == "CN") { cb && cb(path); return; } if (lang == "EN") { let en_Path = path.replace(".png", `-${lang}.png`); let enPath_exist = await this.isExistImgPath(en_Path); if (enPath_exist) { cb && cb(en_Path); return; } cb && cb(path); return; } if (lang == "RU") { let ru_Path = path.replace(".png", `-${lang}.png`); let en_path = path.replace(".png", `-EN.png`); let ruPath_exist = await this.isExistImgPath(ru_Path); let enPath_exist = await this.isExistImgPath(en_path); if (ruPath_exist) { cb && cb(ru_Path); return; } else if (enPath_exist) { cb && cb(en_path); return; } else { cb && cb(path); return; } } }, /** * 下载文件 * @param {*} url * @param {*} filename */ downloadFile(url, filename) { axios({ method: "get", url: url, responseType: "blob", }).then((res) => { const url = window.URL.createObjectURL(new Blob([res.data])); const link = document.createElement("a"); link.href = url; let fileName = filename; link.setAttribute("download", fileName); document.body.appendChild(link); link.click(); link.remove(); window.URL.revokeObjectURL(url); }).catch(err=>{ ElMessage.error(err) }) }, extractFileExtension(path) { var parts = path.split("/"); if (parts.length > 1) { return parts[parts.length - 1]; } }, /** * 格式化价格 * @param {*} price * @returns */ formatMoney(price) { if (price < 0) { return price; } // return price let result = String(Number(price).toFixed(2)).split("."); //按小数点分成2部分 result[0] = result[0].replace( new RegExp("(\\d)(?=(\\d{3})+$)", "ig"), "$1," ); //只将整数部分进行逗号分割 return result.join("."); //再将小数部分合并进来 }, /** * 处理下拉多选回显 * 当前多选的value * @param selValueArr * 当前多选的下拉列表数据 * @param selListData */ viewMultipleSelLabel(selValueArr, selListData) { if (selListData.length == 0) return ""; let text = ""; selValueArr.forEach((item) => { selListData.forEach((selItem) => { if (item == selItem.value) { text += selItem.label + ","; } }); }); return text.substring(0, text.length - 1); }, /** * 数据列表 * @param {*} list * 页数 * @param {*} curIndex * 条数 * @param {*} curSize */ pagination(list, curIndex, curSize) { let data = []; list = this.deepClone(list); data = list.slice((curIndex - 1) * curSize, curIndex * curSize); return data; }, }; export default utils;