cc-jjsp-web/bns/js/public/public.js

506 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 图片路径
let token = localStorage.getItem("tokens");
let us = localStorage.getItem("us");
let isIgwLogin = localStorage.getItem("isIgwLogin");
getVideoConfig(token);
const superUsers = ['jysp','!jysp','zhangyn'];
/* 请求 */
function ajaxRequest2(url, type, data, async, successFn, errorFn, contentType,token) {
$.ajax({
url: url,
type: type,
headers: {
"Authorization": token,
},
data: data,
async: async,
contentType: contentType || "application/x-www-form-urlencoded; charset=utf-8",
success: function (data) {
successFn(data);
},
error: function (error) {
errorFn(error)
}
});
}
/* 请求错误 */
function errorFn(xhr, status, error) {
if (xhr.status === 0) {
// 网络连接失败
console.error("网络连接失败,请检查网络是否正常");
} else {
// 请求出现其他错误
console.error("ajax请求错误" + error);
}
}
// 导出文件-公共方法
function commonExportFile(url,token,fileName){
$('.export').addClass("layui-btn-disabled").attr("disabled", true);
let loadingMsg = layer.msg("数据导出中,请稍候...", { icon: 16, scrollbar: false, time: 0, });
let xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.responseType = "blob"; // 转换流
xhr.setRequestHeader("encryption", "encryption");
xhr.setRequestHeader("Authorization", token);
xhr.onload = function () {
layer.close(loadingMsg);
$('.export').removeClass("layui-btn-disabled").attr("disabled", false);
if (this.status === 200) {
let blob = this.response;
var a = document.createElement("a");
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName; // 文件名
} else {
layer.msg("数据发生异常,请稍后重试", { icon: 16, scrollbar: false, time: 2000 });
}
a.click();
window.URL.revokeObjectURL(url);
};
xhr.send();
}
/* 当前周 */
function getCurrentWeekRange() {
const today = new Date();
const dayOfWeek = today.getDay(); // 0是周日1是周一...6是周六
// 计算周一的日期
const monday = new Date(today);
monday.setDate(today.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1));
// 计算周日的日期
const sunday = new Date(today);
sunday.setDate(today.getDate() + (dayOfWeek === 0 ? 0 : 7 - dayOfWeek));
// 格式化日期为YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
// 拼接开始和结束日期
return `${formatDate(monday)} ~ ${formatDate(sunday)}`;
}
function isFourRisk(riskLevel){
if(riskLevel === '2' || riskLevel === '3'){
return false;
}else if(riskLevel === '4' || riskLevel === '5'){
return true;
}
}
/*系统登出*/
function logout(type) {
let html_type = localStorage.getItem("html_type");
if (type) {
localStorage.removeItem("tokens");
localStorage.removeItem("us");
top.layer.confirm('登录已过期,请点击确定后重新登录!', {
btn: ['确认', '取消'],
cancel: function (index, layero) {
loginExpire(html_type);
}
}, function () {
loginExpire(html_type);
}, function () {
loginExpire(html_type);
});
} else {
let token = localStorage.getItem("tokens");
top.layer.confirm('请您确定注销?', {
btn: ['确认', '取消'],
cancel: function (index, layero) {
}
}, function () {
if (isIgwLogin === '1') {
loginOutAjax(token, null);
} else {
if (html_type === '1') {
loginOutAjax(token, login_url);
} else if (html_type === '2') {
loginOutAjax(token, login_url_new);
} else {
loginOutAjax(token, login_url);
}
}
}, function () {
});
}
}
function getDay(){
let currentDate = new Date();
let year = currentDate.getFullYear(); // 获取当前年份
let month = currentDate.getMonth() + 1; // 获取当前月份注意月份从0开始所以要加1
let nowDay = currentDate.getDate(); // 获取当前日期
return year+"-"+month+"-"+nowDay;
}
function loginOutAjax(token, logoutPath) {
$.ajax({
headers: {
Authorization: token
},
type: "post",
url: dataUrl + 'auth/logout',
data: {},
async: false,
success: function (result) {
localStorage.removeItem("tokens");
localStorage.removeItem("us");
sessionStorage.removeItem("isLockPage");
sessionStorage.removeItem("changeModel");
if (!logoutPath) {
localStorage.removeItem("isIgwLogin");
wx.closeWindow();
} else {
top.location.href = logoutPath;
}
}
});
}
function getVideoConfig(token){
$.ajax({
headers: {
Authorization: token
},
type: "post",
url: dataUrl + 'proteam/pot/device/getVideoConfig',
async: false,
success: function (result) {
var tesData=result.q2httpUrl;
if(typeof(tesData)!='undefined'){
localStorage.setItem("q2http_url",result.q2httpUrl);
localStorage.setItem("q2http_urlN",result.q2httpUrlN);
localStorage.setItem("websocket_url",result.websocketUrl);
localStorage.setItem("websocket_urlN",result.websocketUrlN);
localStorage.setItem("address",result.videoIp);
localStorage.setItem("port",result.videoPort);
localStorage.setItem("user",result.videoUser);
localStorage.setItem("password",result.videoPassword);
localStorage.setItem("epid",result.epid);
localStorage.setItem("bfix",result.bfix);
}else{
localStorage.setItem("q2http_url",'http://220.248.250.31:29605/icvs2/');
localStorage.setItem("q2http_urlN","http://10.138.219.3:29605/icvs2");
localStorage.setItem("websocket_url",'ws://220.248.250.31:29605/wss');
localStorage.setItem("websocket_urlN","ws://10.138.219.3:29605/wss");
localStorage.setItem("address","10.138.219.3");
localStorage.setItem("port","29988");
localStorage.setItem("user","bns4");
localStorage.setItem("password","Bns@2023**");
localStorage.setItem("epid",'system');
localStorage.setItem("bfix",1);
}
},error:function(e){
localStorage.setItem("q2http_url",'http://220.248.250.31:29605/icvs2/');
localStorage.setItem("q2http_urlN","http://10.138.219.3:29605/icvs2");
localStorage.setItem("websocket_url",'ws://220.248.250.31:29605/wss');
localStorage.setItem("websocket_urlN","ws://10.138.219.3:29605/wss");
localStorage.setItem("address","10.138.219.3");
localStorage.setItem("port","29988");
localStorage.setItem("user","bns4");
localStorage.setItem("password","Bns@2023**");
localStorage.setItem("epid",'system');
localStorage.setItem("bfix",1);
}
});
}
// 登录过期
function loginExpire(html_type) {
if (isIgwLogin === '1') {
localStorage.removeItem("isIgwLogin");
wx.closeWindow();
} else {
if (html_type === '1') {
top.location.href = login_url;
} else if (html_type === '2') {
top.location.href = login_url_new;
} else {
top.location.href = login_url;
}
}
}
$(function () {
let html_type = localStorage.getItem("html_type");
if (!token) {
if (html_type === '1') {
top.location.href = login_url;
} else if (html_type === '2') {
top.location.href = login_url_new;
} else {
top.location.href = login_url;
}
}
})
/*
* ajax封装及拦截
*/
var Ajax = function () {
var that = this;
// 创建异步请求对象方法
that.createXHR = function () {
if (window.XMLHttpRequest) { // IE7+、Firefox、Opera、Chrome 和Safari
return new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE6 及以下
var versions = ['MSXML2.XMLHttp', 'Microsoft.XMLHTTP'];
for (var i = 0, len = versions.length; i < len; i++) {
try {
return new ActiveXObject(version[i]);
break;
} catch (e) {
// 跳过
}
}
} else {
throw new Error('浏览器不支持XHR对象');
}
}
// 初始化数据方法
that.init = function (obj) {
// 初始化数据
var objAdapter = {
method: 'get',
data: {},
headers: { encrypt: '' },
success: function () {
},
complete: function () {
},
error: function (s) {
console.log('status:' + s + 'error!')
},
async: true
}
// 通过使用JS随机字符串解决IE浏览器第二次默认获取缓存的问题
that.url = obj.url + '?token=' + token;
that.method = obj.method || objAdapter.method;
that.data = that.params(obj.data) || that.params(objAdapter.data);
that.async = obj.async || objAdapter.async;
that.complete = obj.complete || objAdapter.complete;
that.success = obj.success || objAdapter.success;
that.error = obj.error || objAdapter.error;
let heard = obj.headers || objAdapter.headers;
that.headers = heard.encrypt;
}
// ajax异步调用
that.ajax = function (obj) {
that.method = obj.method || 'get';
if (obj.method === 'post') {
that.post(obj);
} else {
that.get(obj);
}
}
// post方法
that.post = function (obj) {
var xhr = that.createXHR(); // 创建XHR对象
that.init(obj);
that.method = 'post';
if (that.async === true) { // true表示异步false表示同步
// 使用异步调用的时候需要触发readystatechange 事件
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) { // 判断对象的状态是否交互完成
that.callback(obj, this); // 回调
}
};
}
// 在使用XHR对象时必须先调用open()方法,
// 它接受三个参数:请求类型(get、post)、请求的URL和表示是否异步。
xhr.open(that.method, that.url, that.async);
// post方式需要自己设置http的请求头来模仿表单提交。
// 放在open方法之后send方法之前。
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('token', token);
//xhr.setRequestHeader("key","222"); //将token放在header 里面
if (that.headers != '') {
xhr.setRequestHeader("encrypt", that.headers);
}
xhr.send(that.data); // post方式将数据放在send()方法里
if (that.async === false) { // 同步
that.callback(obj, this); // 回调
}
};
// get方法
that.get = function (obj) {
var xhr = that.createXHR(); // 创建XHR对象
that.init(obj);
if (that.async === true) { // true表示异步false表示同步
// 使用异步调用的时候需要触发readystatechange 事件
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) { // 判断对象的状态是否交互完成
that.callback(obj, this); // 回调
}
};
}
// 若是GET请求则将数据加到url后面
that.url += that.url.indexOf('?') == -1 ? '?' + that.data : '&'
+ that.data;
// 在使用XHR对象时必须先调用open()方法,
// 它接受三个参数:请求类型(get、post)、请求的URL和表示是否异步。
xhr.open(that.method, that.url, that.async);
xhr.send(null); // get方式则填null
if (that.headers != '') {
xhr.setRequestHeader("encrypt", that.headers);
}
if (that.async === false) { // 同步
that.callback(obj, this); // 回调
}
}
// 请求成功后,回调方法
that.callback = function (obj, xhr) {
console.log(xhr)
if (xhr.status == 200) { // 判断http的交互是否成功200表示成功
var succobj = JSON.parse(xhr.responseText);
if (succobj.code == '401') {
logout(1)
// top.location.href = login_url;
// localStorage.removeItem("tokens")
// localStorage.removeItem("us")
}
obj.success(succobj); // 回调传递参数
} else if (xhr.status == 401) {
// alert('未授权');
console.log('status:' + s + 'error!')
} else {
console.log('获取数据错误!错误代号:' + xhr.status + ',错误信息:' + xhr.statusText)
// alert('获取数据错误!错误代号:' + xhr.status + ',错误信息:' + xhr.statusText);
}
}
// 数据转换
that.params = function (data) {
var arr = [];
for (var i in data) {
// 特殊字符传参产生的问题可以使用encodeURIComponent()进行编码处理
arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
}
return arr.join('&');
}
return {
post: that.post,
get: that.get,
ajax: that.ajax
}
}
function setData(data) {
let arr = [];
for (let i in data) {
// 特殊字符传参产生的问题可以使用encodeURIComponent()进行编码处理
arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
}
return arr.join('&');
}
//字符串为空转换
function strNull(str) {
if (str == null || str == '') {
return "暂无数据";
} else {
return str;
}
}
/**
* 数字为空转换
* @param {Object} num
*/
function numberNull(num) {
if (num == null || num == '') {
return 0;
} else {
return num;
}
}
//判断字符是否为空的方法
function isEmpty(obj) {
return typeof obj == "undefined" || obj == null || obj == "" || obj == '00';
}
/**
* 将null 转换为 ''
* */
function transformNull(value) {
if (value == null || value == 'null') {
return '';
}
return value;
}
// 判断是否是手机号
function isPhone(value) {
if (value.length === 11) {
return value;
}
return '';
}
// 审计日志容量提示
function capacityTips() {
$.ajax({
headers: {
"encrypt": sm3(JSON.stringify({}))
},
url: dataUrl + 'system/sys/logs/colLogContent' + '?token=' + token,
type: 'get',
data: {},
success: function (obj) {
// debugger
var contentSize = obj.data.maxLogSize.contentSize; //总容量
var logSize = obj.data.usedMaxSize.logSize;//已使用
var useRate = Number(obj.data.useRate) * 100 - 100 + "%"; //使用率
if (obj.code == 200) {
if (Number(obj.data.useRate) * 100 > 90) {
layer.alert("[系统审计日志容量告警] | 总容量:" + contentSize + " MBytes 已使用:" + logSize + " MBytes 使用率超出 " + useRate, {
icon: 0,
color: '#000'
});
}
}
}
});
}
// 设置风险等级颜色
function setRiskLevelColor(value) {
if (value === '2' || value === '2级' || value === '二级') {
return '<span style="color: #DD690B">二级</span>';
} else if (value === '3' || value === '3级' || value === '三级') {
return '<span style="color: #FFE91F">三级</span>';
} else if (value === '4' || value === '4级' || value === '四级') {
return '<span style="color: #2aa998">四级</span>';
} else if (value === '5' || value === '5级' || value === '五级') {
return '<span style="color: #70e180">五级</span>';
} else {
return '';
}
}
// 获取年月日时分秒毫秒
function getTemp(){
const now = new Date();
const year = now.getFullYear(); // 年 (4位数)
const month = now.getMonth() + 1; // 月 (0-11需要+1)
const day = now.getDate(); // 日 (1-31)
const hours = now.getHours(); // 时 (0-23)
const minutes = now.getMinutes(); // 分 (0-59)
const seconds = now.getSeconds(); // 秒 (0-59)
const milliseconds = now.getMilliseconds(); // 毫秒 (0-999)
return `${year}${month}${day}${hours}${minutes}${seconds}${milliseconds}`;
}