/**
* Util工具类
*/
const Util = {};
/**
* 控制台日志打印
*/
Util.debug = function () {
if (console && console.debug) {
console.debug.apply(console, arguments);
}
}
Util.log = function () {
if (console && console.log) {
console.log.apply(console, arguments);
}
}
Util.info = function () {
if (console && console.info) {
console.info.apply(console, arguments);
}
}
Util.warn = function () {
if (console && console.warn) {
console.warn.apply(console, arguments);
}
}
Util.error = function () {
if (console && console.error) {
console.error.apply(console, arguments);
}
}
/**
* 左边补足字符
*/
Util.leftPad = function (str, len, ch) {
str = String(str);
if (!ch && ch !== 0) ch = ' ';
let i = -1;
len = len - str.length;
while (++i < len) str = ch + str;
return str;
}
Util.isObject = function (obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
Util.isFunction = function (func) {
return typeof func === 'function';
}
Util.isArray = function (array) {
return Array.isArray(array);
}
Util.isNumber = function (number) {
return typeof number === 'number' && isFinite(number);
}
Util.isString = function (string) {
return string === string + ''
}
Util.isDate = function (date) {
return Object.prototype.toString.call(date) === '[object Date]';
}
Util.encodeHtml = function (str) {
if (!str || !str.length) return '';
str = str.replace(/&/g, '&');
str = str.replace(/>/g, '>');
str = str.replace(/</g, '<');
str = str.replace(/"/g, '"');
str = str.replace(/'/g, ''');
return str;
}
Util.decodeHtml = function (str) {
if (!str || !str.length) return '';
str = str.replace(/>/g, '>');
str = str.replace(/</g, '<');
str = str.replace(/"/g, '"');
str = str.replace(/'/g, "'");
str = str.replace(/'/g, "'");
str = str.replace(/&/g, '&');
return str;
}
Util.todayBegin = Util.todayStart = function () {
let date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
return date;
}
Util.nDaysBegin = Util.nDaysStart = function (days) {
if (Util.isNumber(days)) {
let today = Util.todayBegin().getTime();
return new Date(today - days * 24 * 3600 * 1000);
} else {
return Util.todayBegin();
}
}
Util.todayEnd = function () {
let date = new Date();
date.setHours(23);
date.setMinutes(59);
date.setSeconds(59);
return date;
}
Util.nDaysEnd = function (days) {
if (Util.isNumber(days)) {
let today = Util.todayEnd().getTime();
return new Date(today - days * 24 * 3600 * 1000);
} else {
return Util.todayEnd();
}
}
Util.formatMonthDayHour = function (date) {
if (date instanceof Date) {
let mon = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
mon = mon > 9 ? mon : `0${mon}`;
day = day > 9 ? day : `0${day}`;
hour = hour > 9 ? hour : `0${hour}`;
return `${mon}-${day} ${hour}:00`;
} else if (Util.isNumber(date)) {
return Util.formatMonthDayHour(new Date(date));
} else {
return date || 'N/A';
}
}
Util.formatDate = function (date) {
if (date instanceof Date) {
let year = date.getFullYear();
let mon = date.getMonth() + 1;
let day = date.getDate();
return year + '-' + (mon > 9 ? mon : '0' + mon) + '-' + (day > 9 ? day : '0' + day);
} else if (Util.isNumber(date)) {
const len = String(date).length;
if (len === 10) date = date * 1000;
if (len === 16) date = Math.floor(date / 1000);
return Util.formatDate(new Date(date));
} else {
return date || 'N/A';
}
}
Util.formatTime = function (date) {
if (date instanceof Date) {
let hour = date.getHours();
let min = date.getMinutes();
let sec = date.getSeconds();
return (hour > 9 ? hour : '0' + hour) + ':' + (min > 9 ? min : '0' + min) + ':' + (sec > 9 ? sec : '0' + sec);
} else if (Util.isNumber(date)) {
return Util.formatTime(new Date(date));
} else {
return date || 'N/A';
}
}
Util.formatDatetime = function (date) {
if (date instanceof Date) {
let year = date.getFullYear();
let mon = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let min = date.getMinutes();
let sec = date.getSeconds();
return year + '-' +
(mon > 9 ? mon : '0' + mon) + '-' +
(day > 9 ? day : '0' + day) + ' ' +
(hour > 9 ? hour : '0' + hour) + ':' +
(min > 9 ? min : '0' + min) + ':' +
(sec > 9 ? sec : '0' + sec);
} else if (Util.isString(date)) {
const len = String(date).length;
date = parseInt(date);
if (date <= 0) return 'N/A';
if (len === 10) date = date * 1000;
if (len === 16) date = Math.floor(date / 1000);
return Util.formatDatetime(new Date(date));
} else if (Util.isNumber(date)) {
const len = String(date).length;
if (len === 10) date = date * 1000;
if (len === 16) date = Math.floor(date / 1000);
return Util.formatDatetime(new Date(date));
} else {
return date || 'N/A';
}
}
Util.dateStrToSecond = function (dateStr) {
if (dateStr instanceof Date) {
return Math.floor(dateStr.getTime() / 1000);
} else if (dateStr.length) { // 格式如2016-10-10 10:00:00
try {
let date = new Date(dateStr.replace(/-/g, '/'));
return Math.floor(date.getTime() / 1000);
} catch (e) {
return 0;
}
} else {
return 0;
}
}
Util.calcDuration = function (seconds) {
const reg = /^[0-9]+$/;
if (!reg.test(String(seconds))) return '';
let [s, d, h, m] = [parseInt(seconds), 0, 0, 0];
let r = [];
if (s >= 86400) {
d = Math.floor(s / 86400);
r.push(d + 'D');
}
if (s >= 3600) {
h = Math.floor((s % 86400) / 3600);
r.push(h + 'H');
}
if (s >= 60) {
m = Math.floor(((s % 86400) % 3600) / 60);
r.push(m + 'M');
}
if (s > 0) {
s = Math.floor(s % 60);
r.push(s + 'S');
}
return r.join('');
}
Util.toNumArr = function (start, end, step) {
if (!Util.isNumber(start) || !Util.isNumber(end) || !Util.isNumber(step)) {
return [];
}
let maxCount = 10000;
let arr = [];
while (start <= end && maxCount-- > 0) {
arr.push(start);
start += step;
}
return arr;
}
Util.getExt = function (path) {
if (!path) return '';
var pos = path.lastIndexOf('.');
if (pos > 0 && pos < path.length) {
return path.substr(pos + 1);
}
return '';
}
Util.subStr = function (str, len) {
let slen = str && str.length || 0;
if (len > 0 && slen > len) {
return str.substr(0, len);
}
return str;
}
Util.copyProperties = function (obj) {
if (!obj) return {};
return Object.assign(obj, {});
}
Util.getTime = function (obj) {
if (obj === null || obj === undefined) {
return 0;
} else if (obj instanceof Date) {
return Math.floor(obj.getTime() / 1000);
} else {
let val = String(obj);
if (val.length < 10) {
return 0;
} else if (/^[1-9][0-9]{9,}$/g.test(val)) {
return parseInt(val.substr(0, 10));
} else {
val = val.replace(/-/g, '/');
try {
let date = new Date(val);
return date ? Math.floor(date.getTime() / 1000) : 0;
} catch (e) {
return 0;
}
}
}
}
Util.array2ParamObj = function (paramKey, array) {
if (!Array.isArray(array)) return {};
paramKey = paramKey || 'array';
let paramObj = {};
array.forEach((item, index) => {
Object.keys(item).forEach(key => {
let k = `${paramKey}[${index}].${key}`;
let v = item[key];
paramObj[k] = v;
});
});
return paramObj;
}
Util.percent = function (value, total) {
value = parseInt(value || 0);
if (value === 0) return 0;
total = parseInt(total || 0);
if (total === 0) return 100;
let percent = String(Math.round(value / total * 10000) / 100.00);
if (percent.length > 5) {
percent = percent.substr(0, 5);
}
return parseFloat(percent);
}
Util.isIE = function () {
return !!window.ActiveXObject || 'ActiveXObject' in window;
}
Util.ieVersion = function () {
let win = window;
let doc = window.document;
let input = doc.createElement('input');
if (win.ActiveXObject === undefined) return null;
if (!win.XMLHttpRequest) return 6;
if (!doc.querySelector) return 7;
if (!doc.addEventListener) return 8;
if (!win.atob) return 9;
// "!doc.body.dataset" is faster but the body is null when the DOM is not
// ready. Anyway, an input tag needs to be created to check if IE is being emulated.
if (!input.dataset) return 10;
return 11;
}
Util.fullscreen = function () {
try {
var docElm = document.documentElement;
if (docElm.requestFullscreen) { // W3C
docElm.requestFullscreen();
} else if (docElm.mozRequestFullScreen) { //FireFox
docElm.mozRequestFullScreen();
} else if (docElm.webkitRequestFullScreen) { //Chrome等
docElm.webkitRequestFullScreen();
} else if (docElm.msRequestFullscreen) { //IE11
docElm.msRequestFullscreen();
}
} catch (e) {
console && console.error && console.error(e);
}
}
Util.exitFullscreen = function () {
try {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
} catch (e) {
console && console.error && console.error(e);
}
}
Util.base64Encode = function (input) {
let rv = encodeURIComponent(input);
rv = unescape(rv);
rv = window.btoa(rv);
return rv;
}
Util.base64Decode = function (input) {
let rv = window.atob(input);
rv = escape(rv);
rv = decodeURIComponent(rv);
return rv;
}
Util.isArrayRepeat = function (array) {
if (!Array.isArray(array)) return false;
let map = {};
for (let i = 0; i < array.length; i++) {
let key = String(array[i]);
if (map.hasOwnProperty(key)) {
return true;
} else {
map[key] = 1;
}
}
map = null;
return false;
}
Util.width = function (id) {
let ele = document.getElementById(id);
return ele && ele.clientWidth || 0;
}
Util.height = function (id) {
let ele = document.getElementById(id);
return ele && ele.clientHeight || 0;
}
Util.arraySum = function (array) {
if (!Array.isArray(array) || array.length === 0) return 0;
let total = 0;
array.forEach(o => {
total += parseInt(o);
});
return total;
}
Util.downloadCsv = function (csvName, csvContent) {
if (!csvName) return;
// BOM防止乱码
var BOM = '\uFEFF';
csvContent = BOM + csvContent;
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURI(csvContent);
a.target = '_blank';
a.download = csvName.toLowerCase().endsWith('.csv') ? csvName : csvName + '.csv';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
Util.parseTime = function (time, cFormat) {
if (arguments.length === 0) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if (('' + time).length === 10) time = parseInt(time) * 1000
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return timeStr
}
Util.wrapStr = function (str, lineLen, separator) {
if (!str || lineLen <= 0) return '';
separator = separator || '<br>';
let index = 0;
const result = [];
while (index < str.length) {
const sub = str.substr(index, lineLen);
if (!sub) {
break;
}
result.push(sub);
if (sub.length < lineLen) {
break;
}
index += lineLen;
}
return result.join(separator);
}
Util.isJsonStr = function (str) {
if (!str) return false;
if (typeof str === 'string') {
try {
const obj = JSON.parse(str);
return obj && typeof obj === 'object';
} catch (e) {
return false;
}
}
}
Util.byteMBtoGB = function (num) {
if (!num) return 0
num = parseFloat(num) / 1024
return Math.round(num * 100.0) / 100
}
export default Util;