epmet pc工作端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

586 lines
15 KiB

//导出excel
// import FileSaver from 'file-saver'
// import XLSX from 'xlsx'
var crypto = require("crypto");
let Base64 = require("js-base64").Base64;
import Vue from "vue";
export default {
/**
*
* @param {*} messageObj
*/
validateRule(messageObj) {
let message = "";
for (var oneObj in messageObj) {
if (messageObj[oneObj][0].message) {
message = message + messageObj[oneObj][0].message + " <br/> ";
}
}
Vue.prototype.$message({
dangerouslyUseHTMLString: true,
message: message,
type: "error",
});
},
/**
* 日期格式化
* @param date
* @param fmt yyyy-MM-dd hh:mm:ss.SSS week
* @param offset:加减天数
* @returns {*}
*/
formatDate(date, fmt, offset) {
if (!date || !(date instanceof Date)) {
return date;
} else {
let d = new Date(date);
if (offset) {
if (offset.day) {
d.setDate(d.getDate() + offset.day);
}
if (offset.month) {
d.setMonth(d.getMonth() + offset.month);
}
}
let _date = {
"M+": d.getMonth() + 1, // 月份
"d+": d.getDate(), // 日
"h+": d.getHours(), // 小时
"m+": d.getMinutes(), // 分
"s+": d.getSeconds(), // 秒
"q+": Math.floor((d.getMonth() + 3) / 3), // 季度
S: d.getMilliseconds(),
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
(d.getFullYear() + "").substr(4 - RegExp.$1.length)
);
}
for (let _d in _date) {
if (new RegExp("(" + _d + ")").test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1
? _date[_d]
: ("00" + _date[_d]).substr(("" + _date[_d]).length)
);
}
}
if (/(week)/.test(fmt)) {
const weeks = ["日", "一", "二", "三", "四", "五", "六"];
fmt = fmt.replace(RegExp.$1, "星期" + weeks[d.getDay()]);
}
return fmt;
}
},
/**
* 获取当月第一天
* @param key
* @param value
*/
getFirstDayOfMonth(date) {
date.setDate(1);
return this.timeFormat(date);
},
timeFormat(date) {
if (!date || typeof date === "string") {
this.error("参数异常,请检查...");
}
var y = date.getFullYear(); //年
var m = date.getMonth() + 1; //月
if (m < 10) m = "0" + m;
var d = date.getDate(); //日
if (d < 10) d = "0" + d;
return y + "-" + m + "-" + d;
},
/**
* 获取当月第一天
* @param key
* @param value
*/
getFirstDayOfMonth(date) {
date.setDate(1);
return this.timeFormat(date);
},
timeFormat(date) {
if (!date || typeof date === "string") {
this.error("参数异常,请检查...");
}
var y = date.getFullYear(); //年
var m = date.getMonth() + 1; //月
if (m < 10) m = "0" + m;
var d = date.getDate(); //日
if (d < 10) d = "0" + d;
return y + "-" + m + "-" + d;
},
//日期时间格式转化工具类
dateFormatter(str, type) {
//默认返回yyyy-MM-dd HH-mm-ss
var hasTime = arguments[1] != false ? true : false; //可传第二个参数false,返回yyyy-MM-dd
var d = new Date(str);
var year = d.getFullYear();
var month =
d.getMonth() + 1 < 10 ? "0" + (d.getMonth() + 1) : d.getMonth() + 1;
var day = d.getDate() < 10 ? "0" + d.getDate() : d.getDate();
var hour = d.getHours() < 10 ? "0" + d.getHours() : d.getHours();
var minute =
d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes();
var second =
d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds();
if (type === "time" && hasTime) {
return (
[year, month, day].join("-") +
" " +
[hour, minute, second].join(":")
);
} else {
return [year, month, day].join("-");
}
},
/**
* 本地LocalStorage获取
* @param value
*/
getLocalStorage(key) {
if (arguments.length === 0) {
app.logger.warn("没有参数");
return;
}
if (!window || !window.localStorage) {
app.logger.error("您开启了秘密浏览或无痕浏览模式,请关闭!");
return;
}
return window.localStorage.getItem(key);
},
/**
* 本地LocalStorage存储
* @param key
* @param value
*/
setLocalStorage(key, value) {
if (
arguments.length === 0 ||
arguments.length === 1 ||
typeof value === "undefined"
) {
app.logger.warn("传参错误");
return;
}
if (!window || !window.localStorage) {
app.logger.error("您开启了秘密浏览或无痕浏览模式,请关闭!");
return;
}
if (typeof value === "object") {
window.localStorage.setItem(key, JSON.stringify(value));
} else {
window.localStorage.setItem(key, value);
}
},
/**
* 本地LocalStorage删除
* @param value
*/
delLocalStorage(key) {
if (arguments.length === 0) {
app.logger.warn("没有参数");
return;
}
if (!window || !window.localStorage) {
app.logger.error("您开启了秘密浏览或无痕浏览模式,请关闭!");
return;
}
window.localStorage.removeItem(key);
},
/**
* 本地SessionStorage存储
* @param key
* @param value
*/
sessionStorage(key) {
if (arguments.length === 0) {
app.logger.warn("没有参数");
return;
}
if (!window || !window.sessionStorage) {
app.logger.error("您开启了秘密浏览或无痕浏览模式,请关闭!");
return;
}
if (arguments.length === 1 || typeof value === "undefined") {
return window.sessionStorage.getItem(key);
} else if (value === null || value === "") {
window.sessionStorage.removeItem(key);
} else if (typeof value === "object") {
window.sessionStorage.setItem(key, JSON.stringify(value));
} else {
window.sessionStorage.setItem(key, value);
}
},
/**
* 获取本地SessionStorage存储
* @param key
*/
getSessionStorage(key) {
if (key != "") {
return window.sessionStorage.getItem(key);
} else {
return "";
}
},
/**
* MD5加密
* @param data
* @param salt
* @returns {*}
*/
md5(data, salt) {
if (!salt) {
salt = app.config.setting.salt;
}
let md5 = crypto.createHash("md5");
return md5.update(data + salt).digest("hex");
},
/**
* base64加密
* @param param
* @returns {*}
*/
base64Encode(code) {
if (code != "") {
return Base64.encode(code);
} else {
return code;
}
},
/**
* 验证
* @param type
* @param value
* @returns {boolean}
*/
validate(type, value) {
let pattern;
switch (type) {
case "ip":
// 一个IP字串,由四段组成,每一段是0~255的数字,段与段之间用小数点隔开
// 0~9 \d 单个数字
// 10~99 [1-9]\d 两位数
// 100~199 1\d\d 百位为1的三位数
// 200~249 2[0-4]\d 三位数,百位是2,十位是0~9
// 250~255 25[0-5] 三位数,百位是2,十位是5,个位是0~5
pattern =
/^(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.){3}([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])$/;
return pattern.test(value);
case "domain":
// 一个完整的域名,由根域、顶级域、二级、三级……域名构成,每级域名之间用点分开,每级域名由字母、数字和减号构成(第一个字母不能是减号),不区分大小写,长度不超过63
// 单独的名字可以由正则表达式[a-zA-Z0-9][-a-zA-Z0-9]{0,62}来匹配,而完整的域名至少包括两个名字(比如google.com,由google和com构成),最后可以有一个表示根域的点(在规范中,最后有一个点的才是完整域名,但一般认为包括两个以上名字的域名也是完整域名,哪怕它后面没有点)
pattern =
/^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?$/;
return pattern.test(value);
case "serverPort1":
pattern =
/^([1-9]\d{0,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;
return pattern.test(value);
case "paymentNo":
pattern = /^[\s\S]{0,16}$/;
return pattern.test(value);
}
return false;
},
/**
* 校验 IP地址、网关是否在同一个网段
* @param ip
* @param gateway
* @param mask
* @returns {boolean}
*/
checkIpMask(ip, gateway, mask) {
let ips = ip.split(".");
let gateways = gateway.split(".");
let masks = mask.split(".");
for (let i = 0, len = masks.length; i < len; i++) {
let _mask = masks[i];
if (_mask === "255") {
if ((parseInt(ips[i]) & 255) !== parseInt(gateways[i])) {
return false;
}
}
}
return true;
},
/**
* 是否移动端访问
* @return {boolean}
*/
mobile() {
const userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串
if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(userAgent)) {
return true;
}
return false;
},
// 表单验证:
/*
* type 格式 number string(数字和字母) tel float
* num 长度
*/
validateForm(type, num) {
if (type == "string") {
if (num) {
return new RegExp("^[0-9a-zA-Z]{" + num + "}$");
} else {
return /^[0-9a-zA-Z]*$/;
}
} else if (type == "tel") {
return /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
} else if (type == "number") {
// 数字类型
if (num) {
return new RegExp("^[0-9]{" + num + "}$");
} else {
return /^[0-9]*$/;
}
} else if (type == "float") {
if (num) {
return new RegExp(
"^(([1-9][0-9]*)|(([0].d{" +
num +
"}|[1-9][0-9]*.d{1,2})))$"
);
} else {
return /^(([1-9][0-9]*)|(([0]|[0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
}
} else if (type == "any") {
return /^[^ ]+$/;
} else if (type == "user") {
return /^[a-zA-Z0-9_-]{2,16}$/;
} else if (type == "phone") {
//联系电话码
return /^1\d{10}$/;
} else if (type == "email") {
//email
return /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
} else if (type == "identifyno") {
//身份证号
return /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;
}
},
debounce(func, wait, immediate) {
let timeout, args, context, timestamp, result;
const later = function () {
// 据上一次触发时间间隔
const last = +new Date() - timestamp;
// 上次被包装函数被调用时间间隔last小于设定时间间隔wait
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
// 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function (...args) {
context = this;
timestamp = +new Date();
const callNow = immediate && !timeout;
// 如果延时不存在,重新设定延时
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
},
/**
*map转化为对象object(map所有键都是字符串,可以将其转换为对象)
*/
strMapToObj(strMap) {
//debugger;
let obj = Object.create(null);
for (let [k, v] of strMap) {
obj[k] = v;
}
return obj;
},
/**
*对象object转换为Map
*/
objToStrMap(obj) {
let strMap = new Map();
for (let k of Object.keys(obj)) {
strMap.set(k, obj[k]);
}
return strMap;
},
/**
* 提示消息:response响应,message提示消息,type消息类型
*/
showMessage(showClose = true, message = "操作失败", type = "error") {
vm.$message({
showClose: showClose,
message: `${message}`,
type: type,
});
},
// exportExcel(name, dom) {
// //导出excel
// let wb = XLSX.utils.table_to_book(document.querySelector(dom))
// let wbout = XLSX.write(wb, {
// bookType: 'xlsx',
// bookSST: true,
// type: 'array'
// })
// try {
// FileSaver.saveAs(
// new Blob([wbout], {
// type: 'application/octet-stream'
// }),
// name + '.xlsx'
// )
// } catch (e) {
// if (typeof console !== 'undefined') console.log(e, wbout)
// }
// return wbout
// },
//获取浏览器类型
agentType() {
//debugger;
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isOpera = userAgent.indexOf("Opera") > -1;
if (isOpera) {
return "Opera";
} //判断是否Opera浏览器
if (userAgent.indexOf("Firefox") > -1) {
return "FF";
} //判断是否Firefox浏览器
if (userAgent.indexOf("Chrome") > -1) {
return "Chrome";
}
if (userAgent.indexOf("Safari") > -1) {
return "Safari";
} //判断是否Safari浏览器
if (userAgent.indexOf("Trident") > -1) {
// debugger;
return "IE";
} //判断是否IE浏览器
},
//接口验证token
async interfaceToken(interface_token) {
//没有保存token 调用接口获取
if (!this.sessionStorage("KEY_ACCESS_TOKEN")) {
let ret = false;
var params = {};
var tockenUrl = "";
var username = "";
//第三方调用密码默认为admin
var userpass = "admin";
var password = this.md5(userpass, app.config.setting.salt);
/*
if(arguments.length === 0 || typeof interface_token === 'undefined'){
params = {
grant_type: "password",
username: username,
password: password,
scope: "all"
};
}else{
*/
params = {
grant_type: "password",
esapikey: interface_token,
username: username,
password: password,
scope: "all",
};
//}
tockenUrl = app.api.common.loadToken;
await app.ajax.interfacetokenPost(
// 暂时固定url,防止前后端对接时,更改url无法登陆
tockenUrl,
params,
(data) => {
var access_token = data.access_token; //访问令牌
var token_type = data.token_type; //令牌类型,必须为bearer
var refresh_token = data.refresh_token; //刷新令牌,当访问令牌过期可使用刷新令牌获取新的访问令牌,刷新令牌的默认为15天,可设置
var expires_in = data.expires_in; //访问令牌的失效,1800秒,可设置
var scope = data.scope; //第三方权限范围
var jti = data.jti; //jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击
var userName = data.userExtraMessage.userName; //用户名
var userId = data.userExtraMessage.userId; //用户id
var userType = data.userExtraMessage.userType; //用户类型
// 存到sessionStorage
this.sessionStorage("KEY_USERID", userId);
this.sessionStorage("KEY_USERNAME", userName);
this.sessionStorage("KEY_ACCESS_TOKEN", access_token);
this.sessionStorage("KEY_TOKEN_TYPE", token_type);
this.sessionStorage(
"KEY_EXPIRES_IN",
new Date().getTime() + (expires_in - 300) * 1000
);
this.sessionStorage("KEY_REFRESH_TOKEN", refresh_token);
this.sessionStorage("USER_TYPE", userType);
this.sessionStorage("HOME_TYPE", "1");
this.sessionStorage("tenantCode", "");
//开启token刷新计时器
app.auth.refreshTokenTimer();
ret = true;
}
);
return ret;
} else {
return true;
}
},
//表格vue 接口页面不需要减去 title高度
titleHeight() {
if (
this.sessionStorage("es_interface") === null ||
this.sessionStorage("es_interface") === ""
) {
return 90;
} else {
return 0;
}
},
// 换肤加class函数
toggleClass(element, className) {
if (!element || !className) {
return;
}
element.className = className;
},
// 大写下划线转驼峰
capitalToHump(str) {
return str
.toLowerCase()
.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
return $1 + $2.toUpperCase();
});
},
};