import { parse } from 'qs'; import { get, isArray, isEmpty, isObject, map, omit, pick } from 'lodash'; import Moment from 'moment'; import Config from '@config/config'; // 遍历tree let loopTree = ({ data = [], _parent = null, childrenName = 'children', cbk = null }) => { data.map((item, index) => { item._index = _parent ? `${_parent._index}.${index}` : `${index}`; item._parentIndex = _parent && _parent._index || ''; if (cbk) { cbk(item, _parent) } if (!isEmpty(item[childrenName])) { loopTree({ ...arguments[0], data: item[childrenName], _parent: omit(item, childrenName), childrenName, cbk }) } }) }; let numberFormat = (n, d = 2, needPrefix = false, prefix = '¥') => { if (n === undefined || n === null) return ''; let displayPrefix = needPrefix ? prefix : ''; let s = n + ''; if (!d) d = 0; if (s.indexOf('.') == -1) s += '.'; s += new Array(d + 1).join('0'); if (new RegExp('^(-|\\+)?(\\d+(\\.\\d{0,' + (d + 1) + '})?)\\d*$').test(s)) { let s = '0' + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true; if (a == d + 2) { a = s.match(/\d/g); if (parseInt(a[a.length - 1]) > 4) { for (var i = a.length - 2; i >= 0; i--) { a[i] = parseInt(a[i]) + 1; if (a[i] == 10) { a[i] = 0; b = i != 1; } else break; } } s = a.join('').replace(new RegExp('(\\d+)(\\d{' + d + '})\\d$'), '$1.$2'); } if (b) s = s.substr(1); return displayPrefix + (pm + s).replace(/\.$/, ''); } return displayPrefix + this; }; /** * 在树中找到匹配当前id的层级 * * @param {*} tree * @param {*} id * @twoNam 第二个需要结合筛选的入参 * @returns */ let findNodeTree = (tree, id, name = 'resourceUrl',c_name,twoNam="")=> { for (const node of tree) { const str_ = twoNam ? (get(node,"parentName","") + get(node,twoNam,"")+'@'+get(node, name, '')) : get(node, name, ''); const key = str_; const children = c_name ? node[c_name] : get(node, 'resourceList', null); if (key === id) { return node; } else if (children) { const target = findNodeTree(children, id, name,c_name,twoNam); if (target != null) { return target; } } } return null; }; let queryToObj = () => { const url = window.location.href; const result = {}; const urlSplit = url.split('?'); const len = urlSplit.length - 1; const queryParam = urlSplit[len] || ''; queryParam .split('&') .filter(str => str !== '') .forEach(str => { const [key, value] = str.split('='); result[key] = value; }); return result; }; class Utils { static loopTree = loopTree; static findNodeTree = findNodeTree; static queryToObj = queryToObj; //多时区 static numberFormat = numberFormat; // 从url取值 name可以参数的key,或者多个key的数组 static getQueryString(name) { let search = window.location.hash.split('?')[1] || ''; let res = search.match(new RegExp(`${name}=(.*?)(&|$)`)); return res ? res[1] : ""; } /* * dateString 只支持 2019-05-28 15:11:19 时间格式 或者 1559027246000 时间戳格式 * */ static timeZone(dateString, format = 'YYYY-MM-DD HH:mm:ss') { let timeObj = { timeStamp: "", //时间戳 utcTime: "", //utc时间 utcTimeStamp: "", // utc时间戳 timeZone: "", //当前时区 currentZoneTime: "", //当前时区的时间 time: "",//时间戳直接转为时间 }; if (!dateString) return timeObj; if (dateString.indexOf("-") > -1 && dateString.length == 10) { dateString += " 00"; } //如果不开启时区效果, 则取消时区转换功能 // if (!Config.isTimeZone) { // timeObj.utcTime = dateString; // timeObj.currentZoneTime = dateString; // return timeObj; // } if (String(dateString).length == 10) dateString = dateString * 1000; //转为时间戳 timeObj.timeStamp = Date.parse(dateString); timeObj.utcTime = Moment.utc(timeObj.timeStamp).format(format); timeObj.timeZone = new Date().getTimezoneOffset() / 60; //获取时区 //当前时区时间等于 UTC时间加上时区偏差 timeObj.currentZoneTime = Moment(dateString).subtract(timeObj.timeZone, 'hour').format(format); timeObj.time = Moment(dateString).format(format); return timeObj; } // let reg = new RegExp('(^|&)' + name.trim() + '=([^&]*)(&|$)'); // let r = after.trim().match(reg); // if (r != null) { // return decodeURIComponent(r[2]); // } else { // return null; // } // } /* * dateString 只支持 2019-05-28 15:11:19 时间格式 或者 1559027246000 时间戳格式 * */ // static timeZone(dateString, format = 'YYYY-MM-DD HH:mm:ss') { // let timeObj = { // timeStamp: "", //时间戳 // utcTime: "", //utc时间 // utcTimeStamp: "", // utc时间戳 // timeZone: "", //当前时区 // currentZoneTime: "", //当前时区的时间 // time: "",//时间戳直接转为时间 // }; // if (!dateString) return timeObj; // if (dateString.indexOf("-") > -1 && dateString.length == 10) { // dateString += " 00"; // } // //如果不开启时区效果, 则取消时区转换功能 // if (!Config.isTimeZone) { // timeObj.utcTime = dateString; // timeObj.currentZoneTime = dateString; // return timeObj; // } // if (String(dateString).length == 10) dateString = dateString * 1000; // //转为时间戳 // timeObj.timeStamp = Date.parse(dateString); // timeObj.utcTime = Moment.utc(timeObj.timeStamp).format(format); // timeObj.timeZone = new Date().getTimezoneOffset() / 60; //获取时区 // //当前时区时间等于 UTC时间加上时区偏差 // timeObj.currentZoneTime = Moment(dateString).subtract(timeObj.timeZone, 'hour').format(format); // timeObj.time = Moment(dateString).format(format); // return timeObj; // } /* * 千分位组件,传入金额,返回千分位数字 * number {number} 需要格式化的数字 默认0 * precision {number} 需要保留的小数位,默认0 * prefix {string} 是否需要加金额前缀,默认false * */ static numberFormat({ number = 0, precision = 0, prefix = false }) { let isPlus = true; if (String(number).indexOf('-') > -1) { isPlus = false; number = Number(String(number).replace(/-/g, '')); } let displayPrefix = prefix ? prefix : ''; number = String(number).replace(/(^\s*)|(\s*$)/g, ""); if (isNaN(number) || !number) { return displayPrefix + parseFloat(0).toFixed(precision); } else { number = parseFloat(number).toFixed(precision) } number = number + ''; if (number) { let nums = number.split('.'); let num = nums[0].slice(nums[0].length % 3); let numBegin = nums[0].slice(0, nums[0].length % 3); number = numBegin + ((numBegin && num) ? ',' : '') + (num ? num.match(/\d{3}/g).join(',') : '') + (nums[1] ? '.' + nums[1] : '') } if (!isPlus) { number = '-' + number; } return displayPrefix + number; } /** * 字符串模板转换 ,将数据源对应{键}的值填入str * * @param {*} str 字符串 * @param {*} source 数据源 * @param {*} handle 处理函数 * @returns */ static strFormat(str, source, handle = () => { }) { if (str instanceof Function) { return str(source); } else if (!isObject(source)) { return str; } const data = { ...source }; const r = /{[^}]+}/; while (r.test(str)) { const key = str .match(r) .toString() .replace('{', '') .replace('}', ''); const value = get(data, key, []); const ids = this.toArray(value).filter(id => id != null); str = str.replace(r, ids.join(',')); handle(key, value); } return str; } /** * 对象转换成数组 * @param {*} source * @returns */ static toArray = function (source) { if (source instanceof Array) { return source; } else { const result = source != null ? [source] : []; return result; } } } export default Utils;