UNPKG

w-vue-middle

Version:

统一公共服务组件

899 lines (846 loc) 25.5 kB
/* * @Author: Jason Liu * @Date: 2023-03-07 15:23:04 * @Desc: */ /* * @Author: Jason Liu * @Date: 2021-04-26 11:02:54 * @Desc: */ /* * 公共函数管理服务 */ /* 子应用服务获取 */ // 埋点服务导入 import Vue from 'vue'; import { message } from 'ant-design-vue'; const sqlFormatter = require('sql-formatter'); const { xmlFormatter } = require('./xmlTool'); const ChineseHelper = require('./pinyin/ChineseHelper').default; /// app版本信息 const appversion = navigator.appVersion.toLocaleLowerCase(); const u = navigator.userAgent; const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端 if (isIOS) { if (screen.height === 812 && screen.width === 375) { document.body.classList.add('ios_x'); } } /** * @Author: Jason Liu * @description: 数学计算服务 */ const math_service = { /** * @Author: Jason Liu * @description: 乘法计算 */ multiplication(arg1, arg2) { var m = 0, s1 = arg1.toString(), s2 = arg2.toString(); try { m += s1.split('.')[1].length; } catch (e) {} try { m += s2.split('.')[1].length; } catch (e) {} return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m); }, /** * @Author: Jason Liu * @description: 加法计算 */ addition(arg1, arg2) { var r1, r2, m; try { r1 = arg1.toString().split('.')[1].length; } catch (e) { r1 = 0; } try { r2 = arg2.toString().split('.')[1].length; } catch (e) { r2 = 0; } m = Math.pow(10, Math.max(r1, r2)); return (math_service.multiplication(arg1, m) + math_service.multiplication(arg2, m)) / m; }, /** * @Author: Jason Liu * @description: 减法 */ subtraction(arg1, arg2) { var r1, r2, m; try { r1 = arg1.toString().split('.')[1].length; } catch (e) { r1 = 0; } try { r2 = arg2.toString().split('.')[1].length; } catch (e) { r2 = 0; } m = Math.pow(10, Math.max(r1, r2)); return (math_service.multiplication(arg1, m) - math_service.multiplication(arg2, m)) / m; }, /** * @Author: Jason Liu * @description: 除法 */ division(arg1, arg2) { var t1 = 0, t2 = 0, r1, r2; try { t1 = arg1.toString().split('.')[1].length; } catch (e) {} try { t2 = arg2.toString().split('.')[1].length; } catch (e) {} r1 = Number(arg1.toString().replace('.', '')); r2 = Number(arg2.toString().replace('.', '')); return (r1 / r2) * Math.pow(10, t2 - t1); }, /** * @Author: Jason Liu * @description: 数组求和 */ array_sum(arr = [0]) { var s = 0; for (var i = arr.length - 1; i >= 0; i--) { s = math_service.addition(s, arr[i]); } return s; }, /** * @Author: Jason Liu * @description: 数组求平均 */ array_average(arr = [0]) { if (arr.length > 0) { return math_service.division(math_service.array_sum(arr), arr.length); } else { return 0; } }, }; const system_version = 'v1.2.116'; /* 1、门户仪表盘不显示问题修复 2、优化正态分布图(线图曲线,柱图的柱间距) 3、其他底层BUG修复 */ const service = { name: 'servicejs', appversion: appversion, isIos: appversion.indexOf('iphone') > 0, isWin: window.navigator.platform.indexOf('Win') == 0, sysversion: system_version, version: `glory soft bi mvp ${system_version}`, pageBack(url = undefined) { if (window.history.length == 1) { if (url) { window.location.replace(url); } else { window.close(); } } else { window.history.go(-1); } }, _init: function () { /// <summary>初始化</summary> var link = document.createElement('A'); String.prototype.toRealUrl = function (param) { /// <summary>获取绝对路径</summary> let url = this; if (param) { let query_param = service.jsonToMapArry(param); if (url.indexOf('?') > -1) { url += `&${query_param.join('&')}`; } else { url += `?${query_param.join('&')}`; } } link.href = url; return link.href; }; String.prototype.format = function (args) { if (arguments.length > 0) { var result = this; if (arguments.length == 1 && typeof args === 'object') { for (var key in args) { var reg = new RegExp('({' + key + '})', 'g'); result = result.replace(reg, args[key]); } } else { for (var i = 0; i < arguments.length; i++) { if (arguments[i] == undefined) { return ''; } else { var reg = new RegExp('({[' + i + ']})', 'g'); result = result.replace(reg, arguments[i]); } } } return result; } else { return this; } }; Date.prototype.toCustomize = function (format) { /// <summary>自定义时间格式</summary> var data = this; var myYear = parseInt(data.getFullYear()); var myMonth = parseInt(data.getMonth()) + 1; var myDay = parseInt(data.getDate()); var myHours = parseInt(data.getHours()); var myMinute = data.getMinutes(); var mySecond = data.getSeconds(); var weeks = [ $t('星期日'), $t('星期一'), $t('星期二'), $t('星期三'), $t('星期四'), $t('星期五'), $t('星期六'), ]; // 如果月份大于12 ,年加1,月份减12 if (myMonth > 12) { myYear++; myMonth = myMonth - 12; } // 如果天数大于28并且是2月份的话 如果天大于30的话,4,6,9,11月返回三十,其他时间返回31 if (myDay > 28 && myMonth == 2) { // 闰年 天数为29 平年天数为28 if ((myYear % 4 == 0 && myYear % 100 != 0) || myYear % 400 == 0) { myDay = 29; } else { myDay = 28; } } else if (myDay > 30) { switch (myMonth) { case 4: case 6: case 9: case 11: myDay = 30; break; default: myDay = 31; break; } } if (myMonth < 10) { myMonth = '0' + myMonth; } if (myDay < 10) { myDay = '0' + myDay; } if (myHours < 10) { myHours = '0' + myHours; } if (myMinute < 10) { myMinute = '0' + myMinute; } if (mySecond < 10) { mySecond = '0' + mySecond; } var result = format .replace(/yyyy/g, '{yyyy}') .replace(/MM/g, '{MM}') .replace(/dd/g, '{dd}') .replace(/hh/g, '{hh}') .replace(/mm/g, '{mm}') .replace(/ss/g, '{ss}') .replace(/week/g, '{week}'); return result.format({ yyyy: myYear, MM: myMonth, dd: myDay, hh: myHours, mm: myMinute, ss: mySecond, week: weeks[data.getDay()], }); }; Number.prototype.toCustomize = function (format) { /// <summary>自定义时间格式</summary> var data = new Date(this); return data.toCustomize(format); }; String.prototype.toCustomize = function (format) { /// <summary>自定义时间格式</summary> var time = parseInt(this); return time.toCustomize(format); }; String.prototype.toDateCustomize = function (format) { /// <summary>字符串格式的时间转换成指定格式</summary> var date = new Date(this.replace(/-/g, '/')); if (this == '0') { date = new Date(); } else if (date == 'Invalid Date' && this.length == 13) { //精确到小时需要特殊处理 date = new Date((this + ':00').replace(/-/g, '/')); } return date.toCustomize(format); }; String.prototype.toDate = function () { /// <summary>时间转日期格式</summary> if (this != '0') { return new Date(this.replace(/-/g, '/')); } else { return new Date(); } }; String.prototype.toStringByAbbreviationDate = function () { /// <summary>缩写日期转全日期</summary> var result = this.slice(0, 4) + '-' + this.slice(4, 6) + '-' + this.slice(6, 8); if (this == '0') { result = '0'; } return result; }; String.prototype.toJson = function (refer = {}) { var result = undefined; try { result = JSON.parse(this); } catch {} return Object.assign(refer, result); }; // 千分位分隔符 String.prototype.toThousands = function () { let result = this.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,'); if (this.indexOf('.') > -1) { let char = this.split('.'); result = char[0].replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,') + '.' + char[1]; } return result; }; // 转化为数字 String.prototype.toNumber = function () { if (!this) return 0; return Number(this.toString().replace(/[^\d]/g, '')); }; String.prototype.toFixed = function (n, isFloat = true) { /// <summary>四舍五入保留小数位</summary> var result = this; var arr = result.split('.'); var integer = arr[0]; var decimal = arr[1] || '0'; var newD = decimal.substr(0, n); if (newD.length < n) { let length = n - newD.length; for (var i = 0; i < length; i++) { newD += '0'; } } if (n == 0) { result = integer; } else { result = integer + '.' + newD; } var last = decimal.substr(n, 1); if (parseInt(last, 10) >= 5) { //这个是个BUG var x = Math.pow(100, n); result = (parseFloat(result) * x + 1) / x; if (result >= 0) { result = result.toFixed(n); } else { result = (result * -1).toFixed(n) * -1; } } return isFloat ? parseFloat(result) : result; }; Number.prototype.toGLFixed = function (n, isFloat = true) { /// <summary>四舍五入保留小数位</summary> var result = this.toString(); return result.toFixed(n, isFloat); }; Number.prototype.toNonExponential = function () { var m = this.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/); return this.toFixed(Math.max(0, (m[1] || '').length - m[2])); }; // 千分位分隔符 Number.prototype.toThousands = function () { return this.toString().toThousands(); }; /** * @Author: Jason Liu * @description: 数组去重 */ Array.unique = (arr) => { return Array.from(new Set(arr)); }; /** * @Author: Jason Liu * @description: 深拷贝对象 */ JSON.DeepCopy = (obj) => { return JSON.parse(JSON.stringify(obj)); }; /** * @Author: Jason Liu * @description: base64代码加密 */ String.prototype.encryptbase64 = function () { return btoa(this); }; const number_type_list = ['number', 'long', 'int']; /** * @Author: Jason Liu * @description: 是否数字列 */ String.prototype.isNumberColumn = function () { let isnum = false; let type = this.toLocaleLowerCase(); if (number_type_list.indexOf(type) > -1 || type.indexOf('numeric') > -1) { isnum = true; } return isnum; }; /** * @Author: Jason Liu * @description: 是否是邮件 */ String.prototype.isEmail = function () { const rgb = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/; if (rgb.test(this)) { return true; } else { return false; } }; const time_type_list = ['date']; /** * @Author: Jason Liu * @description: 是否日期 */ String.prototype.isTimeColumn = function () { let istime = false; let type = this.toLocaleLowerCase(); if (time_type_list.indexOf(type) > -1 || type.indexOf('timestamp') > -1) { istime = true; } return istime; }; String.prototype.sqlFormatter = function () { let sql = this; try { //sql = sqlFormatter.format(this).replace(/\$+\s+{+\s/g, "${").replace(/\s+\}/g, "}").replace(/\#+\s+{/g, "\n\t\t#{").replace(/\=+\s+\=/g, "==").replace(/\!+\s+\=/g, "!="); sql = sqlFormatter .format(this) .replace(/\$+\s+{+\s/g, '${') .replace(/\s+\}/g, '}') .replace(/\[+\s/g, '[') .replace(/\s+\]/g, ']') .replace(/\#+\s+{ /g, '\n\t\t#{') .replace(/\=+\s+\=/g, '==') .replace(/\!+\s+\=/g, '!=') .replace(/\| \|/g, '||') .replace(/\n/g, ' \n') .replace(/\# /g, '#'); } catch (error) {} return sql; }; /** * @Author: Jason Liu * @description: 格式化xml */ String.prototype.xmlFormatter = function () { let value = this; try { value = xmlFormatter(this); } catch (error) {} return value; }; /** * @Author: Jason Liu * @description: 货币函数 */ String.prototype.formatMoney = (money) => { return money.replace( new RegExp(`(?!^)(?=(\\d{3})+${money.includes('.') ? '\\.' : '$'})`, 'g'), ',', ); }; /** * @Author: Jason Liu * @description: 首字母大写 */ String.prototype.toInitialUpperCase = function () { return this.toLowerCase().replace(/\b[a-z]/g, function (match) { return match.toUpperCase(); }); }; /** * @Author: Jason Liu * @description: 指定位置插入 */ Array.prototype.insert = function (index, info) { if (info instanceof Array) { //是数组 let start = index; info.forEach((item) => { if (item) { this.splice(start, 0, item); start++; } }); } else { this.splice(index, 0, info); } }; /** * @Author: Jason Liu * @description: 根据行索引删除数据 */ Array.prototype.deleteRowByIndex = function (rowIndex) { this.splice(rowIndex, 1); }; /** * @Author: Jason Liu * @description: 字符转拼音 */ String.prototype.toConvertPinyin = function () { return ChineseHelper.ConvertPinyin(this); }; window.$copyClipboard = Vue.prototype.$copyClipboard = (value) => { const input = document.createElement('input'); document.body.appendChild(input); input.setAttribute('value', value); input.select(); if (document.execCommand('copy')) { document.execCommand('copy'); message.success($t('内容已复制到粘贴面板中')); } document.body.removeChild(input); }; window.$serviceJs = Vue.prototype.$serviceJs = service; }, jsonToMapArry: function (jsons, nokeys) { /// <summary>json转数组</summary> /// <param name="jsons" type="json">需要解析的json</param> /// <param name="nokeys" type="Strings">不需要加入的key</param> var arr = []; for (var key in jsons) { if (nokeys) { if (!(nokeys.indexOf(key) > -1)) { arr.push(key + '=' + jsons[key]); } } else { if (key == 'url') { let value = jsons[key]; if (value.indexOf('#') > -1) { if (value.indexOf('?') >= 0) { value += '&vue=true'; } else { value += '?vue=true'; } arr.push(key + '=' + encodeURIComponent(value)); } else { arr.push(key + '=' + value); } } else { arr.push(key + '=' + jsons[key]); } } } return arr; }, serializationGrid: function (_grids) { /// <summary>序列化表格</summary> const result = new Array(); if (_grids) { const title = _grids[0].split('|'); for (var i = 1; i < _grids.length; i++) { const row = {}; var details = _grids[i].split('|'); for (var index = 0; index < title.length; index++) { const key = title[index]; if (key) { const val = details[index]; row[key] = val; } } result.push(row); } } return result; }, random: function (_lower, _upper) { /// <summary>随机数</summary> var lower = _lower || 1; const upper = _upper || 100; return Math.floor(Math.random() * (upper - lower)) + lower; }, timeDifferenceToString: function (startTime, endTime) { /// <summary>String格式的时间差计算</summary> return this.timeDifference( new Date(startTime.replace(/-/g, '/')), new Date(endTime.replace(/-/g, '/')), ); }, timeDifference: function (startTime, endTime) { /// <summary>计算时间差</summary> const difference = endTime.getTime() - startTime.getTime(); const days = Math.floor(difference / (24 * 3600 * 1000)); // 获取差异天数 const leave = difference % (24 * 3600 * 1000); // 获取差异天数后的毫秒数 const hours = Math.floor(leave / (3600 * 1000)); const hLeave = leave % (3600 * 1000); // 获取差异小时后的毫秒数 var minutes = Math.floor(hLeave / (60 * 1000)); const mLeave = hLeave % (60 * 1000); // 获取分钟后的毫秒数 const seconds = Math.round(mLeave / 1000); // 获取差异秒数 return { days: days, hours: hours, minutes: minutes, seconds: seconds, millisecond: mLeave % 1000, }; }, getAgeByID: function (IDCard) { /// <summary>根据身份证获取用户年龄</summary> let age = 0; if (IDCard) { const yearBirth = IDCard.substring(6, 10); const monthBirth = IDCard.substring(10, 12); const dayBirth = IDCard.substring(12, 14); // 获取当前年月日并计算年龄 const myDate = new Date(); const monthNow = myDate.getMonth() + 1; const dayNow = myDate.getDate(); age = myDate.getFullYear() - yearBirth; if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) { age--; } } return age; }, getAgeByBirthday: function (_birthday) { /// <summary>根据出身年月获取年龄</summary> let age = 0; if (_birthday || _birthday != '0') { const yearBirth = _birthday.substring(0, 4); const monthBirth = _birthday.substring(4, 6); const dayBirth = _birthday.substring(6, 8); const myDate = new Date(); const monthNow = myDate.getMonth() + 1; const dayNow = myDate.getDate(); age = myDate.getFullYear() - yearBirth; if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) { age--; } } return age; }, imgToCompress: function (obj) { /// <summary>图片压缩</summary> const config = Object.assign( { path: '', // 图片地址,非空 size: { height: 300 * 2, width: 175 * 2, }, // 图片压缩比率 outputFormat: 'image/jpeg', // 图片输出类型 callback: function (base64Data) { // 回调函数 console.log(base64Data); }, }, obj, ); const getSize = function (image) { /// <summary>获取图片大小</summary> var size = { width: 100, height: 100, }; if (image.width > 0 && image.height > 0) { var ww = config.size.width / image.width; var hh = config.size.height / image.height; var rate = ww < hh ? ww : hh; if (rate <= 1) { size.width = image.width * rate; size.height = image.height * rate; } else { size.width = image.width; size.height = image.height; } } return size; }; var image = new Image(); // 新建一个img标签(不嵌入DOM节点,仅做canvas操作) image.src = config.path; // 让该标签加载base64格式的原图 image.onload = function () { if (image.complete) { // 当加载状态为完全结束时进入 var size = getSize(image); var canvas = document.createElement('canvas'); // 创建一个canvas元素 var context = canvas.getContext('2d'); // context相当于画笔,里面有各种可以进行绘图的API canvas.width = size.width; // 设置绘图的宽度 canvas.height = size.height; // 设置绘图的高度 context.drawImage(image, 0, 0, size.width, size.height); config.callback(canvas.toDataURL(config.outputFormat), size); } }; }, imgToBase64: function (path, callback, outputFormat) { /// <summary>图片转base64</summary> var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var img = new Image(); img.crossOrigin = 'Anonymous'; img.src = path; img.onload = function () { canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img, 0, 0); var dataURL = canvas.toDataURL(outputFormat || 'image/jpeg'); callback && callback(dataURL); }; }, /** * @Author: Jason Liu * @description: 转换数据单位格式 */ conversionUnitData(info, unit) { let val = info; let vUnit = ''; switch (unit) { case 'K': //千 val = val / 1000; vUnit = $t('千'); break; case 'W': //万 val = val / 10000; vUnit = $t('万'); break; case 'M': //百万 val = val / 1000000; vUnit = $t('百万'); break; case 'tenM': //千万 val = val / 10000000; vUnit = $t('千万'); break; case 'hundredM': //亿 val = val / 10000000; vUnit = $t('亿'); break; } return { value: val, unit: vUnit, }; }, table_format: { formatValue(row) { return row.cellValue; }, /** * @Author: Jason Liu * @description: 整数 */ formatInt(row) { return parseInt(row.cellValue); }, /** * @Author: Jason Liu * @description: 数字格式处理 */ formatNumber( row, option, config = { formatUnit: undefined, }, ) { if (row.cellValue || row.cellValue == 0) { let value = row.cellValue || 0; let unit = ''; if (config.formatUnit) { let con = service.conversionUnitData(value, config.formatUnit); value = con.value; unit = con.unit; } if (option) { //存在格式化字段 switch (option.type) { case 'per': value = value * 100; unit = '%'; value = value.toFixed(option.value, false) + unit; break; case 'norm': value = value.toFixed(option.value, false).toThousands(); break; default: if (!isNaN(option.value)) { value = value.toFixed(option.value, false); } break; } } if (config.formatUnit && unit != '%') { return value + unit; } else { return value || 0; } } else { return row.cellValue || ''; } }, formatTime(row, option) { let value = row.cellValue || ''; if (option && value) { //存在格式化字段 value = value.toDateCustomize(option); } return value; }, /** * @Author: Jason Liu * @description: 保留小数位 */ formatFloat(row, n) { return row.cellValue.toFixed(n); }, /** * @Author: Jason Liu * @description: 百分比显示 */ formatPercentage(row, n, unit = '%') { let result = row.cellValue * 100; return `${result.toFixed(n)}${unit}`; }, }, setCaches: function (name, info) { // 设置缓存数据 if (typeof info === 'object') { info = JSON.stringify(info); } localStorage.setItem(name, info ? escape(info) : undefined); }, getCaches: function (name, isjson = false) { // 获取缓存信息 let result = ''; const loca = localStorage.getItem(name); if (loca) { result = unescape(loca); if (isjson) { result = result.toJson(); } } return result; }, }; service._init(); export default service;