【js】【笔记】普通js常用util.js
//upd20240306-saveTxt-formatTime-formSubmitRedrict-copyText-arrayToTable-signData-ReSetWebSocket-IsPointInPoly-GetCenterPointInPoly-autoIframeWidth
//--wx-fyAuth
var util = {
//保存文本
saveTxt: function (filname, stringData) {
// 保存的文件名称 filname
// // 要保存的字符串
// const stringData = '一段文本.'
// dada 表示要转换的字符串数据,type 表示要转换的数据格式
const blob = new Blob([stringData], {
type: "text/plain;charset=utf-8"
})
// 根据 blob生成 url链接
const objectURL = URL.createObjectURL(blob)
// 创建一个 a 标签Tag
const aTag = document.createElement('a')
// 设置文件的下载地址
aTag.href = objectURL
// 设置保存后的文件名称
aTag.download = filname + ".txt"
// 给 a 标签添加点击事件
aTag.click()
// 释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。
// 当你结束使用某个 URL 对象之后,应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。
URL.revokeObjectURL(objectURL)
},
//返回上一个页面
breakpage: function (p) {
if (p == undefined) {
p = -1;
}
window.location.href = "javascript:history.go(" + p + ")";
},
//时间转换
convertTime: function (val) {
var date;
if (typeof val == 'string' && val.indexOf("Date") <= -1) {
date = new Date(val);
} else {
var re = /-?\d+/;
var m = re.exec(val);
date = new Date(parseInt(m[0]));
}
return date;
},
//时间格式化显示
formatTime: function (val, format) {
if (val == '' || val == null) {
return '';
}
var date;
if (typeof val == 'string' && val.indexOf("Date") <= -1) {
date = new Date(val);
} else if (typeof val == 'object') {
//时间格式
date = val;
}
else {
var re = /-?\d+/;
var m = re.exec(val);
date = new Date(parseInt(m[0]));
}
if (format || format != null) {
var o = {
"M+": date.getMonth() + 1, //month
"d+": date.getDate(), //day
"H+": date.getHours(), //hour
"m+": date.getMinutes(), //minute
"s+": date.getSeconds(), //second
"q+": Math.floor((date.getMonth() + 3) / 3), //quarter
"S": date.getMilliseconds() //millisecond
}
if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
(date.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length == 1 ? o[k] :
("00" + o[k]).substr(("" + o[k]).length));
}
return format;
},
formatTime2: function (time) {
//var time = new Date()
return time.toLocaleDateString().replace(/\//g, "-") + " " + time.toTimeString().substr(0, 8);
},
//表单提交重定向
formSubmitRedrict: function (url, datas, method, target, bc) {
var tempFormName = 'tempForm';
for (var i = 0; document.getElementById(tempFormName) != undefined; i++) {
tempFormName = 'tempForm' + i;
}
var tempForm = document.createElement("form");
tempForm.id = tempFormName;
tempForm.method = method == undefined ? "post" : method;
tempForm.action = url;
tempForm.target = target == undefined ? "" : target;
for (var i = 0; i < datas.length; i++) {
var hideInput = document.createElement("input");
hideInput.type = "hidden";
hideInput.name = datas[i].name;
hideInput.value = datas[i].value;
tempForm.appendChild(hideInput);
}
if (bc == undefined) {
bc = function () { }
}
if (document.all) {
tempForm.attachEvent("onsubmit", bc); //IE
} else {
tempForm.addEventListener("submit", bc); //firefox
}
document.body.appendChild(tempForm);
if (document.all) {
tempForm.fireEvent("onsubmit");
} else {
tempForm.dispatchEvent(new Event("submit"));
}
tempForm.submit();
document.body.removeChild(tempForm);
},
//copy到剪切板
copyText: function (data, cb) {
//data==={text: OrderNo,target:$event.target }
//创建隐藏的标签
var textArea;
try {
textArea = document.createElement("<textarea></textarea>");
} catch (e) {
textArea = document.createElement("textarea");
}
textArea.textContent = data.text;
//不显示出来
textArea.style.width = '1px';
textArea.style.height = '1px';
textArea.style.color = textArea.style.backgroundColor;
//定位,不滚动
if (!data.target) {
data.target = document.body;
}
data.target.appendChild(textArea);
textArea.select(); // 选择对象
var res = false;
try {
res = document.execCommand("copy");//复制
} catch (err) {
data.target.removeChild(textArea);
console.log('该浏览器不支持点击复制到剪贴板');
}
if (cb && typeof cb == "function") {
cb(res)
}
data.target.removeChild(textArea);
},
//生成【类型-名称】获取器,本地session存储,可用于过滤器调用
GetTypeNameModel: function (op) {
var model = {
sessionStorageKey: op.sessionStorageKey,//此类型在本地session中key值
apiUrl: op.apiUrl,//此类型列表获取接口
idKey: op.idKey,//此类型在对象中id标识字段名
nameKey: op.nameKey,//此类型在对象中显示名称字段名
list: [],
getList: function () {
var list = sessionStorage.getItem(model.sessionStorageKey);
if (list) {
model.list = JSON.parse(list);
} else {
ajaxProtogenesis.ajax("post", model.apiUrl, true, {}, function (res) {
model.list = res.RetData;
sessionStorage.setItem(model.sessionStorageKey, JSON.stringify(model.list));
})
}
},
getName: function (id) {//根据类型获取名称的方法
if (model.list == [] || model.length == 0) {
model.getList();
}
var res = '';
if (model.list && model.list.length > 0) {
for (var i = 0; i < model.list.length; i++) {
if (model.list[i][model.idKey] == id) {
res = model.list[i][model.nameKey];
break;
}
}
}
return res;
}
};
model.getList();
return model;
},
//数组转为二维数组形式成表格的行
arrayToRow: function (model, all, rowNo, maxCell, defaultData) {
//model行的数组,all所有数据数组,rowNo当前行下标,maxCell总列数,defaultData数据不存在时用默认值填充
//获取当前这行数据
var row = [];
for (var i = 0; i < maxCell; i++) {
if (all.length > rowNo * maxCell + i) {
row.push(all[rowNo * maxCell + i]);
} else {
row.push(defaultData)
}
}
model.push(row);
rowNo++;//下一行下标
if (all.length > rowNo * maxCell) {
this.arrayToRow(model, all, rowNo, maxCell, defaultData);
}
return model;
},
//数组转为二维数组形式成表格
arrayToTable: function (all, maxRow, maxCell, def) {
//all所有数据数组,单张表maxRow总行数,maxCell总列数,def默认值。
//每张表的数据数组
var tableDatas = [];
util.arrayToRow(tableDatas, all, 0, maxRow * maxCell, def);
//为表获取行
var tables = [];
for (var i = 0; i < tableDatas.length; i++) {
var rows = [];
rows = util.arrayToRow(rows, tableDatas[i], 0, maxCell, def);
tables[i] = rows;
}
return tables;
},
//数组转为二维数组形式成表格_示例
arrayToTableTest: function () {
var all = [];
for (var i = 0; i < 97; i++) {
all.push(i + 1);
}
var t96 = this.arrayToTable(all, 12, 8, {})
console.log(t96);
return t96;
},
//添加属性到util,用合并对象的方式,用来给全局调用的属性,但要注意属性名称冲突
addAssign: function (obj) {
Object.assign(util, obj);
},
//对象格式时间参数和数组
objFormat: function (data) {
if (!data) {
return data;
}
var newData = data;
if (data instanceof Date || (typeof (data) == "string" && data.indexOf("/Date(") > -1)) {
// debugger
newData = this.formatTime(data, "yyyy-MM-dd HH:mm:ss");
} else if (data instanceof Array) {
newData = [];
if (data.length > 0) {
for (let i = 0; i < data.length; i++) {
newData.push(this.objFormat(data[i]));
}
}
} else if (typeof (data) == "object") {
for (var item in data) {
newData[item] = this.objFormat(data[item]);
}
}
return newData;
},
//对象排序,并格式时间参数和数组
objSortAndFormat: function (data) {
var par = [];
for (var i in data) {
par.push(i);
}
par.sort();
var newData = {};
for (let i = 0; i < par.length; i++) {
var item = par[i];
newData[item] = this.objFormat(data[item]);
}
return newData;
},
//给数据对象排序并动态签名,返回值newData有属性sing为签名值。需全局或传入Base64和md5
signData: function (data, signkey, _Base64, _md5) {
if (_Base64) {
Base64 = _Base64;
}
if (_md5) {
md5 = _md5;
}
//var signkey = "*****";
//参数data
if (!data) { data = {}; }
//设置签名时间
data.signtime = new Date().getTime();
//参数排序
var newData = this.objSortAndFormat(data);
//设置签名
var staticParameter = JSON.stringify(newData);
var signOld = staticParameter;
signOld = signOld.replaceAll(" ", "")
signOld = signOld.replaceAll("\\\"", "\"")
//手动处理一下encodeURIComponent没有编码的字符
var ignoreStr = "-_.!~*'()";
for (let ign = 0; ign < ignoreStr.length; ign++) {
signOld = signOld.replaceAll(ignoreStr[ign], "a");
}
//url编码
signOld = encodeURIComponent(signOld).toLowerCase();
//base64编码
signOld = Base64.encode(signOld);
//md5
var sign = md5(signOld + signkey);
newData.sign = sign;
return newData;
// encodeURI和encodeURIComponent区别
// var set1 = ";,/?:@&=+$"; // 保留字符
// var set2 = "-_.!~*'()"; // 不转义字符
// var set3 = "#"; // 数字标志
// var set4 = "ABC abc 123"; // 字母数字字符和空格
// console.log(encodeURI(set1)); // ;,/?:@&=+$
// console.log(encodeURI(set2)); // -_.!~*'()
// console.log(encodeURI(set3)); // #
// console.log(encodeURI(set4)); // ABC%20abc%20123 (the space gets encoded as %20)
// console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24
// console.log(encodeURIComponent(set2)); // -_.!~*'()
// console.log(encodeURIComponent(set3)); // %23
// console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encoded as %20)
},
//【WebSocket】
WebSocketList: [],
GetWebSocket: function (path, protocols, onopen, onmessage, onclose, onerror) {
if (path[path.length - 1] != "/") {
path = path + "/";
}
if (this.WebSocketList[path]) {
return this.WebSocketList[path];
} else {
return this.ReSetWebSocket(path, protocols, onopen, onmessage, onclose, onerror);
}
},
//WebSocket,含例
ReSetWebSocket: function (path, protocols, onopen, onmessage, onclose, onerror) {
if (path[path.length - 1] != "/") {
path = path + "/";
}
//path:要连接的 URL,WebSocket 服务器将响应的 URL。
//protocols(可选) :一个协议字符串或者一个包含协议字符串的数组。
//if (this.WebSocketList[path]) {
// return this.WebSocketList[path];
//}
//创建一个webSocket实例,执行后,客户端就会与服务端连接
var ws;
if (protocols) {
ws = new WebSocket(path, protocols);
} else {
ws = new WebSocket(path);
}
//事件:
var that = this;
//当WebSocket创建成功时,触发onopen事件,在onopen中再发送数据
ws.onopen = function (e) {
console.log("onopen");
console.log(e);
if (onopen) {
onopen(e);
}
};
//当客户端收到服务端发来的消息时,触发onmessage事件
ws.onmessage = function (e) {
console.log("onmessage:");
console.log(e);
if (onmessage) {
onmessage(e);
}
};
//当客户端收到服务端发送的关闭连接请求时,触发onclose事件
ws.onclose = function (e) {
console.log("onclose:");
console.log(e);
that.WebSocketList[e.target.url] = undefined;
if (onclose) {
onclose(e);
}
};
//如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
ws.onerror = function (e) {
console.log("onerror:");
console.log(e);
if (onerror) {
onerror(e);
}
};
this.WebSocketList[path] = ws;
return ws;
/*
例WebSocket
//打印询问窗口_京东
scope.WayBillPrinterTools_JD = function (item, printType) {
var lindex = layer.confirm('确定开始打印京东面单?', {
}, function () {
layer.close(lindex)
scope.PrintFacialList_JD(item, printType, 3);
});
}
//获取打印数据_京东
scope.PrintFacialList_JD = function (item, printType) {
var info = angular.copy(scope.SearchInfo);
if (printType == 0) {
info.SFOrderNo = item.SFOrderNo
}
Ajax.post("PrintSFOrderList_JD", { s: info }, function (result) {
if (result != null) {
console.log(result);
scope.Print_JD([result]);
} else {
layer.alert("获取打印数据失败", {
skin: 'layui-layer-lan'
, closeBtn: 1
});
}
});
}
//执行打印_京东
scope.Print_JD = function (list) {
layer.alert("打印中", {
skin: 'layui-layer-lan'
, closeBtn: 1
});
var url = "ws://127.0.0.1:9113";
//list[0].orderType = "PRE_View";//单据或指令类型 1、PRE_View 打印预览(默认预览第一张面单,所有面单预览传PRE_View:multi) 2、GET_Printers 获取打印机列表 3、PRINT 打印
util.ReSetWebSocket(url, null, function (e, ws) {
for (var i = 0; i < list.length; i++) {
ws.send(JSON.stringify(list[i]));
}
}, function (e, ws) {
var msg = "";
try {
var ed = JSON.parse(e.data);
if (ed.success == "true") {
msg = "打印成功";
scope.ModifyPrintState(ed.key)
} else {
msg = "打印失败";
}
if (ed.key == list[list.length - 1].key) {
layer.closeAll();
layer.alert(msg, {
skin: 'layui-layer-lan'
, closeBtn: 1
});
}
return;
} catch (e) {
msg = "打印失败";
}
layer.closeAll();
layer.alert(msg, {
skin: 'layui-layer-lan'
, closeBtn: 1
});
return;
}, null, function (e, ws) {
console.log(e);
layer.closeAll();
layer.alert("打印错误", {
skin: 'layui-layer-lan'
, closeBtn: 1
});
});
}
//打印全部京东面单
scope.WayBillPrinterTools_JD_List = function () {
var lindex = layer.confirm('确定开始打印全部京东面单?', {
}, function () {
layer.close(lindex)
scope.PrintFacialList_JD_List();
});
}
//获取打印数据_京东_列表
scope.PrintFacialList_JD_List = function () {
Ajax.post("PrintSFOrderList_JD_List", {}, function (result, code, msg, backRetDate) {
if (result != null && result.length>0) {
scope.Print_JD(result);
} else {
layer.alert("获取打印数据失败", {
skin: 'layui-layer-lan'
, closeBtn: 1
});
}
});
}
//更新已打印状态
scope.ModifyPrintState = function (mailNo) {
if (!mailNo) {
return
}
Ajax.post("ModifyPrintState", { mailNo: mailNo }, function () {
//scope.Search(1);
for (var i = 0; i < scope.List.length; i++) {
if (scope.List[i].SFOrderNo==mailNo) {
scope.List[i].PrintState = 2;
break;
}
}
});
}
*/
},
// 判断点击的点位a是否在polygon之内
IsPointInPoly(aLat, aLon, pointList) {
/*
:param aLat: double 纬度
:param aLon: double 经度
:param pointList: list [{latitude: 22.22, longitude: 113.113}...] 多边形点的顺序需根据顺时针或逆时针,不能乱
*/
let iSum = 0
let iCount = pointList.length
if (iCount < 3) {
return false
}
for (let i = 0; i < iCount; i++) {
//相邻两点作为一条边
let pLat1 = pointList[i].latitude
let pLon1 = pointList[i].longitude
let pLat2 = 0, pLon2 = 0;
if (i == iCount - 1) {
pLat2 = pointList[0].latitude
pLon2 = pointList[0].longitude
} else {
pLat2 = pointList[i + 1].latitude
pLon2 = pointList[i + 1].longitude
}
//判断的点a的纬度在一条边的范围内
if (((aLat >= pLat1) && (aLat < pLat2)) || ((aLat >= pLat2) && (aLat < pLat1))) {
//此边端点纬度不相同
if (Math.abs(pLat1 - pLat2) > 0) {
//得到点a纬度水平线在此边上的交点的经度
let pLon = pLon1 - ((pLon1 - pLon2) * (pLat1 - aLat)) / (pLat1 - pLat2);
//a点在此边右侧计数加1
if (pLon < aLon) {
iSum += 1
}
}
}
}
//在所有边右侧计数为奇数,则为在多边形内。
//判断逻辑为,假设点a的纬度划为水平横线进入多边形体现为,交点代表一进或一出,a点左侧或右侧的交点为偶数则一进一出在外面。
if (iSum % 2 != 0) {
return true
} else {
return false
}
},
//取多边形中心点
GetCenterPointInPoly(lnglatarr) {
// 取面对象 中心点
var total = lnglatarr.length;
var X = 0, Y = 0, Z = 0;
lnglatarr.forEach(function (lnglat) {
var lng = lnglat.longitude * Math.PI / 180;
var lat = lnglat.latitude * Math.PI / 180;
var x, y, z;
x = Math.cos(lat) * Math.cos(lng);
y = Math.cos(lat) * Math.sin(lng);
z = Math.sin(lat);
X += x;
Y += y;
Z += z;
});
X = X / total;
Y = Y / total;
Z = Z / total;
var Lng = Math.atan2(Y, X);
var Hyp = Math.sqrt(X * X + Y * Y);
var Lat = Math.atan2(Z, Hyp);
return { longitude: Lng * 180 / Math.PI, latitude: Lat * 180 / Math.PI };
},
//浮动框架Iframe高度,js按已加载内容适配,需要加载内容页后。
autoIframeWidth: function (viewiframeId) {
if (!viewiframeId) {
return;
}
var iframe = document.getElementById(viewiframeId);
if (iframe) {
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var height = innerDoc.body.scrollHeight;
iframe.style.height = (height + 10) + "px";
}
},
//加载内容页后设置,ng需要渲染后设置 scope.$applyAsync(function () { util.setIframeWidth("iframe_ConfirmOrder") });
setIframeWidth: function (viewiframeId) {
if (window.parent && window.parent.util && window.parent.util.autoIframeWidth) {
window.parent.util.autoIframeWidth(viewiframeId);
}
}
};
// //获取样本类型名称方法对象
// util.TypeNameModel_SampleType = util.GetTypeNameModel({
// sessionStorageKey: "_sampleTypeList20210932",
// apiUrl: "/Product/ProductInfo/GetProductExtractionSampleDTO",
// idKey: "ExtractionSampleTypeId",
// nameKey: "SampleTypeName",
// });
////ng过滤器例:
//FeiYeNGApp.filter("SampleType", function () {
// return function (input) {
// return util.TypeNameModel_SampleType.getName(input);
// }
//});
// //需要放到util中全局调用的参数
// util.addAssign({
// ActivityTypeList: [{ id: "21", name: "盲盒活动" }, { id: "24", name: "传染病盲盒活动" }, { id: "25", name: "上上签活动" }],//活动类型
// BoxTypeList: ["基因检测","传染病原始样本","传染病提取样本"],//
// });
//参数对象动态签名
//var data = {
// publicOpenId: "ZDDE01QCF55SP", configId: "宠知因", userInfo: { openId: "" }
//}
//var newData = util.signData(data, "******");
//微信小程序转ng电脑端,复制代码做部分中间处理
try {
if (!utilwx) {
utilwx = {
//本地缓存
setStorageSync: function (key, value) {
if (typeof value == "object") {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
},
getStorageSync: function (key) {
var value = localStorage.getItem(key);
try {
return JSON.parse(value);
} catch (e) {
}
return value;
},
removeStorageSync: function (key) {
localStorage.removeItem(key);
},
//跳转
navigateTo: function (data) {
document.location.href = data.url;
},
navigateBack: function (data) {
if (!data) {
util.breakpage(-1);
return;
}
util.breakpage((0 - data.delta));
}
};
if (!wx) {
wx = {};
}
Object.assign(wx, utilwx);
}
} catch (e) {
}
//var showClassNameFunc = function () {
// var showName = "el-table_14_column_50";
// var classNames = ["el-table_14_column_46", "el-table_14_column_47", "el-table_14_column_48", "el-table_14_column_49", "el-table_14_column_50"];
// for (var c = 0; c < classNames.length; c++) {
// var s = document.getElementsByClassName(classNames[c])
// for (var i = 0; i < s.length; i++) {
// if (classNames[c] == showName) {
// s[i].style.display = 'block';
// } else {
// s[i].style.display = 'none';
// }
// }
// }
//}
//ng过滤器隐藏没有访问权限的按钮。用例:<button class="btn btn-default btn-xs" fy-auth="会员信息-变更余额" ng-click="OpenTopUpModal()"><i class="fa fa-angle-double-up"></i> 变更余额</button>
if (FeiYeNGApp) {
FeiYeNGApp.directive('fyAuth', function factory() {
return {
controller: function ($scope, $element, $attrs, $transclude) {
//判断权限
if (!ng_customextend_FeiYeAuthCheck($attrs.fyAuth)) {
$element.css('display', 'none');
}
}
};
});
}
var ng_customextend_FeiYeAuthCheck = function (authName) {
//我的权限
var myauthKey = "MyAuth-ng-customextend";
var myauth = localStorage.getItem(myauthKey);
//是否超级管理员
if (myauth == "Admin") {
return true;
}
if (myauth) {
myauth = JSON.parse(myauth);
}
//所有权限,不在列表的不限制
var allauthKey = "AllAuth-ng-customextend";
var allauth = localStorage.getItem(allauthKey);
if (!allauth) {
$.ajax({
url: "/Auth/GetResourceList",
type: "post",
async: false,
success: function (res) {
if (res.RetCode == 0) {
allauth = res.RetData;
} else {
layer.msg("系统有些开小差,请稍后重试。");
}
}
});
//存入本地
localStorage.setItem(allauthKey, JSON.stringify(allauth));
} else {
allauth = JSON.parse(allauth);
}
//,不在列表的不限制
var isChack = false;
for (var i = 0; i < allauth.length; i++) {
if (allauth[i].Description == authName) {
isChack = true;
break;
}
}
if (!isChack) {
return true;
}
if (!myauth) {
var isAdmin = false;
//获取accid的权限,同步
$.ajax({
url: "/Account/GetMyAuthResource",
type: "post",
async: false,
success: function (res) {
if (res.RetCode == 0) {
if (res.RetMsg == "Admin") {
isAdmin = true;
}
myauth = res.RetData;
} else {
layer.msg("系统有些开小差,请稍后重试。");
}
}
});
if (isAdmin) {
localStorage.setItem(myauthKey, "Admin");
return true;
}
if (!myauth) {
console.log("获取权限失败");
return false;
}
//存入本地
localStorage.setItem(myauthKey, JSON.stringify(myauth));
}
//判断
for (var i = 0; i < myauth.length; i++) {
if (myauth[i].Description == authName) {
return true;
}
}
return false;
}
//--wx-fyAuth
var util = {
//保存文本
saveTxt: function (filname, stringData) {
// 保存的文件名称 filname
// // 要保存的字符串
// const stringData = '一段文本.'
// dada 表示要转换的字符串数据,type 表示要转换的数据格式
const blob = new Blob([stringData], {
type: "text/plain;charset=utf-8"
})
// 根据 blob生成 url链接
const objectURL = URL.createObjectURL(blob)
// 创建一个 a 标签Tag
const aTag = document.createElement('a')
// 设置文件的下载地址
aTag.href = objectURL
// 设置保存后的文件名称
aTag.download = filname + ".txt"
// 给 a 标签添加点击事件
aTag.click()
// 释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。
// 当你结束使用某个 URL 对象之后,应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。
URL.revokeObjectURL(objectURL)
},
//返回上一个页面
breakpage: function (p) {
if (p == undefined) {
p = -1;
}
window.location.href = "javascript:history.go(" + p + ")";
},
//时间转换
convertTime: function (val) {
var date;
if (typeof val == 'string' && val.indexOf("Date") <= -1) {
date = new Date(val);
} else {
var re = /-?\d+/;
var m = re.exec(val);
date = new Date(parseInt(m[0]));
}
return date;
},
//时间格式化显示
formatTime: function (val, format) {
if (val == '' || val == null) {
return '';
}
var date;
if (typeof val == 'string' && val.indexOf("Date") <= -1) {
date = new Date(val);
} else if (typeof val == 'object') {
//时间格式
date = val;
}
else {
var re = /-?\d+/;
var m = re.exec(val);
date = new Date(parseInt(m[0]));
}
if (format || format != null) {
var o = {
"M+": date.getMonth() + 1, //month
"d+": date.getDate(), //day
"H+": date.getHours(), //hour
"m+": date.getMinutes(), //minute
"s+": date.getSeconds(), //second
"q+": Math.floor((date.getMonth() + 3) / 3), //quarter
"S": date.getMilliseconds() //millisecond
}
if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
(date.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length == 1 ? o[k] :
("00" + o[k]).substr(("" + o[k]).length));
}
return format;
},
formatTime2: function (time) {
//var time = new Date()
return time.toLocaleDateString().replace(/\//g, "-") + " " + time.toTimeString().substr(0, 8);
},
//表单提交重定向
formSubmitRedrict: function (url, datas, method, target, bc) {
var tempFormName = 'tempForm';
for (var i = 0; document.getElementById(tempFormName) != undefined; i++) {
tempFormName = 'tempForm' + i;
}
var tempForm = document.createElement("form");
tempForm.id = tempFormName;
tempForm.method = method == undefined ? "post" : method;
tempForm.action = url;
tempForm.target = target == undefined ? "" : target;
for (var i = 0; i < datas.length; i++) {
var hideInput = document.createElement("input");
hideInput.type = "hidden";
hideInput.name = datas[i].name;
hideInput.value = datas[i].value;
tempForm.appendChild(hideInput);
}
if (bc == undefined) {
bc = function () { }
}
if (document.all) {
tempForm.attachEvent("onsubmit", bc); //IE
} else {
tempForm.addEventListener("submit", bc); //firefox
}
document.body.appendChild(tempForm);
if (document.all) {
tempForm.fireEvent("onsubmit");
} else {
tempForm.dispatchEvent(new Event("submit"));
}
tempForm.submit();
document.body.removeChild(tempForm);
},
//copy到剪切板
copyText: function (data, cb) {
//data==={text: OrderNo,target:$event.target }
//创建隐藏的标签
var textArea;
try {
textArea = document.createElement("<textarea></textarea>");
} catch (e) {
textArea = document.createElement("textarea");
}
textArea.textContent = data.text;
//不显示出来
textArea.style.width = '1px';
textArea.style.height = '1px';
textArea.style.color = textArea.style.backgroundColor;
//定位,不滚动
if (!data.target) {
data.target = document.body;
}
data.target.appendChild(textArea);
textArea.select(); // 选择对象
var res = false;
try {
res = document.execCommand("copy");//复制
} catch (err) {
data.target.removeChild(textArea);
console.log('该浏览器不支持点击复制到剪贴板');
}
if (cb && typeof cb == "function") {
cb(res)
}
data.target.removeChild(textArea);
},
//生成【类型-名称】获取器,本地session存储,可用于过滤器调用
GetTypeNameModel: function (op) {
var model = {
sessionStorageKey: op.sessionStorageKey,//此类型在本地session中key值
apiUrl: op.apiUrl,//此类型列表获取接口
idKey: op.idKey,//此类型在对象中id标识字段名
nameKey: op.nameKey,//此类型在对象中显示名称字段名
list: [],
getList: function () {
var list = sessionStorage.getItem(model.sessionStorageKey);
if (list) {
model.list = JSON.parse(list);
} else {
ajaxProtogenesis.ajax("post", model.apiUrl, true, {}, function (res) {
model.list = res.RetData;
sessionStorage.setItem(model.sessionStorageKey, JSON.stringify(model.list));
})
}
},
getName: function (id) {//根据类型获取名称的方法
if (model.list == [] || model.length == 0) {
model.getList();
}
var res = '';
if (model.list && model.list.length > 0) {
for (var i = 0; i < model.list.length; i++) {
if (model.list[i][model.idKey] == id) {
res = model.list[i][model.nameKey];
break;
}
}
}
return res;
}
};
model.getList();
return model;
},
//数组转为二维数组形式成表格的行
arrayToRow: function (model, all, rowNo, maxCell, defaultData) {
//model行的数组,all所有数据数组,rowNo当前行下标,maxCell总列数,defaultData数据不存在时用默认值填充
//获取当前这行数据
var row = [];
for (var i = 0; i < maxCell; i++) {
if (all.length > rowNo * maxCell + i) {
row.push(all[rowNo * maxCell + i]);
} else {
row.push(defaultData)
}
}
model.push(row);
rowNo++;//下一行下标
if (all.length > rowNo * maxCell) {
this.arrayToRow(model, all, rowNo, maxCell, defaultData);
}
return model;
},
//数组转为二维数组形式成表格
arrayToTable: function (all, maxRow, maxCell, def) {
//all所有数据数组,单张表maxRow总行数,maxCell总列数,def默认值。
//每张表的数据数组
var tableDatas = [];
util.arrayToRow(tableDatas, all, 0, maxRow * maxCell, def);
//为表获取行
var tables = [];
for (var i = 0; i < tableDatas.length; i++) {
var rows = [];
rows = util.arrayToRow(rows, tableDatas[i], 0, maxCell, def);
tables[i] = rows;
}
return tables;
},
//数组转为二维数组形式成表格_示例
arrayToTableTest: function () {
var all = [];
for (var i = 0; i < 97; i++) {
all.push(i + 1);
}
var t96 = this.arrayToTable(all, 12, 8, {})
console.log(t96);
return t96;
},
//添加属性到util,用合并对象的方式,用来给全局调用的属性,但要注意属性名称冲突
addAssign: function (obj) {
Object.assign(util, obj);
},
//对象格式时间参数和数组
objFormat: function (data) {
if (!data) {
return data;
}
var newData = data;
if (data instanceof Date || (typeof (data) == "string" && data.indexOf("/Date(") > -1)) {
// debugger
newData = this.formatTime(data, "yyyy-MM-dd HH:mm:ss");
} else if (data instanceof Array) {
newData = [];
if (data.length > 0) {
for (let i = 0; i < data.length; i++) {
newData.push(this.objFormat(data[i]));
}
}
} else if (typeof (data) == "object") {
for (var item in data) {
newData[item] = this.objFormat(data[item]);
}
}
return newData;
},
//对象排序,并格式时间参数和数组
objSortAndFormat: function (data) {
var par = [];
for (var i in data) {
par.push(i);
}
par.sort();
var newData = {};
for (let i = 0; i < par.length; i++) {
var item = par[i];
newData[item] = this.objFormat(data[item]);
}
return newData;
},
//给数据对象排序并动态签名,返回值newData有属性sing为签名值。需全局或传入Base64和md5
signData: function (data, signkey, _Base64, _md5) {
if (_Base64) {
Base64 = _Base64;
}
if (_md5) {
md5 = _md5;
}
//var signkey = "*****";
//参数data
if (!data) { data = {}; }
//设置签名时间
data.signtime = new Date().getTime();
//参数排序
var newData = this.objSortAndFormat(data);
//设置签名
var staticParameter = JSON.stringify(newData);
var signOld = staticParameter;
signOld = signOld.replaceAll(" ", "")
signOld = signOld.replaceAll("\\\"", "\"")
//手动处理一下encodeURIComponent没有编码的字符
var ignoreStr = "-_.!~*'()";
for (let ign = 0; ign < ignoreStr.length; ign++) {
signOld = signOld.replaceAll(ignoreStr[ign], "a");
}
//url编码
signOld = encodeURIComponent(signOld).toLowerCase();
//base64编码
signOld = Base64.encode(signOld);
//md5
var sign = md5(signOld + signkey);
newData.sign = sign;
return newData;
// encodeURI和encodeURIComponent区别
// var set1 = ";,/?:@&=+$"; // 保留字符
// var set2 = "-_.!~*'()"; // 不转义字符
// var set3 = "#"; // 数字标志
// var set4 = "ABC abc 123"; // 字母数字字符和空格
// console.log(encodeURI(set1)); // ;,/?:@&=+$
// console.log(encodeURI(set2)); // -_.!~*'()
// console.log(encodeURI(set3)); // #
// console.log(encodeURI(set4)); // ABC%20abc%20123 (the space gets encoded as %20)
// console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24
// console.log(encodeURIComponent(set2)); // -_.!~*'()
// console.log(encodeURIComponent(set3)); // %23
// console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encoded as %20)
},
//【WebSocket】
WebSocketList: [],
GetWebSocket: function (path, protocols, onopen, onmessage, onclose, onerror) {
if (path[path.length - 1] != "/") {
path = path + "/";
}
if (this.WebSocketList[path]) {
return this.WebSocketList[path];
} else {
return this.ReSetWebSocket(path, protocols, onopen, onmessage, onclose, onerror);
}
},
//WebSocket,含例
ReSetWebSocket: function (path, protocols, onopen, onmessage, onclose, onerror) {
if (path[path.length - 1] != "/") {
path = path + "/";
}
//path:要连接的 URL,WebSocket 服务器将响应的 URL。
//protocols(可选) :一个协议字符串或者一个包含协议字符串的数组。
//if (this.WebSocketList[path]) {
// return this.WebSocketList[path];
//}
//创建一个webSocket实例,执行后,客户端就会与服务端连接
var ws;
if (protocols) {
ws = new WebSocket(path, protocols);
} else {
ws = new WebSocket(path);
}
//事件:
var that = this;
//当WebSocket创建成功时,触发onopen事件,在onopen中再发送数据
ws.onopen = function (e) {
console.log("onopen");
console.log(e);
if (onopen) {
onopen(e);
}
};
//当客户端收到服务端发来的消息时,触发onmessage事件
ws.onmessage = function (e) {
console.log("onmessage:");
console.log(e);
if (onmessage) {
onmessage(e);
}
};
//当客户端收到服务端发送的关闭连接请求时,触发onclose事件
ws.onclose = function (e) {
console.log("onclose:");
console.log(e);
that.WebSocketList[e.target.url] = undefined;
if (onclose) {
onclose(e);
}
};
//如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
ws.onerror = function (e) {
console.log("onerror:");
console.log(e);
if (onerror) {
onerror(e);
}
};
this.WebSocketList[path] = ws;
return ws;
/*
例WebSocket
//打印询问窗口_京东
scope.WayBillPrinterTools_JD = function (item, printType) {
var lindex = layer.confirm('确定开始打印京东面单?', {
}, function () {
layer.close(lindex)
scope.PrintFacialList_JD(item, printType, 3);
});
}
//获取打印数据_京东
scope.PrintFacialList_JD = function (item, printType) {
var info = angular.copy(scope.SearchInfo);
if (printType == 0) {
info.SFOrderNo = item.SFOrderNo
}
Ajax.post("PrintSFOrderList_JD", { s: info }, function (result) {
if (result != null) {
console.log(result);
scope.Print_JD([result]);
} else {
layer.alert("获取打印数据失败", {
skin: 'layui-layer-lan'
, closeBtn: 1
});
}
});
}
//执行打印_京东
scope.Print_JD = function (list) {
layer.alert("打印中", {
skin: 'layui-layer-lan'
, closeBtn: 1
});
var url = "ws://127.0.0.1:9113";
//list[0].orderType = "PRE_View";//单据或指令类型 1、PRE_View 打印预览(默认预览第一张面单,所有面单预览传PRE_View:multi) 2、GET_Printers 获取打印机列表 3、PRINT 打印
util.ReSetWebSocket(url, null, function (e, ws) {
for (var i = 0; i < list.length; i++) {
ws.send(JSON.stringify(list[i]));
}
}, function (e, ws) {
var msg = "";
try {
var ed = JSON.parse(e.data);
if (ed.success == "true") {
msg = "打印成功";
scope.ModifyPrintState(ed.key)
} else {
msg = "打印失败";
}
if (ed.key == list[list.length - 1].key) {
layer.closeAll();
layer.alert(msg, {
skin: 'layui-layer-lan'
, closeBtn: 1
});
}
return;
} catch (e) {
msg = "打印失败";
}
layer.closeAll();
layer.alert(msg, {
skin: 'layui-layer-lan'
, closeBtn: 1
});
return;
}, null, function (e, ws) {
console.log(e);
layer.closeAll();
layer.alert("打印错误", {
skin: 'layui-layer-lan'
, closeBtn: 1
});
});
}
//打印全部京东面单
scope.WayBillPrinterTools_JD_List = function () {
var lindex = layer.confirm('确定开始打印全部京东面单?', {
}, function () {
layer.close(lindex)
scope.PrintFacialList_JD_List();
});
}
//获取打印数据_京东_列表
scope.PrintFacialList_JD_List = function () {
Ajax.post("PrintSFOrderList_JD_List", {}, function (result, code, msg, backRetDate) {
if (result != null && result.length>0) {
scope.Print_JD(result);
} else {
layer.alert("获取打印数据失败", {
skin: 'layui-layer-lan'
, closeBtn: 1
});
}
});
}
//更新已打印状态
scope.ModifyPrintState = function (mailNo) {
if (!mailNo) {
return
}
Ajax.post("ModifyPrintState", { mailNo: mailNo }, function () {
//scope.Search(1);
for (var i = 0; i < scope.List.length; i++) {
if (scope.List[i].SFOrderNo==mailNo) {
scope.List[i].PrintState = 2;
break;
}
}
});
}
*/
},
// 判断点击的点位a是否在polygon之内
IsPointInPoly(aLat, aLon, pointList) {
/*
:param aLat: double 纬度
:param aLon: double 经度
:param pointList: list [{latitude: 22.22, longitude: 113.113}...] 多边形点的顺序需根据顺时针或逆时针,不能乱
*/
let iSum = 0
let iCount = pointList.length
if (iCount < 3) {
return false
}
for (let i = 0; i < iCount; i++) {
//相邻两点作为一条边
let pLat1 = pointList[i].latitude
let pLon1 = pointList[i].longitude
let pLat2 = 0, pLon2 = 0;
if (i == iCount - 1) {
pLat2 = pointList[0].latitude
pLon2 = pointList[0].longitude
} else {
pLat2 = pointList[i + 1].latitude
pLon2 = pointList[i + 1].longitude
}
//判断的点a的纬度在一条边的范围内
if (((aLat >= pLat1) && (aLat < pLat2)) || ((aLat >= pLat2) && (aLat < pLat1))) {
//此边端点纬度不相同
if (Math.abs(pLat1 - pLat2) > 0) {
//得到点a纬度水平线在此边上的交点的经度
let pLon = pLon1 - ((pLon1 - pLon2) * (pLat1 - aLat)) / (pLat1 - pLat2);
//a点在此边右侧计数加1
if (pLon < aLon) {
iSum += 1
}
}
}
}
//在所有边右侧计数为奇数,则为在多边形内。
//判断逻辑为,假设点a的纬度划为水平横线进入多边形体现为,交点代表一进或一出,a点左侧或右侧的交点为偶数则一进一出在外面。
if (iSum % 2 != 0) {
return true
} else {
return false
}
},
//取多边形中心点
GetCenterPointInPoly(lnglatarr) {
// 取面对象 中心点
var total = lnglatarr.length;
var X = 0, Y = 0, Z = 0;
lnglatarr.forEach(function (lnglat) {
var lng = lnglat.longitude * Math.PI / 180;
var lat = lnglat.latitude * Math.PI / 180;
var x, y, z;
x = Math.cos(lat) * Math.cos(lng);
y = Math.cos(lat) * Math.sin(lng);
z = Math.sin(lat);
X += x;
Y += y;
Z += z;
});
X = X / total;
Y = Y / total;
Z = Z / total;
var Lng = Math.atan2(Y, X);
var Hyp = Math.sqrt(X * X + Y * Y);
var Lat = Math.atan2(Z, Hyp);
return { longitude: Lng * 180 / Math.PI, latitude: Lat * 180 / Math.PI };
},
//浮动框架Iframe高度,js按已加载内容适配,需要加载内容页后。
autoIframeWidth: function (viewiframeId) {
if (!viewiframeId) {
return;
}
var iframe = document.getElementById(viewiframeId);
if (iframe) {
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var height = innerDoc.body.scrollHeight;
iframe.style.height = (height + 10) + "px";
}
},
//加载内容页后设置,ng需要渲染后设置 scope.$applyAsync(function () { util.setIframeWidth("iframe_ConfirmOrder") });
setIframeWidth: function (viewiframeId) {
if (window.parent && window.parent.util && window.parent.util.autoIframeWidth) {
window.parent.util.autoIframeWidth(viewiframeId);
}
}
};
// //获取样本类型名称方法对象
// util.TypeNameModel_SampleType = util.GetTypeNameModel({
// sessionStorageKey: "_sampleTypeList20210932",
// apiUrl: "/Product/ProductInfo/GetProductExtractionSampleDTO",
// idKey: "ExtractionSampleTypeId",
// nameKey: "SampleTypeName",
// });
////ng过滤器例:
//FeiYeNGApp.filter("SampleType", function () {
// return function (input) {
// return util.TypeNameModel_SampleType.getName(input);
// }
//});
// //需要放到util中全局调用的参数
// util.addAssign({
// ActivityTypeList: [{ id: "21", name: "盲盒活动" }, { id: "24", name: "传染病盲盒活动" }, { id: "25", name: "上上签活动" }],//活动类型
// BoxTypeList: ["基因检测","传染病原始样本","传染病提取样本"],//
// });
//参数对象动态签名
//var data = {
// publicOpenId: "ZDDE01QCF55SP", configId: "宠知因", userInfo: { openId: "" }
//}
//var newData = util.signData(data, "******");
//微信小程序转ng电脑端,复制代码做部分中间处理
try {
if (!utilwx) {
utilwx = {
//本地缓存
setStorageSync: function (key, value) {
if (typeof value == "object") {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
},
getStorageSync: function (key) {
var value = localStorage.getItem(key);
try {
return JSON.parse(value);
} catch (e) {
}
return value;
},
removeStorageSync: function (key) {
localStorage.removeItem(key);
},
//跳转
navigateTo: function (data) {
document.location.href = data.url;
},
navigateBack: function (data) {
if (!data) {
util.breakpage(-1);
return;
}
util.breakpage((0 - data.delta));
}
};
if (!wx) {
wx = {};
}
Object.assign(wx, utilwx);
}
} catch (e) {
}
//var showClassNameFunc = function () {
// var showName = "el-table_14_column_50";
// var classNames = ["el-table_14_column_46", "el-table_14_column_47", "el-table_14_column_48", "el-table_14_column_49", "el-table_14_column_50"];
// for (var c = 0; c < classNames.length; c++) {
// var s = document.getElementsByClassName(classNames[c])
// for (var i = 0; i < s.length; i++) {
// if (classNames[c] == showName) {
// s[i].style.display = 'block';
// } else {
// s[i].style.display = 'none';
// }
// }
// }
//}
//ng过滤器隐藏没有访问权限的按钮。用例:<button class="btn btn-default btn-xs" fy-auth="会员信息-变更余额" ng-click="OpenTopUpModal()"><i class="fa fa-angle-double-up"></i> 变更余额</button>
if (FeiYeNGApp) {
FeiYeNGApp.directive('fyAuth', function factory() {
return {
controller: function ($scope, $element, $attrs, $transclude) {
//判断权限
if (!ng_customextend_FeiYeAuthCheck($attrs.fyAuth)) {
$element.css('display', 'none');
}
}
};
});
}
var ng_customextend_FeiYeAuthCheck = function (authName) {
//我的权限
var myauthKey = "MyAuth-ng-customextend";
var myauth = localStorage.getItem(myauthKey);
//是否超级管理员
if (myauth == "Admin") {
return true;
}
if (myauth) {
myauth = JSON.parse(myauth);
}
//所有权限,不在列表的不限制
var allauthKey = "AllAuth-ng-customextend";
var allauth = localStorage.getItem(allauthKey);
if (!allauth) {
$.ajax({
url: "/Auth/GetResourceList",
type: "post",
async: false,
success: function (res) {
if (res.RetCode == 0) {
allauth = res.RetData;
} else {
layer.msg("系统有些开小差,请稍后重试。");
}
}
});
//存入本地
localStorage.setItem(allauthKey, JSON.stringify(allauth));
} else {
allauth = JSON.parse(allauth);
}
//,不在列表的不限制
var isChack = false;
for (var i = 0; i < allauth.length; i++) {
if (allauth[i].Description == authName) {
isChack = true;
break;
}
}
if (!isChack) {
return true;
}
if (!myauth) {
var isAdmin = false;
//获取accid的权限,同步
$.ajax({
url: "/Account/GetMyAuthResource",
type: "post",
async: false,
success: function (res) {
if (res.RetCode == 0) {
if (res.RetMsg == "Admin") {
isAdmin = true;
}
myauth = res.RetData;
} else {
layer.msg("系统有些开小差,请稍后重试。");
}
}
});
if (isAdmin) {
localStorage.setItem(myauthKey, "Admin");
return true;
}
if (!myauth) {
console.log("获取权限失败");
return false;
}
//存入本地
localStorage.setItem(myauthKey, JSON.stringify(myauth));
}
//判断
for (var i = 0; i < myauth.length; i++) {
if (myauth[i].Description == authName) {
return true;
}
}
return false;
}