jz-tool-lib
Version:
项目常用公共方法集合
3 lines (2 loc) • 15.7 kB
JavaScript
import e from"axios";import{reactive as t,onMounted as r}from"vue";function o(e){return Object.prototype.toString.call(e)}function s(...e){const t=[null,NaN,"",void 0,!1];return!e.some(e=>t.includes(e))}function n(e,t){if(e===t)return!0;if(null===e||"object"!=typeof e||null===t||"object"!=typeof t)return!1;let r=[],o=[];if("object"==typeof e&&(r=Object.keys(e)),"object"==typeof t&&(o=Object.keys(t)),r.length!==o.length)return!1;for(const s of r)if(!o.includes(s)||!n(e[s],t[s]))return!1;return!0}const c=e=>{if(!["[object Number]","[object String]"].includes(o(e)))return void console.error("参数错误, 请传入数字和数字字符串");let t=Number(e);s(t)||(t=0);const r=t<0?"欠":"",n=["角","分"],c=[["元","万","亿"],["","拾","佰","仟"]],i=["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"];t=Math.abs(t);let a="";for(let e=0;e<n.length;e++)a+=(i[Math.floor(10*t*Math.pow(10,e))%10]+n[e]).replace(/零./,"");a=a||"整",t=Math.floor(t);for(let e=0;e<c[0].length&&t>0;e++){let r="";for(let e=0;e<c[1].length&&t>0;e++)r=i[t%10]+c[1][e]+r,t=Math.floor(t/10);a=r.replace(/(零.)*零$/,"").replace(/^$/,"零")+c[0][e]+a}return r+a.replace(/(零.)*零元/,"元").replace(/(零.)+/g,"零").replace(/^整$/,"零元整")},i=(e,t,r)=>{const o=t.value,s=r&&r();if(o&&o instanceof Array){if(!o.length)throw new Error("传入关于权限的数组,如 v-permission=\"['super','normal']\"");s.some(e=>o.includes(e))||e.parentNode&&e.parentNode.removeChild(e)}},a=(e,t=globalThis.location.href)=>{if(e&&t){let r=[];return"string"==typeof e&&(r=[e]),r.length?r.map(e=>{const r=new RegExp(`[?&]${e}=([^&]*)(?:&|$)`),o=t.match(r);return{[e]:o?decodeURIComponent(o[1]):""}}):""}return""};let l=e=>{const t=navigator.clipboard;return l=t?e=>new Promise((t,r)=>{navigator.clipboard.writeText(e).then(()=>t({status:!0})).catch(e=>r({status:!1,error:e}))}):e=>new Promise((t,r)=>{try{const r=document.createElement("textarea");r.readOnly=!0,r.value=e,r.style.position="absolute",r.style.top="-9999px",r.style.left="-9999px",document.body.appendChild(r),r.select(),document.execCommand("copy"),r.remove(),t({status:!0})}catch(e){r({status:!1,error:e})}}),l(e)};const u=e=>{e.scrollIntoView({behavior:"smooth",block:"start"})};function h(e,t,r,o){if(!e||!t)return"";const s=e.split("");let n,c;n=r?r<0?0:r>s.length?s.length:r:0,c=o?o<0?0:o>s.length?s.length:o:s.length,n>=c&&(n=c,c=n);for(let e=n;e<c;e++)s[e]=t;return s.join("")}const p=e=>{let t=parseFloat(e+"");const r={count:0,list:["B","KB","MB","GB","TB","PB"]};for(;t>=1024&&r.count<r.list.length;)t/=1024,r.count++;return{unit:r.list[r.count],count:Math.floor(parseFloat(e+"")/Math.pow(1024,r.count)*100)/100}};function d(e=0,t="",r=""){if(e=parseFloat(e+""),isNaN(e)||e<=0)throw new Error("请输入有效的数字作为内存计数");const o=["B","KB","MB","GB","TB","PB"],s=o.findIndex(e=>e===t.toUpperCase());if(-1===s)throw new Error("请输入有效单位B、KB、MB、GB、TB、PB");const n=o.findIndex(e=>e===r.toUpperCase());if(-1===n)throw new Error("请输入有效单位B、KB、MB、GB、TB、PB");const c=s<n?Math.fround(e/Math.pow(1024,n-s)):Math.fround(e*Math.pow(1024,s-n));return{unit:o[n],count:Math.trunc(100*c)/100,preciseCount:c}}const f=function(e){const t=parseFloat(e+"");return Math.floor(t/1073741824*100)/100},g=(e,t=!1)=>{const r=Math.floor(100*parseFloat(e+""));if(isNaN(r))return 0;{const e=(r/100).toFixed(2);return t?Number(e).toLocaleString():e}},m=(e=0,t={accuracy:3,isCover:!1})=>{const{accuracy:r,isCover:o}=Object.assign({accuracy:3,isCover:!1},t);if(e=parseFloat(e+""),isNaN(e))return"";{const t=Math.pow(10,r),s=Math.trunc(e*t)/t;return o?s.toFixed(r):s+""}};function b(e,t,r="single",o){const s=[];if(t.length){if(e.length){if("complex"===r&&!o)throw new Error("对象数组缺少id字段");return t.map(t=>{const c="complex"===r?Reflect.get(t,o):t,i=e.find(e=>{const t="complex"===r?Reflect.get(e,o):e;return n(c,t)});i&&s.push(i)}),s}return s}return s}function v(e,t,r="single",o){let s=[];if(t.length){if(e.length){if("complex"===r&&!o)throw new Error("对象数组缺少id字段");const c=e.concat(t),i=b(e,t,r,o);return c.map(e=>{const t="complex"===r?Reflect.get(e,o):e;i.some(e=>{const s="complex"===r?Reflect.get(e,o):e;return n(t,s)})||s.push(e)}),s}return t}return e}function y(e){return!(!Array.isArray(e)||!e.length)}function x(e,t){return y(e)?t?e.filter((e,r,o)=>o.findIndex(r=>r[t]===e[t])===r):e.filter((e,t,r)=>r.indexOf(e)===t):[]}function k(e,t,r){if(!y(e))return;return e.every(e=>"[object Object]"===o(e))?e.find(e=>r?"[object Object]"!==o(t)?e[r]===t:e[r]===t[r]:void console.warn("对象匹配的属性propKey不能为空")):e.find(e=>e===t)}function w(e,t){if(!y(e))return[];return e.slice().sort((e,r)=>{if("number"==typeof e&&"number"==typeof r)return e-r;if("string"==typeof e&&"string"==typeof r)return e.localeCompare(r);if("object"==typeof e&&"object"==typeof r){if(t){if(Reflect.has(e,t)&&Reflect.has(r,t))return"number"==typeof e[t]&&"number"==typeof r[t]?e[t]-r[t]:e[t].localeCompare(r[t]);throw new Error("对象不存在排序字段")}throw new Error("对象缺少排序字段")}})}function I(e=[],t=[],r=[]){let o;o=r.length?e.filter(e=>{if(e.meta.authKey){if("string"==typeof e.meta.authKey)return r.includes(e.meta.authKey);return b(e.meta.authKey,r,"single").length}return!e.meta.authKey}):e;const s=[];return t.length?o.forEach(e=>{if(-1!==t.findIndex(t=>t===e.meta.moduleTitle)){const t=s.findIndex(t=>Reflect.has(t,e.meta.moduleTitle));-1===t?s.push({moduleTitle:e.meta.moduleTitle,[e.meta.moduleTitle]:[e]}):s[t][e.meta.moduleTitle].push(e)}}):o.forEach(e=>{s.push(e)}),s}const S=function(e){return/^1[3-9]\d{9}$/.test(e)},C=function(e){return/^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])\d{3}(\d|X|x)$/.test(e)},j=function(e){return/^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_.!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_.!@#$%^&*`~()-+=]+$)(?![0-9\\W_.!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_.!@#$%^&*`~()-+=]{8,16}$/.test(e)},E=function(e){return/^([1-9]\d{0,9}|0)(\.\d{1,2})?$/.test(e)};class T{constructor(e){this.storage=globalThis[e]}getItem(e){const t=this.storage.getItem(e);if(t){const r=JSON.parse(t),s=Object.keys(r);return["[object Object]"].includes(o(r))&&1===s.length?r[e]:r}}batchGetItem(e){const t={},r=Array.from(new Set(e));for(const e of r)Reflect.set(t,e,this.getItem(e));return Object.keys(t).length?t:""}setItem(e,t){return["[object Object]","[object Array]"].includes(o(t))?this.storage.setItem(e,JSON.stringify(t)):["[object Number]","[object String]","[object Boolean]","[object Null]"].includes(o(t))?this.storage.setItem(e,JSON.stringify({[e]:t})):void console.error(`不支持${o(t)}数据类型`)}batchSetItem(e){for(const t in e){const r=e[t];this.setItem(t,r)}}removeItem(e){this.storage.removeItem(e)}batchRemoveItem(e){for(const t in e)this.storage.removeItem(e[t])}clear(){this.storage.clear()}}class N extends T{constructor(){super("localStorage")}static getInstance(){return N.instance||(N.instance=new N),N.instance}}class O extends T{constructor(){super("sessionStorage")}static getInstance(){return O.instance||(O.instance=new O),O.instance}}const $=N.getInstance(),M=O.getInstance();function B(e,t,r,o){const s=`<thead>${t.reduce((e,t)=>e+`<th style="width: ${t.width}; text-align: center;">${t.label}</th>`,"")}</thead><tbody>${e.reduce((e,r)=>e+`<tr>${t.reduce((e,t)=>e+`<td style="width: ${t.width}; text-align: center;">${r[t.prop]}</td>`,"")}</tr>`,"")}</tbody>`,n=`\n <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" lang="zh-Hans">\n <head>\x3c!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--\x3e<title>excel表格</title></head>\n <body><table border="1">${s}</table></body></html>`,c="data:application/vnd.ms-excel;base64,"+function(e){return globalThis.btoa(unescape(encodeURIComponent(e)))}((i={worksheet:o||"worksheet",tableData:s},n.replace(/{(\w+)}/g,function(e,t){return i[t]})));var i;const a=document.createElement("a");a.href=c,a.download=r||(new Date).getTime()+"",a.click(),globalThis.URL.revokeObjectURL(c)}function W(e){e?globalThis.open(e,"_blank"):console.error("url参数不能为空")}const R=(e,t)=>{if(!e)return void console.error("blob参数不能为空");if(!t)return void console.error("fileName参数不能为空");const r=document.createElement("a"),o=globalThis.URL.createObjectURL(e);r.href=o,r.download=t,r.click(),globalThis.URL.revokeObjectURL(o)};class q{constructor(t){this.abortControllers=new Map,this.requestInterceptors=null,this.responseInterceptors=null;try{this.http=e.create(t),this.requestInterceptorsSuccess=t.requestInterceptorsSuccess,this.requestInterceptorsCatch=t.requestInterceptorsCatch,this.responseInterceptorsSuccess=t.responseInterceptorsSuccess,this.responseInterceptorsCatch=t.responseInterceptorsCatch,this.setupInterceptors()}catch(e){throw e}}setupInterceptors(){this.requestInterceptors=this.http.interceptors.request.use(this.requestInterceptorsSuccess,this.requestInterceptorsCatch),this.responseInterceptors=this.http.interceptors.response.use(this.responseInterceptorsSuccess,this.responseInterceptorsCatch)}get(e,t,r){return this.request(e,"get",void 0,t,r)}delete(e,t,r){return this.request(e,"delete",void 0,t,r)}post(e,t,r){return this.request(e,"post",t,void 0,r)}put(e,t,r){return this.request(e,"put",t,void 0,r)}request(e,t,r,o,s){return new Promise((n,c)=>{const i=this.getIdentifier({url:e,params:["get","GET","delete","DELETE"].includes(t)?o:r}),a=new AbortController;this.abortControllers.set(i,a),this.http.request(Object.assign({url:e,method:t,data:r,params:o,signal:a.signal},s)).then(e=>{n(e),this.abortControllers.delete(i)}).catch(e=>{c(e),this.abortControllers.delete(i)})})}cancelRequest(e){(Array.isArray(e)?e:[e]).map(e=>{const t=this.getIdentifier(e);this.abortControllers.has(t)&&(this.abortControllers.get(t).abort(),this.abortControllers.delete(t))})}getIdentifier(e){return[e.url,JSON.stringify(e.params)].join("@")}requestInterceptorsEject(){return new Promise((e,t)=>{null!==this.requestInterceptors?(this.http.interceptors.request.eject(this.requestInterceptors),e({message:"取消请求拦截器成功",data:this})):t({message:"请求拦截器不存在",data:this})})}responseInterceptorsEject(){return new Promise((e,t)=>{null!==this.responseInterceptors?(this.http.interceptors.response.eject(this.responseInterceptors),e({message:"取消请求拦截器成功",data:this})):t({message:"请求拦截器不存在",data:this})})}}function z(e,t,r,o){return new(r||(r=Promise))(function(s,n){function c(e){try{a(o.next(e))}catch(e){n(e)}}function i(e){try{a(o.throw(e))}catch(e){n(e)}}function a(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(c,i)}a((o=o.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const P=e=>{const{listApi:o,props:s,notExecute:n=!1,searchParams:c,paramsData:i={},conditionData:a={}}=e;let l=10,u="pageSize",h=1,p="pageNumber";s&&("string"==typeof s.pageSize?u=s.pageSize:(u=s.pageSize.name,l=s.pageSize.default?s.pageSize.default:10),"string"==typeof s.pageNumber?p=s.pageNumber:(p=s.pageNumber.name,h=s.pageNumber.default?s.pageNumber.default:10));const d=t({list:[],pageTotal:0,pageSize:l,pageNumber:h,[u]:l,[p]:h}),f=()=>z(void 0,void 0,void 0,function*(){var e;const t=null!==(e=c&&c())&&void 0!==e?e:{},r=Object.assign(Object.assign(Object.assign(Object.assign({},i),a.value),t),{[u]:d[u],[p]:d[p]}),s=yield o.getData(r),{list:n,total:l}=o.handleData(s.data);d.list=n,d.pageTotal=l}),g=()=>z(void 0,void 0,void 0,function*(){d[u]=l,d.pageSize=l}),m=()=>z(void 0,void 0,void 0,function*(){d[p]=h,d.pageNumber=h});return r(()=>z(void 0,void 0,void 0,function*(){!n&&(yield f())})),{getList:f,pageData:d,resetPageData:()=>z(void 0,void 0,void 0,function*(){yield g(),yield m()}),resetPageSize:g,resetPageNumber:m,pageSizeChange:e=>z(void 0,void 0,void 0,function*(){d[u]=e,d[p]=1,d.pageSize=e,d.pageNumber=1,yield f()}),pageNumberChange:e=>z(void 0,void 0,void 0,function*(){d.pageNumber=e,d[p]=e,yield f()})}};class A{constructor(e){this.socket=null,this.isConnect=!0,this.maxReconnectCount=10,this.reconnectTime=5e3,this.reconnectCount=0,this.reconnectTimer=null,this.heartbeatTimer=null,this.heartbeatTime=5e3,this.dispatchCenter=new Map,"undefined"!=typeof WebSocket?(this.url=e.url,this.connect()):console.error("您的浏览器不支持WebSocket")}connect(){this.url?(this.socket=new WebSocket(this.url),console.log(1),this.socket&&(this.setupOpen(),this.setupMessage(),this.setupClose(),this.setupError())):console.error("WebSocket error: 请传入连接地址")}openHook(e){this.subscribeEvent("open",e)}errorHook(e){this.subscribeEvent("error",e)}messageHook(e){this.subscribeEvent("message",e)}closeHook(e){this.subscribeEvent("close",e)}subscribeEvent(e,t){this.dispatchCenter.has(e)||this.dispatchCenter.set(e,[]);this.dispatchCenter.get(e).push(t)}dispatchEvent(e,t){var r;const o=null!==(r=this.dispatchCenter.get(e))&&void 0!==r?r:[];o.length&&o.map(e=>{e.call(this,t)})}setupOpen(){this.socket.onopen=()=>{var e;this.dispatchEvent("open",{event:"open",state:null===(e=this.socket)||void 0===e?void 0:e.readyState}),this.heartbeat(),console.log("%cWebSocket连接成功readyState:1","color:#ffffff;background-color:#67c23a;")}}setupMessage(){this.socket.onmessage=e=>{var t;this.dispatchEvent("message",{event:"message",state:null===(t=this.socket)||void 0===t?void 0:t.readyState,data:e.data}),console.log("%cWebSocket收到服务器数据readyState:1","color:#ffffff;background-color:#409eff;")}}setupClose(){this.socket.onclose=()=>{this.isConnect&&(this.reconnectCount<this.maxReconnectCount?(this.reconnectCount++,this.reconnectTimer=setTimeout(()=>{this.connect(),console.error(`WebSocket重新连接尝试${this.reconnectCount}次数`)},this.reconnectTime)):(this.reconnectCount=0,console.error("WebSocket已达到最大重新连接尝试次数。无法重新连接")))}}setupError(){this.socket.onerror=e=>{var t;this.dispatchEvent("error",{event:"error",state:null===(t=this.socket)||void 0===t?void 0:t.readyState,data:e}),console.error("WebSocket连接错误")}}heartbeat(){this.heartbeatTimer=setInterval(()=>{this.sendMessage({module:"heartbeat",data:"ping"})},this.heartbeatTime)}sendMessage(e){this.socket&&this.socket.readyState===WebSocket.OPEN?this.socket.send(JSON.stringify(e)):console.error("WebSocket连接没有建立成功")}dispose(){this.isConnect=!1,this.reconnectCount=0,clearTimeout(this.reconnectTimer),clearTimeout(this.heartbeatTimer),this.socket&&this.socket.close(),this.socket=null,console.warn("WebSocket:已销毁")}}class U extends A{constructor(e){super(e)}static getInstance(e){return U.instance||(U.instance=new U(e)),U.instance}}console.log("%cjz-tool-lib version: 1.0.1-beta.26","color: #ffffff;background: #0056ff;");export{q as Http,$ as LocalStorage,M as SessionStorage,U as StockService,v as arrayDiffValue,y as arrayHasValue,k as arrayMatchValue,b as arraySomeValue,w as arraySort,x as arrayUnique,I as authRouter,f as bToGB,l as copyText,c as currencyChinese,R as downLoadBlob,W as downLoadFile,B as downloadExcel,a as getQueryByName,n as isEqual,s as judgeBoolean,o as judgeDataType,p as memory,d as memoryConvert,g as moneyFormat,i as permission,u as scrollToTop,h as strExtract,C as testIdentification,E as testMoney,j as testPassword,S as testTelephone,m as toMoney,P as usePage};
//# sourceMappingURL=index.es.js.map