import store from '../../store';
import Api from '../../api';
import ApiSet from './ApiSet';
let Utils = function () {
return {
formatDate(value, fmt, emptyText) {
fmt = fmt || 'yyyy-MM-dd hh:mm:ss'
if (!value) return emptyText || ""
let getDate = new Date(value)
let o = {
'M+': getDate.getMonth() + 1,
'd+': getDate.getDate(),
'h+': getDate.getHours(),
'm+': getDate.getMinutes(),
's+': getDate.getSeconds(),
'q+': Math.floor((getDate.getMonth() + 3) / 3),
'S': getDate.getMilliseconds()
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (let k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
}
}
return fmt;
},
dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {
type: mime
});
},
GetPercent(num, total) {
num = parseFloat(num);
total = parseFloat(total);
if (isNaN(num) || isNaN(total)) {
return "-";
}
return total <= 0 ? "0%" : (Math.round(num / total * 10000) / 100.00)+"%";
},
imgFit(event) {
let pw = event.currentTarget.parentNode.offsetWidth
let ph = event.currentTarget.parentNode.offsetHeight
let w = event.target.width
let h = event.target.height
let className = w / pw >= h / ph ? 'w' : 'h'
event.target.className = className
},
tel(tel) {
if (isNaN(tel)) return
window.location.href = 'tel://' + tel
},
hideTel(cellValue) {
if (Number(cellValue) && String(cellValue).length === 11) {
var mobile = String(cellValue)
var reg = /^(\d{3})\d{4}(\d{4})$/
return mobile.replace(reg, '$1****$2')
} else {
return cellValue
}
},
/**
* 精确加法
* @param {*} arg1
* @param {*} arg2
*/
accAdd(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 (arg1 * m + arg2 * m) / m;
},
/**
* 精确减法
* @param {被减数} arg1
* @param {减数} arg2
*/
Subtr(arg1, arg2) {
var r1, r2, m, n;
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));
//last modify by deeka
//动态控制精度长度
n = (r1 >= r2) ? r1 : r2;
return ((arg1 * m - arg2 * m) / m).toFixed(n);
},
/**
* 精确乘法
* @param {*} arg1
* @param {*} arg2
*/
accMul(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);
},
/**
* 精确除法
* @param {被除数} arg1
* @param {除数} arg2
*/
accDiv(arg1, arg2) {
var r1 = arg1.toString(),
r2 = arg2.toString(),
m, resultVal, d = arguments[2];
m = (r2.split(".")[1] ? r2.split(".")[1].length : 0) - (r1.split(".")[1] ? r1.split(".")[1].length : 0);
resultVal = Number(r1.replace(".", "")) / Number(r2.replace(".", "")) * Math.pow(10, m);
return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)));
},
getTbUrl(id) {
return 'https://acs.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?data={%22itemNumId%22%3A%22' + id + '%22}'
},
getCurrentMonthFirst(time,skew) {
if(!time){
var date = new Date();
}else{
var date = time
}
let n = skew ? Number(skew) : 1
date.setDate(1);
var month = parseInt(date.getMonth() + n);
var day = date.getDate();
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return date.getFullYear() + '-' + month + '-' + day;
},
getCurrentMonthLast(time,skew) {
if(!time){
var date = new Date();
}else{
var date = time
}
console.log(this.formatDate(date)) //2020-07-01 00:00:00 选中月第一天
let n = skew ? Number(skew) : 1
var currentMonth = date.getMonth(); // 6月
console.log('currentMonth',currentMonth)
if(skew){
var nextMonth = currentMonth;
currentMonth = currentMonth + n
}else{
var nextMonth = ++currentMonth
}
var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
var oneDay = 1000 * 60 * 60 * 24;
var lastTime = new Date(nextMonthFirstDay - oneDay);
var month = parseInt(lastTime.getMonth() + 1);
var day = lastTime.getDate();
if (month < 10) {
month = '0' + month
}
if (day < 10) {
day = '0' + day
}
return date.getFullYear() + '-' + month + '-' + day;
},
formatDiffDate(diffTime) {
let date = {
day: 0,
hour: 0,
minute: 0,
second: 0,
};
if (diffTime <= 0) {
return date;
}
if (diffTime) {
//这边是重点
diffTime = diffTime / 1000;
date.day = Math.floor(diffTime / 86400);
date.hour = Math.floor(diffTime % 86400 / 3600);
date.minute = Math.floor(diffTime % 86400 % 3600 / 60);
date.second = Math.floor(diffTime % 86400 % 3600 % 60);
}
date.day = date.day < 10 ? '0' + date.day : date.day
date.hour = date.hour < 10 ? '0' + date.hour : date.hour
date.minute = date.minute < 10 ? '0' + date.minute : date.minute
date.second = date.second < 10 ? '0' + date.second : date.second
return date;
},
refReshUserInfo() {
Api.sendAxiosPromise({
method: "post",
url: ApiSet.getCurrentUserView
}).then(res => {
store.commit('SET_USERINFO', res.data || {});
}).catch((err) => {
console.log(err)
})
},
/**
* 获取时间数组
* @param {*} type 类型 [day, week, month]
* @param {*} size 数组长度 day: size天, week: 当前周往前的size周, month: 当前月往前的size月
*/
getTimeArr(type, size){
let timeArr = []
let nowTime = new Date().getTime();
let dayTime = 24 * 60 * 60 * 1000
for (let i = 1; i <= size; i++) {
if(type == 'day'){
let time = nowTime - i * dayTime
let date = new Date(time)
let year = date.getFullYear()
let month = date.getMonth() + 1
month = month < 10 ? '0' + month : month
let day = date.getDate()
day = day < 10 ? '0' + day : day
timeArr.push({
value: year + month + day,
label: month + '月' + day + '日'
})
}else if(type == 'week'){
let time = nowTime - (i * 7 * dayTime)
let date = new Date(time)
let timeLabel = this.getWeekSatrtAndEnd(date, 'MM月dd日')
let timeValue = this.getWeekSatrtAndEnd(date, 'yyyyMMdd')
timeArr.push({
value: timeValue[0] + '-' + timeValue[1],
label: timeLabel[0] + '-' + timeLabel[1]
})
}else if(type == 'month'){
var date = new Date(nowTime);
date.setMonth(date.getMonth() - i);//每次循环一次 月份值减1
var m = date.getMonth() + 1;
m = m < 10 ? "0" + m : m;
timeArr.push({
value: date.getFullYear() + (m),
label: date.getFullYear() + "年" + (m) + '月'
})
}
}
return timeArr
},
/**
* 传入时间 获取该时间所在周的 第一天(星期一)和最后一天(星期天)
* @param {*} now 当前时间
* @param {*} fmt 时间格式 默认'yyyy-MM-dd'
* @param {*} skew 偏移量 -1 上一周 1 下一周
*/
getWeekSatrtAndEnd(now, fmt, skew){
var day = now.getDay()
var week = "1234567"
var first = 0 - week.indexOf(day)
first = skew && !isNaN(skew) ? first + 7*skew : first
var f = new Date(now)
f.setDate(now.getDate() + first)
var last = 6 - week.indexOf(day)
last = skew && !isNaN(skew) ? last + 7*skew : last
var l = new Date(now)
l.setDate(now.getDate() + last);
f = this.formatDate(f, fmt || 'yyyy-MM-dd')
l = this.formatDate(l, fmt || 'yyyy-MM-dd')
return [f, l]
},
/**
* 传入类型, 获取当前时间和当前时间往前推[n->根据time决定]n天的日期
* @param {*} time [today=当天][yesterday=昨天][week=今天往前推一周--今天][thisMonth=这个月的第一天--这个月的最后一天][month=今天往前推30天--今天]
* @return {startTime: 开始时间, endTime: 结束时间}
*/
getTimeBetween(time) {
let nowTime = new Date().getTime();
let startTime = ''
let endTime = ''
if (time == 'today') {
startTime = this.formatDate(nowTime, 'yyyy-MM-dd') + ' 00:00:00';
endTime = this.formatDate(nowTime, 'yyyy-MM-dd') + ' 23:59:59';
} else if (time == 'yesterday') {
let diffTime = nowTime - 24 * 60 * 60 * 1000
startTime = this.formatDate(diffTime, 'yyyy-MM-dd') + ' 00:00:00';
endTime = this.formatDate(diffTime, 'yyyy-MM-dd') + ' 23:59:59';
} else if (time == 'week') {
let diffTime = nowTime - 6 * 24 * 60 * 60 * 1000
startTime = this.formatDate(diffTime, 'yyyy-MM-dd') + ' 00:00:00';
endTime = this.formatDate(nowTime, 'yyyy-MM-dd') + ' 23:59:59';
} else if (time == 'thisMonth') {
let start = this.getCurrentMonthFirst()
let end = this.getCurrentMonthLast()
startTime = this.formatDate(start, 'yyyy-MM-dd') + ' 00:00:00';
endTime = this.formatDate(end, 'yyyy-MM-dd') + ' 23:59:59';
} else if (time == 'month') {
let diffTime = nowTime - 30 * 24 * 60 * 60 * 1000
startTime = this.formatDate(diffTime, 'yyyy-MM-dd') + ' 00:00:00';
endTime = this.formatDate(nowTime, 'yyyy-MM-dd') + ' 23:59:59';
}
return {
startTime: startTime,
endTime: endTime
}
},
/**
* 根据开始时间和结束时间计算时间差
* @param {*} startTime
* @param {*} endTime
*/
diffTime(startTime, endTime) {
if (!startTime || !endTime) {
return ''
}
if(typeof startTime !== String) {
startTime = String(startTime)
}
if(typeof endTime !== String) {
endTime = String(endTime)
}
startTime = startTime.replace(/-/g, "/")
endTime = endTime.replace(/-/g, "/")
var dateDiff = new Date(endTime).getTime() - new Date(startTime).getTime(); //时间差的毫秒数
var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
var leave1 = dateDiff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
var hours = Math.floor(leave1 / (3600 * 1000)) //计算出小时数
//计算相差分钟数
var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
var minutes = Math.floor(leave2 / (60 * 1000)) //计算相差分钟数
//计算相差秒数
var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
var seconds = Math.round(leave3 / 1000)
var leave4 = leave3 % (60 * 1000) //计算分钟数后剩余的毫秒数
var minseconds = Math.round(leave4 / 1000)
var timeFn = "";
if (dayDiff) {
timeFn = timeFn + dayDiff + "天 "
}
if (hours) {
timeFn = timeFn + hours + "小时 "
}
if (minutes) {
timeFn = timeFn + minutes + "分 "
}
if (seconds) {
timeFn = timeFn + seconds + "秒"
}
return timeFn;
},
/**
* 毫秒数换算成 年月日时分秒
* @param {*} result 毫秒数
* @param {true: 忽略秒, false: 需要精确到秒} disSecond 是否忽略秒
*/
secondToDate(result, disSecond) {
var h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
var m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
var s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
let timeFn = ""
if (!isNaN(h) && Number(h) > 0) {
timeFn = timeFn + h + "小时 "
}
if (!isNaN(m) && Number(m) > 0) {
timeFn = timeFn + m + (disSecond ? "分钟 " : "分 ")
}
if (!isNaN(s) && Number(s) > 0 && !disSecond) {
timeFn = timeFn + s + "秒"
}
return timeFn;
},
/**
* 生日换算年龄
* @param {*} strBirthday 生日
*/
birthdayTotAge(strBirthday){
if(!strBirthday){
return ''
}
let returnAge;
let strBirthdayArr=strBirthday.split("-");
let birthYear = strBirthdayArr[0];
let birthMonth = strBirthdayArr[1];
let birthDay = strBirthdayArr[2];
let d = new Date();
let nowYear = d.getFullYear();
let nowMonth = d.getMonth() + 1;
let nowDay = d.getDate();
if(nowYear == birthYear){
returnAge = 0;//同年 则为0岁
}else{
let ageDiff = nowYear - birthYear ; //年之差
if(ageDiff > 0){
if(nowMonth == birthMonth) {
let dayDiff = nowDay - birthDay;//日之差
if(dayDiff < 0){
returnAge = ageDiff - 1;
}else{
returnAge = ageDiff ;
}
}else{
let monthDiff = nowMonth - birthMonth;//月之差
if(monthDiff < 0){
returnAge = ageDiff - 1;
}else{
returnAge = ageDiff ;
}
}
}else{
returnAge = ageDiff;//返回-1 表示出生日期输入错误 晚于今天
}
}
return returnAge;//返回周岁年龄
},
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";
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
},
fixImg(url) {
if (!url) {
return ''
}
return url.indexOf('http') === -1 ? 'https:' + url : url;
},
download(src) {
var filename; //图片名称
var filetype; //图片类型
var path = src;
if (path.indexOf("/") > 0) {
var file = path.substring(path.lastIndexOf("/") + 1, path.length);
var fileArr = file.toLowerCase().split(".");
filename = fileArr[0];
filetype = fileArr[1];
}
var canvas = document.createElement("canvas");
var img = document.createElement("img");
img.onload = function (e) {
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext("2d");
context.drawImage(img, 0, 0, img.width, img.height);
canvas.toBlob(blob => {
var a = document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = filename;
a.click();
}, `image/${filetype}`);
};
img.setAttribute("crossOrigin", "Anonymous");
img.src = src;
},
downloadfile(url, strFileName, strMimeType) {
var xmlHttp = null;
if (window.ActiveXObject) {
// IE6, IE5 浏览器执行代码
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlHttp = new XMLHttpRequest();
}
//2.如果实例化成功,就调用open()方法:
if (xmlHttp != null) {
xmlHttp.open("get", url, true);
xmlHttp.responseType = 'blob'; //关键
xmlHttp.send();
xmlHttp.onreadystatechange = doResult; //设置回调函数
}
function doResult() {
if (xmlHttp.readyState == 4) { //4表示执行完成
if (xmlHttp.status == 200) { //200表示执行成功
download(xmlHttp.response, strFileName, strMimeType);
}
}
}
},
getFileType(fileName) {
// 后缀获取
let suffix = '';
// 获取类型结果
let result = '';
try {
const flieArr = fileName.split('.');
suffix = flieArr[flieArr.length - 1];
} catch (err) {
suffix = '';
}
// fileName无后缀返回 false
if (!suffix) {
return false;
}
suffix = suffix.toLocaleLowerCase();
// 图片格式
const imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];
// 进行图片匹配
result = imglist.find(item => item === suffix);
if (result) {
return 'image';
}
// 匹配txt
const txtlist = ['txt'];
result = txtlist.find(item => item === suffix);
if (result) {
return 'txt';
}
// 匹配 excel
const excelist = ['xls', 'xlsx'];
result = excelist.find(item => item === suffix);
if (result) {
return 'excel';
}
// 匹配 word
const wordlist = ['doc', 'docx'];
result = wordlist.find(item => item === suffix);
if (result) {
return 'word';
}
// 匹配 pdf
const pdflist = ['pdf'];
result = pdflist.find(item => item === suffix);
if (result) {
return 'pdf';
}
// 匹配 ppt
const pptlist = ['ppt', 'pptx'];
result = pptlist.find(item => item === suffix);
if (result) {
return 'ppt';
}
// 匹配 视频
const videolist = ['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', 'm4v'];
result = videolist.find(item => item === suffix);
if (result) {
return 'video';
}
// 匹配 音频
const radiolist = ['mp3', 'wav', 'wmv'];
result = radiolist.find(item => item === suffix);
if (result) {
return 'radio';
}
// 其他 文件类型
return 'other';
},
toW(count, fixed, uom){
if(isNaN(count)){
return 0;
}
if(count < 10000){
return count;
}
fixed = fixed || 0
return `${(count / 10000).toFixed(fixed)}${uom || 'W'}`;
},
toY(value, fixed){
if(!value || isNaN(value)){
return 0
}
let isMinus = false
let param = {};
let k = 10000,
sizes = ['', '万', '亿', '万亿'],
i;
if(value < 0){
isMinus = true
value = -value
}
if(value < k){
param.value = value
param.unit=''
}else{
i = Math.floor(Math.log(value) / Math.log(k));
param.value = value / Math.pow(k, i);
param.unit = sizes[i];
}
if(param.value && param.value.toString().split('.')[1] && param.value.toString().split('.')[1].length > fixed){
param.value = Number(param.value).toFixed(fixed)
}
if(isMinus){
return -param.value + param.unit;
}
return param.value + param.unit;
},
isIE() {
if (!!window.ActiveXObject || "ActiveXObject" in window) {
return true
} else {
return false
}
},
/**
* 树转列表
* @param {*} tree
*/
treeToList(tree){
let list = []; //结果lsit
for(let i in tree){
let node = tree[i];
if (node.children.length !== 0) { //遍历树的第一层
//第一层加入到list中
list.push({
name: node.name,
numGoods: node.numGoods,
abbrev:node.abbrev,
position:node.position,
hidden:node.hidden
});
this.toListDF(node.children, list); //遍历子树,并加入到list中.
}
}
return list;
},
toListDF (tree, list) {
for (let i in tree) { //遍历最上层
//将当前树放入list中
let node = tree[i];
list.push({
name: node.name,
numGoods: node.numGoods,
abbrev:node.abbrev,
position:node.position,
hidden:node.hidden
});
//如果有子结点,再遍历子结点
if (node.children && node.children.length !== 0) {
this.toListDF(node.children, list) //递归
}
}
},
strToDate(time,fmt){
fmt = fmt || 'yyyy-MM-dd hh:mm:ss'
let pattern = /(\d{4})(\d{2})(\d{2})/
let newTime = time.replace(pattern, '$1-$2-$3')
newTime = this.formatDate(newTime,fmt)
return newTime
},
getWeek(dt) {
let d1 = new Date(dt);
let d2 = new Date(dt);
let year = d1.getFullYear()
d2.setMonth(0);
d2.setDate(1);
let rq = d1 - d2;
let days = Math.ceil(rq / (24 * 60 * 60 * 1000));
let num = Math.ceil(days / 7);
return year + '第' + (num+1) + '周';
},
floatSub(arg1, arg2) {
var r1 = arg1.toString(),
r2 = arg2.toString(),
m, resultVal, d = arguments[2];
m = (r2.split(".")[1] ? r2.split(".")[1].length : 0) - (r1.split(".")[1] ? r1.split(".")[1].length : 0);
resultVal = Number(r1.replace(".", "")) / Number(r2.replace(".", "")) * Math.pow(10, m);
return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)));
},
$undefined(val){
if(typeof(val) == "undefined"){
return true
}else{
return false
}
},
$null(val){
if (!val && typeof(val)!="undefined" && val!=0){
return true
}else{
return false
}
},
$emptyObj(obj){
if(Object.prototype.isPrototypeOf(obj) && Object.keys(obj).length === 0){
return true
}else{
return false
}
},
$emptyArr(arr){
if(Array.prototype.isPrototypeOf(arr) && arr.length === 0){
return true
}else{
return false
}
},
$show(val){
// 1 判断类型 undefined,object
if(typeof val == 'undefined'){
// undefined
console.log('undefined')
return false
}else{
// object
if(this.$null(val)){
console.log('null')
return false
}else{
// 判断空对象空数组
if(JSON.stringify(val) === '{}'){
console.log('空对象')
return false
}else if(JSON.stringify(val) === '[]'){
console.log('空数组')
return false
}else{
console.log('可以渲染')
return true
}
}
}
},
isObject (value) {
const type = typeof value
return value !== null && (type === 'object' || type === 'function')
},
merge (source, other) {
if (!this.isObject(source) || !this.isObject(other)) {
return other === undefined ? source : other
}
return Object.keys({
...source,
...other
}).reduce((acc, key) => {
acc[key] = this.merge(source[key], other[key])
return acc
}, Array.isArray(source) ? [] : {})
},
timeDiff(endTime, startTime, isLiving){
let nowTime = new Date().getTime() / 1000
if(isLiving && endTime > nowTime){
return nowTime - startTime
}
return endTime - startTime
},
/**
* @description 累加去重
* @param {Array} arr
* @returns {obj} obj
*/
uniqueCount(arr){
var obj = {},i=0
for(i;i<arr.length;i++){
if(arr[i] == null || arr[i] == '') continue
if(obj.hasOwnProperty(arr[i])){
obj[arr[i]]++
}else{
obj[arr[i]] = 1
}
}
return obj
}
}
}();
export default Utils;