Authored by 袁晋鹏

新增日志页面嵌套监控的公共方法,后续根据需求合入公共代码

... ... @@ -43,7 +43,8 @@ layui.define(['laytpl', 'layer', 'element', 'util'], function(exports){
//独立页面路由,可随意添加(无需写参数)
,indPage: [
'/user/login', //登入页
'/page/forward' // 听云访问系统页面
'/page/forward', // 听云访问系统页面
'/page/log' //辽宁日志系统访问监控页面
]
//扩展的第三方模块
... ...
layui.define(['sessions', 'form', 'common'],function (exports) {
//登录相关模块,对外暴露的接口
exports('pageLog', function () {
var $ = layui.$
, setter = layui.setter
, form = layui.form
, router = layui.router()
, search = router.search
, common = layui.common
, sessions = layui.sessions;
function getUrlParam(key) {
var href = window.location.href;
var url = href.split("?");
if (url.length <= 1) {
return "";
}
var params = url[1].split("&");
for (var i = 0; i < params.length; i++) {
var param = params[i].split("=");
if (key == param[0]) {
var temp = "" + params[1];
if (temp.search("#") > -1) {
return temp.substring(0, temp.indexOf("#"));
}
return param[1];
}
}
return "";
}
try {
logPage();
}catch (e) {
err()
}
function err(){
layer.msg('没有权限!', {icon: 5, time: 500});
$('#text').text("没有权限!")
layer.closeAll();
}
/**
* 听云系统嵌套咋们系统
* 听云token是通过连接传参,key=Authorization
* url 是请求的页面
* http://xxxxxx:8088/?show=0&Authorization=token&url=alarm/activewarning#/page/forward
* @constructor
*/
function logPage(){
var index = layer.load(2); //加载层
// 日志token
var tokenStr = getUrlParam("Authorization").replace('Bearer%20','').replace('Bearer ','');
// 跳转地址
var url = getUrlParam("url").split('#/')[0];
// 日志地址
var logApi = 'http://192.168.0.44:8080';
$.ajax({
url: '/config/getConfig',
data: {
configName: 'url'
},
async: false,
success(response) {
//debugger
if(response.gateway){
//logApi = response.gateway;
}
}
});
var api = logApi + "/api-user/users/getUserByToken";
$.ajax(api,{
data:{
"access_token": tokenStr
},
headers: {
'authorization': 'Bearer '+tokenStr,
},
//dataType:'json',//服务器返回json格式数据
type:'get',//HTTP请求类型
timeout:30000,//超时时间设置为30秒;
//contentType: 'application/x-www-form-urlencoded',
success:function(rsp){
if(rsp.code == 0){
console.log(JSON.stringify(rsp.data));
var name = rsp.object.username;
var pwd = common.Base64.decode(rsp.object.password);
console.log(pwd);
var field = {};
field.username = name;
field.password = '123456';
field.grant_type = 'password';
field.scope = 'app';
field.client_id = 'webApp';
field.client_secret = 'webApp';
field.deviceId = "";
field.validCode = '';
$.ajax({
url: common.domainName + '/api-auth/oauth/token',
data: field,
type: 'POST',
dataType: 'JSON',
success: function (data) {
if (data.access_token) {
console.log('登录成功')
layui.data(setter.tableName, {
key: setter.request.tokenName
, value: data.access_token
});
sessions.putToken(data);
sessions.putUser(name);
layer.closeAll();
//将access_token和refresh_token写入本地
localStorage.setItem("access_token", data.access_token);
localStorage.setItem("refresh_token", data.refresh_token);
//将登陆url写入本地
localStorage.setItem("loginUrl", location.href);
//登入成功的提示与跳转
window.location = window.location.origin + '/start/index.html?show=0&access_token='+data.access_token+'#/'+url;
} else {
layer.msg('登录失败,请重试', {icon: 5, time: 500});
}
},
error: function (xhr) {
err();
}
});
}
},
error:function(xhr,type,errorThrown){
err();
}
});
}
});
});
... ...
... ... @@ -8,303 +8,310 @@
*/
layui.extend({
setter: 'config' //配置文件
,admin: 'lib/admin' //核心模块
/*,sessions: 'controller/sessions'*/
,view: 'lib/view' //核心模块
}).define(['setter', 'admin'], function(exports){
var setter = layui.setter
,element = layui.element
,admin = layui.admin
,tabsPage = admin.tabsPage
,view = layui.view
,defaultIndex = ''
// 根据 路由渲染页面
,renderPage = function(){
var show = location.search.substr(1).split("&")[0].split("=")[1];
var router = layui.router()
,path = router.path
,pathURL = admin.correctRouter(router.path.join('/'));
//默认读取主页
if(!path.length) path = [''];
if(!tabsPage.index && !renderPage.haveInit && show != '0') path=['']
// 如果访问首页
if(pathURL === '/'){
// path[path.length - 1] = setter.entry;
// 根据不同角色 用户 展示不同首页 开始
if (!defaultIndex) {
$.ajax({
url: sessionStorage.getItem('domainName') + '/api-web/defaultIndex/getDefaultIndexByUser?access_token=' + localStorage.getItem("access_token"),
async: false,
success(response) {
// 获取成功
if(response && response.success && response.object){
if (response.object.path && response.object.path != '/') {
defaultIndex = '/' + response.object.path;
} else {
defaultIndex = setter.entry;
}
setter.entry = '';
}
}
});
}
// path = defaultIndex.substring(1).split('/');
path = defaultIndex.split('/');
// 根据不同角色 用户 展示不同首页 结束
}
if (pathURL === defaultIndex) {
$('li[lay-id="/"]').click();
return;
}
setter: 'config' //配置文件
, admin: 'lib/admin' //核心模块
/*,sessions: 'controller/sessions'*/
, view: 'lib/view' //核心模块
}).define(['setter', 'admin'], function (exports) {
var setter = layui.setter
, element = layui.element
, admin = layui.admin
, tabsPage = admin.tabsPage
, view = layui.view
, defaultIndex = ''
// 根据 路由渲染页面
, renderPage = function () {
var show = location.search.substr(1).split("&")[0].split("=")[1];
var router = layui.router()
, path = router.path
, pathURL = admin.correctRouter(router.path.join('/'));
//默认读取主页
if (!path.length) path = [''];
if (!tabsPage.index && !renderPage.haveInit && show != '0') path = ['']
// 如果访问首页
if (pathURL === '/') {
// path[path.length - 1] = setter.entry;
// 根据不同角色 用户 展示不同首页 开始
if (!defaultIndex) {
$.ajax({
url: sessionStorage.getItem('domainName') + '/api-web/defaultIndex/getDefaultIndexByUser?access_token=' + localStorage.getItem("access_token"),
async: false,
success(response) {
// 获取成功
if (response && response.success && response.object) {
if (response.object.path && response.object.path != '/') {
defaultIndex = '/' + response.object.path;
} else {
defaultIndex = setter.entry;
}
setter.entry = '';
}
}
});
}
// path = defaultIndex.substring(1).split('/');
path = defaultIndex.split('/');
// 根据不同角色 用户 展示不同首页 结束
}
if (pathURL === defaultIndex) {
$('li[lay-id="/"]').click();
return;
}
/*
layui.config({
base: setter.base + 'controller/'
});
*/
//重置状态
var reset = function(type){
//renderPage.haveInit && layer.closeAll();
if(renderPage.haveInit){
$('.layui-layer').each(function(){
var othis = $(this),
index = othis.attr('times');
if(!othis.hasClass('layui-layim')){
layer.close(index);
}
});
}
renderPage.haveInit = true;
/*
layui.config({
base: setter.base + 'controller/'
});
*/
//重置状态
var reset = function (type) {
//renderPage.haveInit && layer.closeAll();
if (renderPage.haveInit) {
$('.layui-layer').each(function () {
var othis = $(this),
index = othis.attr('times');
if (!othis.hasClass('layui-layim')) {
layer.close(index);
}
});
}
renderPage.haveInit = true;
$(APP_BODY).scrollTop(0);
delete tabsPage.type; //重置页面标签的来源类型
};
//如果路由来自于 tab 切换,则不重新请求视图
if (tabsPage.type === 'tab') {
//切换到非主页、或者切换到主页且主页必须有内容。方可阻止请求
if (pathURL !== '/' || (pathURL === '/' && admin.tabsBody().html())) {
admin.tabsBodyChange(tabsPage.index);
return reset(tabsPage.type);
}
}
$(APP_BODY).scrollTop(0);
delete tabsPage.type; //重置页面标签的来源类型
};
//请求视图渲染
view().render(path.join('/')).then(function (res) {
//遍历页签选项卡
var matchTo
, tabs = $('#LAY_app_tabsheader>li');
tabs.each(function (index) {
var li = $(this)
, layid = li.attr('lay-id');
if (layid === pathURL) {
matchTo = true;
tabsPage.index = index;
}
});
var tabName;
//start lsq 页面刷新后名称改变,把aj得存储到localStorage中 2022-03-30
let routerPath = router.path;
if (routerPath.indexOf('ajConfig') != -1 && routerPath.indexOf('view') != -1 && !localStorage.getItem(router.search.ajConfig)) {
localStorage.setItem(router.search.ajConfig, admin.tabsPage.elem.text());
}
//end lsq 2022-03-30
try {
let el = admin.tabsPage.elem;
if (el && el.attr('lay-href-type')) {
if (el.attr('lay-href-type') == 'menu' && !matchTo) {
tabName = admin.tabsPage.elem.text();
}
}
} catch (e) {
}
if (!tabName) {
//lsq 页面刷新后名称改变 2022-03-30
if (routerPath.indexOf('ajConfig') != -1 && routerPath.indexOf('view') != -1) {
tabName = localStorage.getItem(router.search.ajConfig);
} else {
tabName = res.title
//如果路由来自于 tab 切换,则不重新请求视图
if(tabsPage.type === 'tab'){
//切换到非主页、或者切换到主页且主页必须有内容。方可阻止请求
if(pathURL !== '/' || (pathURL === '/' && admin.tabsBody().html())){
admin.tabsBodyChange(tabsPage.index);
return reset(tabsPage.type);
}
}
//请求视图渲染
view().render(path.join('/')).then(function(res){
//遍历页签选项卡
var matchTo
,tabs = $('#LAY_app_tabsheader>li');
tabs.each(function(index){
var li = $(this)
,layid = li.attr('lay-id');
if(layid === pathURL){
matchTo = true;
tabsPage.index = index;
}
});
var tabName;
//start lsq 页面刷新后名称改变,把aj得存储到localStorage中 2022-03-30
let routerPath=router.path;
if(routerPath.indexOf('ajConfig')!=-1 && routerPath.indexOf('view')!=-1 && !localStorage.getItem(router.search.ajConfig)){
localStorage.setItem(router.search.ajConfig,admin.tabsPage.elem.text());
}
}
//如果未在选项卡中匹配到,则追加选项卡
if (setter.pageTabs && pathURL !== '/') {
if (!matchTo) {
$(APP_BODY).append('<div class="layadmin-tabsbody-item layui-show"></div>');
tabsPage.index = tabs.length;
element.tabAdd(FILTER_TAB_TBAS, {
title: '<span>' + (tabName || '新标签页') + '</span>'
, id: pathURL
, attr: router.href
});
}
}
this.container = admin.tabsBody(tabsPage.index);
setter.pageTabs || this.container.scrollTop(0); //如果不开启标签页,则跳转时重置滚动条
//定位当前tabs
element.tabChange(FILTER_TAB_TBAS, pathURL);
// 修改为当前菜单名称
$('* [lay-id="' + pathURL + '"] span').text(tabName)
admin.tabsBodyChange(tabsPage.index);
}).done(function () {
layui.use('common', layui.cache.callback.common);
$win.on('resize', layui.data.resize);
element.render('breadcrumb', 'breadcrumb');
//容器 scroll 事件,剔除吸附层
admin.tabsBody(tabsPage.index).on('scroll', function () {
var othis = $(this)
, elemDate = $('.layui-laydate')
, layerOpen = $('.layui-layer')[0];
//关闭 layDate
if (elemDate[0]) {
elemDate.each(function () {
var thisElemDate = $(this);
thisElemDate.hasClass('layui-laydate-static') || thisElemDate.remove();
});
othis.find('input').blur();
}
//关闭 Tips 层
layerOpen && layer.closeAll('tips');
});
});
reset();
}
//end lsq 2022-03-30
try {
let el = admin.tabsPage.elem;
if(el && el.attr('lay-href-type')){
if(el.attr('lay-href-type') == 'menu' && !matchTo){
tabName= admin.tabsPage.elem.text();
//入口页面
, entryPage = function (fn) {
var router = layui.router()
, container = view(setter.container)
, pathURL = admin.correctRouter(router.path.join('/'))
, isIndPage;
//检查是否属于独立页面
layui.each(setter.indPage, function (index, item) {
if (pathURL === item) {
return isIndPage = true;
}
});
//将模块根路径设置为 controller 目录
layui.config({
base: setter.base + 'controller/'
});
// 跳转到过度页面的时候,判断参数与跳转的过渡页面的参数是否一直,则强制设置hash
// http://localhost:8088/?Authorization=xxx&show=0&url=alarm/activewarning#/page/forward
var href = window.location.href;
console.log(pathURL)
console.log(href)
if (href.indexOf('?Authorization') != -1 && href.indexOf('&show=0&url=') != -1 && pathURL !== '/page/forward'&& pathURL !== '/page/log') {
if(href.indexOf('&flag=log') != -1){
return location.hash = "/page/log";
}else {
return location.hash = "/page/forward";
}
}
} catch (e){
}
if(!tabName){
//lsq 页面刷新后名称改变 2022-03-30
if(routerPath.indexOf('ajConfig')!=-1 && routerPath.indexOf('view')!=-1){
tabName=localStorage.getItem(router.search.ajConfig);
}else{
tabName= res.title
//跳转到告警页面
let params = new URLSearchParams(location.search);
let [bizId] = [params.get('bizId')];
//活动告警页面
if (href.indexOf('&show=3') != -1 && pathURL !== '/alarm/activewarning') {
return location.hash = "/alarm/activewarning/bizId=" + bizId;
}
//历史告警页面
if (href.indexOf('&show=4') != -1 && pathURL !== '/alarm/historywarning') {
return location.hash = "/alarm/historywarning/bizId=" + bizId;
}
}
//如果未在选项卡中匹配到,则追加选项卡
if(setter.pageTabs && pathURL !== '/'){
if(!matchTo){
$(APP_BODY).append('<div class="layadmin-tabsbody-item layui-show"></div>');
tabsPage.index = tabs.length;
element.tabAdd(FILTER_TAB_TBAS, {
title: '<span>'+ (tabName || '新标签页') +'</span>'
,id: pathURL
,attr: router.href
});
}
}
this.container = admin.tabsBody(tabsPage.index);
setter.pageTabs || this.container.scrollTop(0); //如果不开启标签页,则跳转时重置滚动条
//定位当前tabs
element.tabChange(FILTER_TAB_TBAS, pathURL);
// 修改为当前菜单名称
$('* [lay-id="' + pathURL + '"] span').text(tabName)
admin.tabsBodyChange(tabsPage.index);
}).done(function(){
layui.use('common', layui.cache.callback.common);
$win.on('resize', layui.data.resize);
element.render('breadcrumb', 'breadcrumb');
//容器 scroll 事件,剔除吸附层
admin.tabsBody(tabsPage.index).on('scroll', function(){
var othis = $(this)
,elemDate = $('.layui-laydate')
,layerOpen = $('.layui-layer')[0];
//关闭 layDate
if(elemDate[0]){
elemDate.each(function(){
var thisElemDate = $(this);
thisElemDate.hasClass('layui-laydate-static') || thisElemDate.remove();
});
othis.find('input').blur();
}
//独立页面
if (isIndPage || pathURL === '/user/login' || pathURL === '/page/forward' || pathURL == "/page/log") { //此处单独判断登入页,是为了兼容旧版(即未在 sessions.js 配置 indPage 的情况)
let path = router.path.join('/')
if (pathURL.indexOf('/user/login') != -1) {
var loginIndex = 'default';
// let loginSkin = sessionStorage.getItem("loginSkin");
//lsq 从cookie中获取登录皮肤 2022-03-31
let loginSkin = admin.getCookie("loginSkin");
if (loginSkin && ["default", 'skin1', 'skin2'].indexOf(loginSkin) != -1) {
loginIndex = loginSkin;
}
//关闭 Tips 层
layerOpen && layer.closeAll('tips');
});
});
path = path + '-' + loginIndex;
}
container.render(path).done(function () {
admin.pageType = 'alone';
});
} else { //后台框架页面
reset();
}
//入口页面
,entryPage = function(fn){
var router = layui.router()
,container = view(setter.container)
,pathURL = admin.correctRouter(router.path.join('/'))
,isIndPage;
//检查是否属于独立页面
layui.each(setter.indPage, function(index, item){
if(pathURL === item){
return isIndPage = true;
}
});
//强制拦截未登入
if (setter.interceptor) {
var local = layui.data(setter.tableName);
if (!local[setter.request.tokenName]) {
return location.hash = '/user/login/redirect=' + encodeURIComponent(pathURL); //跳转到登入页
}
}
//将模块根路径设置为 controller 目录
layui.config({
base: setter.base + 'controller/'
});
//渲染后台结构
if (admin.pageType === 'console') { //后台主体页
renderPage();
} else { //初始控制台结构
var renderUrl = 'layout';
// if(localStorage.getItem("lgn") != 'admin'){
// renderUrl = 'layout-nx';
// }
let userLayout = sessionStorage.getItem("userLayout");
if (userLayout && ['layout', 'layout-nx'].indexOf(userLayout) != -1) {
renderUrl = userLayout;
}
container.render(renderUrl).done(function () {
renderPage();
layui.element.render();
if (admin.screen() < 2) {
admin.sideFlexible();
}
admin.pageType = 'console';
});
}
// 跳转到过度页面的时候,判断参数与跳转的过渡页面的参数是否一直,则强制设置hash
// http://localhost:8088/?Authorization=xxx&show=0&url=alarm/activewarning#/page/forward
var href = window.location.href;
if(href.indexOf('?Authorization') != -1 && href.indexOf('&show=0&url=') != -1 && pathURL !== '/page/forward'){
return location.hash = "/page/forward";
}
//跳转到告警页面
let params=new URLSearchParams(location.search);
let [bizId]=[params.get('bizId')];
//活动告警页面
if( href.indexOf('&show=3') != -1 && pathURL !== '/alarm/activewarning'){
return location.hash = "/alarm/activewarning/bizId="+bizId;
}
//历史告警页面
if( href.indexOf('&show=4') != -1 && pathURL !== '/alarm/historywarning'){
return location.hash = "/alarm/historywarning/bizId="+bizId;
}
//独立页面
if(isIndPage || pathURL === '/user/login'|| pathURL === '/page/forward'){ //此处单独判断登入页,是为了兼容旧版(即未在 sessions.js 配置 indPage 的情况)
let path = router.path.join('/')
if(pathURL.indexOf('/user/login') != -1){
var loginIndex = 'default';
// let loginSkin = sessionStorage.getItem("loginSkin");
//lsq 从cookie中获取登录皮肤 2022-03-31
let loginSkin = admin.getCookie("loginSkin");
if(loginSkin && ["default",'skin1','skin2'].indexOf(loginSkin) != -1){
loginIndex = loginSkin;
}
}
, APP_BODY = '#LAY_app_body', FILTER_TAB_TBAS = 'layadmin-layout-tabs'
, $ = layui.$, $win = $(window);
//初始主体结构
layui.link(setter.base + 'style/admin.css?v=' + (admin.v + '-1'));
layui.link(setter.base + 'style/css/main.css?v=' + (admin.v + '-1'), entryPage, 'layuiAdmin');
//监听Hash改变
window.onhashchange = function () {
entryPage();
//执行 {setter.MOD_NAME}.hash 下的事件
layui.event.call(this, setter.MOD_NAME, 'hash({*})', layui.router());
};
path = path + '-' + loginIndex;
//扩展 lib 目录下的其它模块
layui.each(setter.extend, function (index, item) {
var mods = {};
if (item === 'mxClient') {
mods[item] = '{/}' + setter.base + 'lib/mxgraph/' + item;
}
container.render(path).done(function(){
admin.pageType = 'alone';
});
} else { //后台框架页面
//强制拦截未登入
if(setter.interceptor){
var local = layui.data(setter.tableName);
if(!local[setter.request.tokenName]){
return location.hash = '/user/login/redirect='+ encodeURIComponent(pathURL); //跳转到登入页
else if (item === 'soulTable' || item === 'tableFilter' || item === 'tableChild'
|| item === 'tableMerge' || item === 'excel') {
mods[item] = '{/}' + setter.base + 'lib/soultable/' + item;
} else if (item === 'tableEdit' || item === 'tableTree') {
mods[item] = '{/}' + setter.base + 'lib/tabletree/' + item;
} else {
mods[item] = '{/}' + setter.base + 'lib/extend/' + item;
}
}
//渲染后台结构
if(admin.pageType === 'console') { //后台主体页
renderPage();
} else { //初始控制台结构
var renderUrl = 'layout';
// if(localStorage.getItem("lgn") != 'admin'){
// renderUrl = 'layout-nx';
// }
let userLayout = sessionStorage.getItem("userLayout");
if(userLayout && ['layout','layout-nx'].indexOf(userLayout) != -1){
renderUrl = userLayout;
}
container.render(renderUrl).done(function(){
renderPage();
layui.element.render();
if(admin.screen() < 2){
admin.sideFlexible();
}
admin.pageType = 'console';
});
}
}
}
,APP_BODY = '#LAY_app_body', FILTER_TAB_TBAS = 'layadmin-layout-tabs'
,$ = layui.$, $win = $(window);
//初始主体结构
layui.link(setter.base + 'style/admin.css?v='+ (admin.v + '-1'));
layui.link(setter.base + 'style/css/main.css?v='+ (admin.v + '-1'), entryPage, 'layuiAdmin');
//监听Hash改变
window.onhashchange = function(){
entryPage();
//执行 {setter.MOD_NAME}.hash 下的事件
layui.event.call(this, setter.MOD_NAME, 'hash({*})', layui.router());
};
//扩展 lib 目录下的其它模块
layui.each(setter.extend, function(index, item){
var mods = {};
if(item === 'mxClient'){
mods[item] = '{/}' + setter.base + 'lib/mxgraph/' + item;
}
else if(item === 'soulTable' || item === 'tableFilter' || item === 'tableChild'
|| item === 'tableMerge' || item === 'excel'){
mods[item] = '{/}' + setter.base + 'lib/soultable/' + item;
}else if(item === 'tableEdit' || item === 'tableTree'){
mods[item] = '{/}' + setter.base + 'lib/tabletree/' + item;
} else{
mods[item] = '{/}' + setter.base + 'lib/extend/' + item;
}
layui.extend(mods);
});
layui.extend(mods);
});
// 创建canvas
window.createCanvas = function (target) {
... ... @@ -324,34 +331,34 @@ layui.extend({
// 设置canvas尺寸
window.resizeEventFn = function () {
$(onresizeEvents).map(function (index, event) {
var item = event.val;
if (typeof item === 'function') {
item();
} else if (item[0].nodeName.toUpperCase() === 'CANVAS') {
var canvas = item;
var target = canvas.parent();
canvas[0].width= target.width() + 30;
canvas[0].height = target.height() + 20;
}
});
$(onresizeEvents).map(function (index, event) {
var item = event.val;
if (typeof item === 'function') {
item();
} else if (item[0].nodeName.toUpperCase() === 'CANVAS') {
var canvas = item;
var target = canvas.parent();
canvas[0].width = target.width() + 30;
canvas[0].height = target.height() + 20;
}
});
};
// 页面尺寸变化的事件栈
window.onresizeEvents = [];
window.setResizeEvents = function(key, val) {
var index = -1;
window.setResizeEvents = function (key, val) {
var index = -1;
$(onresizeEvents).map(function (i, event) {
if (event.key === key) {
index = i;
}
});
$(onresizeEvents).map(function (i, event) {
if (event.key === key) {
index = i;
}
});
if (index !== -1) {
onresizeEvents.splice(index, 1);
}
onresizeEvents.push({ key: key, val: val });
if (index !== -1) {
onresizeEvents.splice(index, 1);
}
onresizeEvents.push({key: key, val: val});
};
window.addEventListener('resize', resizeEventFn);
... ... @@ -361,7 +368,7 @@ layui.extend({
*/
window.generateUUID = function () {
var d = new Date().getTime()
return'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
... ... @@ -370,285 +377,285 @@ layui.extend({
//系统登录后建立长连接监控实时告警信息
layui.use(['jquery','msgTips','sockjs','stomp', 'laytpl'], function () {
var msgTips = layui.msgTips
,webSockState = false
,sock = undefined
,stompClient = null
,laytpl = layui.laytpl
,access_token = localStorage.getItem("access_token")
,domainName = sessionStorage.getItem('domainName');
var connectFlg = false;
var tryIndex = 1;
var voiceList = [{
voice_:'咳咳',
type_:'ERROR',
},{
voice_:'微信提醒',
type_:'WARNING',
},{
voice_:'滑稽',
type_:'SUCCESS',
}];
//setTimeout(alarmWebSocket,10000);
function alarmWebSocket() {
if (!webSockState) {
webSockState = true;
console.log("websock正在连接。。。。。。")
sock = new SockJS(domainName+'/api-web/sock-js?access_token=' + access_token);
stompClient = Stomp.over(sock);
stompClient.connect({},function (frame) {
console.log("websock连接成功。。。。。。")
connectFlg = true;
tryIndex = 1;
//通过stompClient.subscribe订阅/topic/getResponse 目标(destination)发送的消息
// stompClient.send("/home/alarmPolling", {}, JSON.stringify({ 'accessToken': access_token }),function (e) {
// console.log(e)
// });
//通过stompClient.subscribe订阅/topic/getResponse 目标(destination)发送的消息
stompClient.subscribe('/alarmQuery/', function(respnose){
var alarmArr = JSON.parse(respnose.body);
var mp3Name = sessionStorage.getItem('mp3');
var audio = audioPlayer(`../src/style/mp3/${mp3Name}.mp3`)
$.each(alarmArr,function (i,v) {
if (v.alarmContent) {
(function(i) {
var alarmLevel = 'error';
var alarmType = 'alarm';
if (v.clearType && v.alarmLevel === '1') {
alarmLevel = 'info';
} else if (v.clearType && v.alarmLevel === '2') {
alarmLevel = 'warning';
} else if (v.clearType && v.alarmLevel === '3') {
alarmLevel = 'error';
} else if (v.clearType === 0) {
alarmLevel = 'success';
alarmType = 'alarmHis'
}
let isNotify = alarmByUser(v.alarmId,alarmType === 'alarm' ? 'b_alarm' : 'b_alarm_his');
if (isNotify) {
setTimeout(function() {
audio.playclip();
new msgTips({
dom:".right-bottom-tips",
title: "告警消息",
message:`<p style="line-height: 40px">${v.alarmContent}</p>`,
duration:10000,
space:10,
firstSpace:8,
limit:8,
margin:15,
direction:'right bottom',
timingFun:'ease',
width:'300px',
toastType:alarmLevel,
type:'click',
action: function () {
if (alarmType === 'alarm') {
location.hash = "/alarm/activewarning/alarmNo=" + v.alarmNo;
} else {
location.hash = "/alarm/historywarning/alarmNo=" + v.alarmNo;
}
}
})
}, (i + 1) * 1250);
}
})(i)
}
})
});
// 弹框展示错误消息
let showTips = function (content,title="提示", toastType = 'error', hash, delay = 1000, queryResult) {
if (queryResult) {
content = laytpl(content).render(queryResult);
}
//判断是否为故障诊断的三种类型
if(toastType=='faultinfo'||toastType=='faultover'||toastType=='faultprogress'){
var imgUrl="";
if(toastType=='faultinfo'){
imgUrl="/src/style/img/fault.png";
}
layui.use(['jquery', 'msgTips', 'sockjs', 'stomp', 'laytpl'], function () {
var msgTips = layui.msgTips
, webSockState = false
, sock = undefined
, stompClient = null
, laytpl = layui.laytpl
, access_token = localStorage.getItem("access_token")
, domainName = sessionStorage.getItem('domainName');
var connectFlg = false;
var tryIndex = 1;
var voiceList = [{
voice_: '咳咳',
type_: 'ERROR',
}, {
voice_: '微信提醒',
type_: 'WARNING',
}, {
voice_: '滑稽',
type_: 'SUCCESS',
}];
//setTimeout(alarmWebSocket,10000);
function alarmWebSocket() {
if (!webSockState) {
webSockState = true;
console.log("websock正在连接。。。。。。")
sock = new SockJS(domainName + '/api-web/sock-js?access_token=' + access_token);
stompClient = Stomp.over(sock);
stompClient.connect({}, function (frame) {
console.log("websock连接成功。。。。。。")
connectFlg = true;
tryIndex = 1;
//通过stompClient.subscribe订阅/topic/getResponse 目标(destination)发送的消息
// stompClient.send("/home/alarmPolling", {}, JSON.stringify({ 'accessToken': access_token }),function (e) {
// console.log(e)
// });
//通过stompClient.subscribe订阅/topic/getResponse 目标(destination)发送的消息
stompClient.subscribe('/alarmQuery/', function (respnose) {
var alarmArr = JSON.parse(respnose.body);
var mp3Name = sessionStorage.getItem('mp3');
var audio = audioPlayer(`../src/style/mp3/${mp3Name}.mp3`)
$.each(alarmArr, function (i, v) {
if (v.alarmContent) {
(function (i) {
var alarmLevel = 'error';
var alarmType = 'alarm';
if (v.clearType && v.alarmLevel === '1') {
alarmLevel = 'info';
} else if (v.clearType && v.alarmLevel === '2') {
alarmLevel = 'warning';
} else if (v.clearType && v.alarmLevel === '3') {
alarmLevel = 'error';
} else if (v.clearType === 0) {
alarmLevel = 'success';
alarmType = 'alarmHis'
}
let isNotify = alarmByUser(v.alarmId, alarmType === 'alarm' ? 'b_alarm' : 'b_alarm_his');
if (isNotify) {
setTimeout(function () {
audio.playclip();
new msgTips({
dom: ".right-bottom-tips",
title: "告警消息",
message: `<p style="line-height: 40px">${v.alarmContent}</p>`,
duration: 10000,
space: 10,
firstSpace: 8,
limit: 8,
margin: 15,
direction: 'right bottom',
timingFun: 'ease',
width: '300px',
toastType: alarmLevel,
type: 'click',
action: function () {
if (alarmType === 'alarm') {
location.hash = "/alarm/activewarning/alarmNo=" + v.alarmNo;
} else {
location.hash = "/alarm/historywarning/alarmNo=" + v.alarmNo;
}
}
})
}, (i + 1) * 1250);
}
})(i)
}
})
});
// 弹框展示错误消息
let showTips = function (content, title = "提示", toastType = 'error', hash, delay = 1000, queryResult) {
if (queryResult) {
content = laytpl(content).render(queryResult);
}
if(toastType=='faultover'){
imgUrl="/src/style/img/faultprogress.png";
}
//判断是否为故障诊断的三种类型
if (toastType == 'faultinfo' || toastType == 'faultover' || toastType == 'faultprogress') {
var imgUrl = "";
if (toastType == 'faultinfo') {
imgUrl = "/src/style/img/fault.png";
}
if(toastType=='faultprogress'){
imgUrl="/src/style/img/faultover.png";
}
setTimeout(function () {
new msgTips({
dom: ".right-bottom-tips",
title: title,
message: `<p style="line-height: 18px;background: url(${imgUrl}) no-repeat;background-size: 100%;height: 160px;background-position-x: right;padding: 145px 22px 0; "><span style=" overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical;" title="${content}">${content}</span><span class="title closeFault" style="position: absolute;top: 66px;left: 214px;">X</span><span style="position: absolute;left: 87px;top: 124px; font-weight: bold;float: right;">${title}</span></p>`,
duration: 10000,
space: 10,
firstSpace: 8,
limit: 8,
margin: 15,
direction: 'right top',
timingFun: 'ease',
width: '300px',
toastType: toastType,
type: 'click',
action: function () {
//if (hash) {
// location.hash = hash;
location.hash = "/faultDiagnosis/list/faultNo="+content.split(",")[0].split(":")[1];
//}
if (toastType == 'faultover') {
imgUrl = "/src/style/img/faultprogress.png";
}
})
}, delay);
}else{
setTimeout(function () {
new msgTips({
dom: ".right-bottom-tips",
title: title,
message: `<p style="line-height: 40px">${content}</p>`,
duration: 10000,
space: 10,
firstSpace: 8,
limit: 8,
margin: 15,
direction: 'right bottom',
timingFun: 'ease',
width: '300px',
toastType: toastType,
type: 'click',
action: function () {
if (hash) {
if(hash.toLowerCase().indexOf("http://")!=-1 && hash.toLowerCase().indexOf("https://")!=-1){
location.hash = hash;
}else{
window.location.href=hash;
if (toastType == 'faultprogress') {
imgUrl = "/src/style/img/faultover.png";
}
setTimeout(function () {
new msgTips({
dom: ".right-bottom-tips",
title: title,
message: `<p style="line-height: 18px;background: url(${imgUrl}) no-repeat;background-size: 100%;height: 160px;background-position-x: right;padding: 145px 22px 0; "><span style=" overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical;" title="${content}">${content}</span><span class="title closeFault" style="position: absolute;top: 66px;left: 214px;">X</span><span style="position: absolute;left: 87px;top: 124px; font-weight: bold;float: right;">${title}</span></p>`,
duration: 10000,
space: 10,
firstSpace: 8,
limit: 8,
margin: 15,
direction: 'right top',
timingFun: 'ease',
width: '300px',
toastType: toastType,
type: 'click',
action: function () {
//if (hash) {
// location.hash = hash;
location.hash = "/faultDiagnosis/list/faultNo=" + content.split(",")[0].split(":")[1];
//}
}
})
}, delay);
} else {
setTimeout(function () {
new msgTips({
dom: ".right-bottom-tips",
title: title,
message: `<p style="line-height: 40px">${content}</p>`,
duration: 10000,
space: 10,
firstSpace: 8,
limit: 8,
margin: 15,
direction: 'right bottom',
timingFun: 'ease',
width: '300px',
toastType: toastType,
type: 'click',
action: function () {
if (hash) {
if (hash.toLowerCase().indexOf("http://") != -1 && hash.toLowerCase().indexOf("https://") != -1) {
location.hash = hash;
} else {
window.location.href = hash;
}
}
}
})
}, delay);
}
}
// 订阅实时消息
stompClient.subscribe('/realTime/', function (respnose) {
console.log('实时信息: ' + respnose);
var data = respnose.body;
if (data) {
var obj = JSON.parse(data);
showTips(obj.content, obj.title, obj.msgType.toLowerCase(), obj.href, 1000, obj.queryResult);
}
});
// 订阅用户消息
stompClient.subscribe("/user/realTime/notifications/", function (respnose) {
console.log('专属信息: ' + respnose);
var data = respnose.body;
if (data) {
var obj = JSON.parse(data);
if (obj.msgType == 'LOGOUT') {
layer.msg("登录凭证失效,请重新登录验证!", {
icon: 7, time: 3000
}, function () {
view.exit();
});
} else {
showTips(obj.content, obj.title, obj.msgType.toLowerCase(), obj.href, 1000, obj.queryResult);
if (typeof(obj.msgType) != "undefined") {
var str = '滑稽';
voiceList.forEach(item => {
if (item.type_ == obj.msgType) {
str = item.voice_;
}
})
var url = '../src/style/mp3/' + str + '.mp3';
var audio = audioPlayer(url);
audio.playclip();
}
}
})
}, delay);
}
}
});
}, function (e) {
console.log(`(${tryIndex})链接失败,重试中....`)
connectFlg = false;
if (location.hash.indexOf('#/user/login') == -1) {
// 调用测试接口,出现过期则会跳转到登录页面
admin.req({
url: domainName + "/api-web/common/test"
, type: "get"
, async: false
, done: function (data) {
tryFunc();
}
});
} else {
tryFunc();
}
})
}
}
// 订阅实时消息
stompClient.subscribe('/realTime/', function (respnose) {
console.log('实时信息: '+ respnose);
var data = respnose.body;
if (data) {
var obj = JSON.parse(data);
showTips(obj.content, obj.title, obj.msgType.toLowerCase(), obj.href, 1000, obj.queryResult);
//告警是否属于当前用户
function alarmByUser(alarmId, tableName) {
let isNotify = false;
$.ajax({
url: sessionStorage.getItem('domainName') + '/api-web/bAlarm/hasAlarmByUserName?access_token=' + localStorage.getItem("access_token") + '&alarmId=' + alarmId + '&tableName=' + tableName,
async: false,
success(res) {
if (res && res.success) {
isNotify = true;
}
}
});
return isNotify;
}
// 订阅用户消息
stompClient.subscribe("/user/realTime/notifications/", function (respnose) {
console.log('专属信息: '+ respnose);
var data = respnose.body;
if (data) {
var obj = JSON.parse(data);
if (obj.msgType == 'LOGOUT') {
layer.msg("登录凭证失效,请重新登录验证!", {
icon: 7, time: 3000
}, function () {
view.exit();
});
} else {
showTips(obj.content,obj.title, obj.msgType.toLowerCase(), obj.href, 1000, obj.queryResult);
if(typeof(obj.msgType)!="undefined"){
var str = '滑稽';
voiceList.forEach(item =>{
if(item.type_== obj.msgType){
str = item.voice_;
}
})
var url = '../src/style/mp3/' + str + '.mp3';
var audio = audioPlayer(url);
audio.playclip();
}
}
//音频播放
function audioPlayer(url) {
var audio = document.createElement('audio')
if (audio.canPlayType) {
var element = document.createElement('source')
element.setAttribute('src', url)
element.setAttribute('type', 'audio/mpeg')
audio.appendChild(element)
audio.load()
audio.playclip = function () {
audio.pause()
audio.currentTime = 0
audio.play()
}
});
},function(e){
console.log(`(${tryIndex})链接失败,重试中....`)
connectFlg = false;
if(location.hash.indexOf('#/user/login') == -1){
// 调用测试接口,出现过期则会跳转到登录页面
admin.req({
url: domainName + "/api-web/common/test"
, type: "get"
, async: false
, done: function (data) {
tryFunc();
}
});
} else {
tryFunc();
return audio
}
})
}
}
//告警是否属于当前用户
function alarmByUser(alarmId,tableName) {
let isNotify = false;
$.ajax({
url: sessionStorage.getItem('domainName') + '/api-web/bAlarm/hasAlarmByUserName?access_token=' + localStorage.getItem("access_token") + '&alarmId=' + alarmId + '&tableName=' + tableName,
async: false,
success(res) {
if (res && res.success) {
isNotify = true;
}
var tryFunc = function () {
setTimeout(function () {
if (!connectFlg) {
tryIndex++;
access_token = localStorage.getItem("access_token")
webSockState = false;
alarmWebSocket();
//setTimeout(tryFunc(),3000);
}
}
});
return isNotify;
}
//音频播放
function audioPlayer(url){
var audio = document.createElement('audio')
if (audio.canPlayType){
var element = document.createElement('source')
element.setAttribute('src', url)
element.setAttribute('type', 'audio/mpeg')
audio.appendChild(element)
audio.load()
audio.playclip=function(){
audio.pause()
audio.currentTime=0
audio.play()
}
return audio
}
}
var tryFunc = function () {
setTimeout(function () {
if(!connectFlg){
tryIndex++;
access_token = localStorage.getItem("access_token")
webSockState = false;
alarmWebSocket();
//setTimeout(tryFunc(),3000);
}
},tryIndex*3000);
}
tryFunc();
})
//对外输出
exports('index', {
render: renderPage
});
}, tryIndex * 3000);
}
tryFunc();
})
//对外输出
exports('index', {
render: renderPage
});
//解决刷新后中间出现404页面问题
var show = location.search.substr(1).split("&")[0].split("=")[1];
if(show == '1') window.history.pushState({} ,'' ,'#');
if(show != '0') location.hash = "/";
if (show == '1') window.history.pushState({}, '', '#');
if (show != '0') location.hash = "/";
});
... ...
... ... @@ -132,7 +132,7 @@ layui.define(['laytpl', 'layer'], function(exports){
typeof success === 'function' && success(res);
}
,error: function(e, code){
if(window.location.hash.indexOf('page/forward') != -1){
if(window.location.hash.indexOf('page/forward') != -1 || window.location.hash.indexOf('page/log') != -1){
return;
}
if(e.status == '401'){
... ...
<!-- -->
<article class="page-container template">
<div class="page-panel">
<div class="main" id="text">
加载中.....
</div>
</div>
<textarea id="line_param" style="display: none;">{{d}}</textarea>
</article>
<script>
layui.use('pageLog', function (fn) {
var $ = layui.$;
var parm = $("#line_param").val();
if(parm.indexOf('{{d') != -1){
fn();
}else{
fn(JSON.parse(parm));
}
});
</script>
... ...