erp-el-element/commont.js

541 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import request from './utils/request';
/**
* 脱敏处理函数
* @param {string} input - 需要脱敏处理的数据
* @param {string} type - 数据类型,包括 'email', 'id', 'bankCard', 'address', 'birthdate', 'name', 'phone', 'custom'(不脱敏)
* @return {string} 脱敏后的数据
*/
function maskData(input, type = 'phone') {
if (typeof input !== 'string') return input
// const { securityEncryption } = session.get('THEME_CONFIG') || {}
// 与服务端商定加解密方式
// input = decrypt(input)
// 只解密不脱敏
if (type === 'custom') return input
// 地址脱敏 中间的数字进行脱敏 明月小区*单元**号楼101
if (type === 'address') return input.replace(/(\d+)(?=\D)/g, match => '*'.repeat(match.length))
let start, end
switch (type) {
case 'email': {
// 邮箱,保留前两位和 "@" 后的所有字符
const [localPart, domain] = input.split('@')
if (localPart.length > 2) {
start = 2
end = domain.length + 1 }
break
}
case 'bankCard': {
// 身份证号或银行卡号,保留前三位和后四位
start = 3
end = 4
break
}
case 'birthdate': {
// 出生日期,隐藏中间四位
start = 2
end = 2
break
}
case 'name': {
// 姓名3个字以内隐藏第1个字4-6个字隐藏前2个字大于6个字隐藏第3-6个字
const length = input.length
if (length <= 3) {
start = 0
end = length - 1
} else if (length <= 6) {
start = 0
end = length - 2
} else {
start = 2
end = length - 6
}
break
}
default: // phone 包含手机号和固定电话
// 手机号,保留前三位和后两位,电话号码保留区号和后三位
// telRegExp-固定电话正则 phoneRegExp-手机号正则
let telRegExp=/^(?:(?:\+|00)86)?1\d{10}$/;
if (telRegExp.test(input)) {
let matchRes = input.match(telRegExp);
if(matchRes){
console.log(matchRes,"matchRes")
if(matchRes[1]&&matchRes[1].length){
start = matchRes[1].length
}else{
start = 3
}
if(matchRes[2]&&matchRes[2].length){
end = matchRes[2].length
}else{
end = 2
}
}
} else {
start = 3
end = 2
}
}
// 计算被脱敏处理后的字符的长度
let maskLength = input.length - start - end
// 使用正则表达式进行脱敏处理
const reg = new RegExp(`^(.{${start}}).*(.{${end}})$`)
return input.replace(reg, `$1${'*'.repeat(maskLength)}$2`)
}
//获取近几天
function getDay (number,bool = false) {
let today = new Date();
let day = today.getTime() + 24 * 60 * 60 * 1000 * number;
today.setTime(day);
let val = formatDate(parseInt(today.getTime() / 1000), 'Y-m-d')
if(bool){
val = parseInt(today.getTime() / 1000)
}
return val
}
// 添加本地存储
function addSessionStorage(key,value) {
sessionStorage.setItem(key,JSON.stringify(value));
}
function getSessionStorage(key) {
let result=sessionStorage.getItem(key);
try{
result= JSON.parse(result);
}catch(err){
}
return result;
}
function delSessionStorage(key) {
sessionStorage.removeItem(key);
}
function getMonthFirst (data) {
let date = new Date(data);
date.setDate(1);
let month = parseInt(date.getMonth() + 1);
let day = date.getDate();
if( month < 10) {
month = '0' + month
}
if(day < 10 ) {
day = '0' + day
}
let val = date.getFullYear() + '-' + month +'-' + day
return val
}
function getMonthLast (data) {
let date = new Date(data);
let currentMonth = date.getMonth();
let nextMonth = ++currentMonth;
let nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
let oneDay = 24 * 60 * 60 * 1000
let lastTime = new Date(nextMonthFirstDay - oneDay);
let month = parseInt(lastTime.getMonth() + 1);
let day = lastTime.getDate();
if( month < 10) {
month = '0' + month
}
if(day < 10 ) {
day = '0' + day
}
let val = date.getFullYear() + '-' + month +'-' + day
return val
}
//格式化时间
function uuid(){
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
}
//获取url上的参数值 e为参数名称
function getCookie(e) {
return new Promise((r,j)=>{
// 获取所有的cookie
var cookies = document.cookie;
// 将cookie字符串拆分为一个数组
// 注意:这个方法仅用于演示目的,实际的解析可能需要更复杂的逻辑来处理等号、引号、分号等
var cookieArray = cookies.split(";");
let find=false;
// 遍历cookie数组并处理每个cookie
for (var i = 0; i < cookieArray.length; i++) {
// 使用trim()方法去除前后的空格
var cookiePair = cookieArray[i]?.split("=");
var cookieName = cookiePair[0]?.trim();
var cookieValue = cookiePair[1]?.trim();
// 如果你只对某个特定的cookie感兴趣可以添加条件判断
if (cookieName === e) {
find=true;
r(cookieValue);
}
if(i==cookieArray.length-1){
if(!find){
r(false);
}
}
}
});
}
function setCookie(name, value, days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); // 有效期为days天
var expires = "; expires=" + date.toUTCString();
document.cookie = name + "=" + (value || "") + expires + "; path=/"; // 默认情况下path为'/'
}
//获取url上的参数值 e为参数名称
function getQueryString(e) {
var t = new RegExp("(/\?|&)" + e + "=([^&]*)(&|$)");
var a = window.location.href.substr(1).match(t);
if (a != null) return a[2];
return ""
}
// 添加本地存储
function addStorage(key,value) {
localStorage.setItem(key,JSON.stringify(value));
}
// 获取本地存储
function getStorage(key) {
let result=localStorage.getItem(key);
try{
result= JSON.parse(result);
}catch(err){
}
return result;
}
// <Button className={styles.btnDelete} size="small"><Icon type="delete" />删除本地存储指定的值
function deloneStorage(key) {
localStorage.removeItem(key);
}
// <Button className={styles.btnDelete} size="small"><Icon type="delete" />删除所有本地存储的值
function delAllStorage(key) {
return localStorage.clear();
}
// JSON数据转换 url后的参数格式
function jsonurldata(datas) {
const dataarray = [];
const datakeys = Array.from(Object.keys(datas));
const datavalue = Array.from(Object.values(datas));
for (let i in datakeys) {
let jsontostring = datakeys[i] + '=' + datavalue[i]
dataarray.push(jsontostring);
}
let outdata = dataarray.join('&');
return outdata;
}
function isWeiXin(){
let ua = window.navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i) == 'micromessenger'){
return true;
}else{
return false;
}
}
//把时间戳格式化成标准格式 第一个参数为时间戳,第二个参数为格式例如 Y-m-d h:M:s'
function formatDate(date, format) {
if(!date){
return ''
}
const days = [
'周日',
'周一',
'周二',
'周三',
'周四',
'周五',
'周六'
];
if ( typeof date == 'string') {
if (date.length < 13) {
const j = 13 - date.length;
for (let i = 0; i < j; i++) {
date = date + '0';
}
}
date = new Date(Number(date));
}else if (typeof date == 'number'){
if(date<1000000000000){
date=date*1000;
}
date = new Date(date);
} else if (typeof date === 'undefined') {
return '';
}
if (!format) {
format = 'Y-m-d';
}
if (Number(date.getHours()) < 10) {
var hour = '0' + String(date.getHours());
}
else {
var hour = date.getHours();
}
if (Number(date.getMinutes()) < 10) {
var Minute = '0' + String(date.getMinutes());
}
else {
var Minute = date.getMinutes();
}
if (Number(date.getSeconds()) < 10) {
var Seconds = '0' + String(date.getSeconds());
}
else {
var Seconds = date.getSeconds();
}
if (Number((date.getMonth()) + 1) < 10) {
var month = '0' + String(date.getMonth() + 1);
} else {
var month = date.getMonth() + 1;
}
if (Number(date.getDate()) < 10) {
var day = '0' + String(date.getDate());
} else {
var day = date.getDate();
}
format = format.replace('Y', date.getFullYear())
.replace('m', month)
.replace('d', day)
.replace('h', hour)
.replace('M', Minute)
.replace('D', days[date.getDay()])
.replace('s', Seconds);
return format;
};
// 压缩图片
function compression(imgsrc, truewidth,trueheight) {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
const cts = canvas.getContext('2d');
const newimg = new Image();
newimg.src = imgsrc;
newimg.onload = function () {
let _w = newimg.naturalWidth;
let _h = newimg.naturalHeight;
const trueheightarray=[];
if(trueheight){
trueheightarray.push(trueheight);
}else{
let trueheight = _h / _w * truewidth;
trueheightarray.push(trueheight);
}
canvas.width = truewidth;
canvas.height = trueheightarray[0];
cts.drawImage(newimg, 0, 0, _w, _h, 0, 0, truewidth, trueheightarray[0]);
resolve(canvas.toDataURL('images/png',0.8));
}
})
}
function isObject(item) {
// 判断参数是否存在且类型为对象且不是数组
return (item && typeof item === 'object' && !Array.isArray(item));
}
function isArray(value) {
// 使用Array.isArray方法判断传入的值是否为数组
return Array.isArray(value);
}
function pagedata(ndatas,pageSize=200) {
let myproxy=new Proxy({},{
page:1,
data:[],
pageSize:200,
alldata:[],
get:(tar,key)=>{
if(key=="page"){
return tar.page;
}else if(key=="data"){
if(tar.alldata){
return tar.alldata.slice(0,tar.page*tar.pageSize);
}
return true;
}
return true;
},
set:(tar,key,value)=>{
if(key=="alldata"){
if(Array.isArray(value)){
tar.alldata=value;
tar.page=1;
tar.data=value.slice(0,tar.page*tar.pageSize);
}
}else if(key=="page"){
if(typeof(value)=="number"){
tar.page=value;
tar.data=tar.alldata.slice(0,value*tar.pageSize);
}
}else if(key=="pageSize"){
if(typeof(value)=="number"){
tar.pageSize=value;
tar.data=tar.alldata.slice(0,value*tar.page);
}
}
}
});
if(datas){
myproxy.alldata=ndatas;
}
if(pageSize){
myproxy.pageSize=pageSize;
}
return myproxy;
}
function getFileExtension(file) {
var fileName = file.name;
if(fileName){
var dotIndex = fileName.lastIndexOf('.');
if (dotIndex !== -1) {
return fileName.substring(dotIndex);
}
}
return ''; // 或者返回 null表示没有扩展名
}
const initOss=(file,key="xy_shop_qc_avatar")=>{
return new Promise((r,j)=>{
const fileLast = getFileExtension(file);
if (!fileLast) j();
let oss=getSessionStorage("oss");
if(oss){
const key = oss.dir +new Date().getTime()+Number.parseInt((9999)*Math.random())+fileLast;
if(oss.expire>Number(new Date().getTime().toString().slice(0,10))){
sendoss({ key, file, ... oss });
}else{
delSessionStorage("oss");
getSign();
}
}else{
getSign();
}
function getSign(){
request({
url: '/api/base_config/get_oss_sign_aliyun_v3',
method: 'get',
params: {bussiness_type:key}
}).then((res)=>{
if(res.errcode==0){
let oss=Object.assign({},res.datas);
const key = oss.dir +new Date().getTime()+(99999)*Math.random()+fileLast;
oss.accessKeyId = res.datas.accessid;
oss.accessKeySecret = res.datas.signature;
addSessionStorage('oss',oss);
sendoss({ key, file, ... oss });
}else{
j();
}
}).catch((err)=>{
j();
});
}
function sendoss(data){
// OSS 的 POST 请求 URL
const url = 'https://'+data.host;
// 创建一个 FormData 实例
const formData = new FormData();
// 添加字段到 formData
formData.append('key',data.key);
formData.append('policy', data.policy);
formData.append('OSSAccessKeyId',data.accessid);
formData.append('Signature',data.signature);
formData.append('success_action_status', 201);
formData.append('file', data.file,data.file.name);
let resulturl=url+'/'+data.key;
fetch(url, {
method: 'POST', // 或者 'PUT'
body: formData,
}).then((res)=>{
console.log(res,"rrr",resulturl)
if(res.status==201){
r(resulturl);
}else{
j();
}
}).catch((err)=>{
console.log(err.message,"err1")
if(err.message=="Failed to fetch"){
delSessionStorage("oss");
j();
}
});
}
});
}
function debunce(fn,delay=1000) {
let timer;
return function(...args){
if(timer){
clearTimeout(timer);
}
timer=setTimeout(()=>{
fn.apply(this,args);
},delay);
}
}
function promiseAllWithErrors(promises) {
return new Promise((resolve, reject) => {
let resolvedResults = [];
let rejectedReasons = [];
let fncout=0;
promises.forEach((promise, index) => {
promise.then(
result => {
resolvedResults[index] = result;
fncout++;
console.log(fncout,"fncout",promises.length,result)
if (result&&fncout== promises.length) {
// 所有Promise都成功解析
resolve({ results: resolvedResults, errors: rejectedReasons });
}
}
).catch((reason)=>{
rejectedReasons[index] = reason;
fncout++;
// 检查是否所有Promise都已处理无论成功或失败
if (fncout === promises.length) {
// 处理完所有Promise可能有成功也有失败
resolve({ results: resolvedResults, errors: rejectedReasons });
}
});
});
});
}
const commont=[{pagedata:pagedata},{maskData:maskData},{getDay:getDay},{uuid:uuid},{addStorage:addStorage},{addStorage:addStorage},{getStorage:getStorage},{deloneStorage:deloneStorage},{delAllStorage:delAllStorage},{formatDate:formatDate},{jsonurldata:jsonurldata},{isWeiXin:isWeiXin},
{getQueryString},{getMonthLast},{getMonthFirst},{compression},{isObject},{isArray},{addSessionStorage},{getSessionStorage},{delSessionStorage},{initOss},{setCookie},
{getCookie},{debunce},{promiseAllWithErrors}];
export default commont;