import {nextTick, defineAsyncComponent} from 'vue';
import type {App} from 'vue';
import * as svg from '@element-plus/icons-vue';
import router from '/@/router/index';
import {i18n} from '/@/i18n/index';
import {verifyUrl} from '/@/utils/toolsValidate';
import request from '/@/utils/request';
import {useMessage} from '/@/hooks/message';
import * as CryptoJS from 'crypto-js';
import {sm4} from 'sm-crypto'
import {validateNull} from './validate';
import {RouteItem, RouteItems, RouteToFrom} from '/@/types/global';
const SvgIcon = defineAsyncComponent(() => import('/@/components/SvgIcon/index.vue'));
export function elSvg(app: App) {
const icons = svg as any;
for (const i in icons) {
app.component(`ele-${icons[i].name}`, icons[i]);
}
app.component('SvgIcon', SvgIcon);
}
export function setMenuI18n(item: any) {
let name = i18n.global.t(item.name);
if (name !== item.name) {
return name;
}
return i18n.global.locale.value === 'en' ? item.meta.enName : item.meta.title;
}
export const lazyImg = (el: string, arr: EmptyArrayType) => {
const io = new IntersectionObserver((res) => {
res.forEach((v: any) => {
if (v.isIntersecting) {
const {img, key} = v.target.dataset;
v.target.src = img;
v.target.onload = () => {
io.unobserve(v.target);
arr[key]['loading'] = false;
};
}
});
});
nextTick(() => {
document.querySelectorAll(el).forEach((img) => io.observe(img));
});
};
export function deepClone(obj: EmptyObjectType) {
let newObj: EmptyObjectType;
try {
newObj = obj.push ? [] : {};
} catch (error) {
newObj = {};
}
for (let attr in obj) {
if (obj[attr] && typeof obj[attr] === 'object') {
newObj[attr] = deepClone(obj[attr]);
} else {
newObj[attr] = obj[attr];
}
}
return newObj;
}
export function isMobile() {
if (
navigator.userAgent.match(
/('phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone')/i
)
) {
return true;
} else {
return false;
}
}
export function handleEmpty(list: EmptyArrayType) {
const arr = [] as any[];
for (const i in list) {
const d = [] as any[];
for (const j in list[i]) {
d.push(list[i][j]);
}
const leng = d.filter((item) => item === '').length;
if (leng !== d.length) {
arr.push(list[i]);
}
}
return arr;
}
export function handleOpenLink(val: RouteItem) {
router.push(val.path);
if (verifyUrl(<string>val.meta?.isLink)) window.open(val.meta?.isLink);
else window.open(`${val.meta?.isLink}`);
}
export const openWindow = (url: string, title: string, w: number, h: number) => {
const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;
const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
const height = window.innerHeight
? window.innerHeight
: document.documentElement.clientHeight
? document.documentElement.clientHeight
: screen.height;
const left = width / 2 - w / 2 + dualScreenLeft;
const top = height / 2 - h / 2 + dualScreenTop;
return window.open(
url,
title,
'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' +
w +
', height=' +
h +
', top=' +
top +
', left=' +
left
);
};
export function encryption(src: string, keyWord: string) {
const key = CryptoJS.enc.Utf8.parse(keyWord);
var encrypted = CryptoJS.AES.encrypt(src, key, {
iv: key,
mode: CryptoJS.mode.CFB,
padding: CryptoJS.pad.NoPadding,
});
return encrypted.toString();
}
export function decryption(src: string, keyWord: string) {
const key = CryptoJS.enc.Utf8.parse(keyWord);
var decryptd = CryptoJS.AES.decrypt(src, key, {
iv: key,
mode: CryptoJS.mode.CFB,
padding: CryptoJS.pad.NoPadding,
});
return decryptd.toString(CryptoJS.enc.Utf8);
}
export function sm4Encryption(src: string, keyWord: string) {
return sm4.encrypt(src, keyWord);
}
export function sm4Decryption(src: string, keyWord: string) {
return sm4.decrypt(src, keyWord);
}
export function base64Encrypt(src: string) {
const encodedWord = CryptoJS.enc.Utf8.parse(src);
return CryptoJS.enc.Base64.stringify(encodedWord);
}
export function downBlobFile(url: any, query: any, fileName: string) {
return request({
url: url,
method: 'get',
responseType: 'blob',
params: query,
}).then((response) => {
handleBlobFile(response, fileName);
});
}
export function handleBlobFile(response: any, fileName: string) {
const blob = response;
if (blob && blob.size === 0) {
useMessage().error('内容为空,无法下载');
return;
}
const link = document.createElement('a');
var binaryData = [] as any;
binaryData.push(response);
link.href = window.URL.createObjectURL(new Blob(binaryData));
link.download = fileName;
document.body.appendChild(link);
link.click();
window.setTimeout(function () {
URL.revokeObjectURL(blob);
document.body.removeChild(link);
}, 0);
}
export function generateUUID() {
if (typeof crypto === 'object') {
if (typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
if (typeof crypto.getRandomValues === 'function' && typeof Uint8Array === 'function') {
const callback = (c: any) => {
const num = Number(c);
return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(16);
};
return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, callback);
}
}
let timestamp = new Date().getTime();
let performanceNow = (typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0;
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
let random = Math.random() * 16;
if (timestamp > 0) {
random = (timestamp + random) % 16 | 0;
timestamp = Math.floor(timestamp / 16);
} else {
random = (performanceNow + random) % 16 | 0;
performanceNow = Math.floor(performanceNow / 16);
}
return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16);
});
}
const other = {
elSvg: (app: App) => {
elSvg(app);
},
useTitle: () => {
useTitle();
},
setMenuI18n(item: RouteItems) {
return setMenuI18n(item);
},
lazyImg: (el: string, arr: EmptyArrayType) => {
lazyImg(el, arr);
},
globalComponentSize: () => {
return globalComponentSize();
},
deepClone: (obj: EmptyObjectType) => {
return deepClone(obj);
},
isMobile: () => {
return isMobile();
},
handleEmpty: (list: EmptyArrayType) => {
return handleEmpty(list);
},
handleOpenLink: (val: RouteItem) => {
handleOpenLink(val);
},
encryption: (src: string, keyWord: string) => {
return encryption(src, keyWord);
},
decryption: (src: string, keyWord: string) => {
return decryption(src, keyWord);
},
base64Encrypt: (data: any) => {
return base64Encrypt(data);
},
downBlobFile: (url: any, query: any, fileName: string) => {
return downBlobFile(url, query, fileName);
},
toUnderline: (str: string) => {
return toUnderline(str);
},
openWindow: (url: string, title: string, w: number, h: number) => {
return openWindow(url, title, w, h);
},
getQueryString: (url: string, paraName: string) => {
return getQueryString(url, paraName);
},
adaptationUrl: (url?: string) => {
return adaptationUrl(url);
},
resolveAllEunuchNodeId: (json: any[], idArr: any[], temp: any[] = []) => {
return resolveAllEunuchNodeId(json, idArr, temp);
},
getNonDuplicateID: () => {
return getNonDuplicateID();
},
addUnit: (value: string | number, unit = 'px') => {
return addUnit(value, unit);
},
};
export function getQueryString(url: string, paraName: string) {
const arrObj = url.split('?');
if (arrObj.length > 1) {
const arrPara = arrObj[1].split('&');
let arr;
for (let i = 0; i < arrPara.length; i++) {
arr = arrPara[i].split('=');
if (arr != null && arr[0] == paraName) {
return arr[1];
}
}
return '';
} else {
return '';
}
}
export function handleTree(data: any, id: any, parentId: any, children: any, rootId: any) {
id = id || 'id';
parentId = parentId || 'parentId';
children = children || 'children';
rootId =
rootId ||
Math.min.apply(
Math,
data.map((item: any) => {
return item[parentId];
})
) ||
0;
const cloneData = JSON.parse(JSON.stringify(data));
const treeData = cloneData.filter((father: any) => {
const branchArr = cloneData.filter((child: any) => {
return father[id] === child[parentId];
});
branchArr.length > 0 ? (father[children] = branchArr) : '';
return father[parentId] === rootId;
});
return treeData !== '' ? treeData : data;
}
const resolveAllEunuchNodeId = (json: any[], idArr: any[], temp: any[] = []) => {
for (const item of json) {
if (item.children && item.children.length !== 0) {
resolveAllEunuchNodeId(item.children, idArr, temp);
} else {
temp.push(...idArr.filter((id) => id === item.id));
}
}
return temp;
};
export function toUnderline(str: string) {
return str.replace(/([A-Z])/g, '_$1').toLowerCase();
}
const adaptationUrl = (originUrl?: string) => {
const isMicro = import.meta.env.VITE_IS_MICRO;
if (validateNull(isMicro) || isMicro === 'true') {
return originUrl;
}
return `/admin/${originUrl?.split('/').splice(2).join('/')}`;
};
const getNonDuplicateID = (length = 8) => {
let idStr = Date.now().toString(36);
idStr += Math.random().toString(36).substring(3, length);
return idStr;
};
const addUnit = (value: string | number, unit = 'px') => {
return !Object.is(Number(value), NaN) ? `${value}${unit}` : value;
};
export default other;