safesite/static/safesite/mystatic/js/util.js

574 lines
16 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.

var csrftoken = $.cookie('csrftoken');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
},
complete:function(xhr, status){
if(xhr.status==405){
$.messager.alert('错误','超时请重新登陆!','error',function(){
top.location = "http://" + window.location.host;
});
}
}
});
function photoCompress(file, w, objDiv) {
var ready = new FileReader();
/*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
ready.readAsDataURL(file);
ready.onload = function () {
var re = this.result;
canvasDataURL(re, w, objDiv)
}
}
function canvasDataURL(path, obj, callback) {
var img = new Image();
img.src = path;
img.onload = function () {
var that = this;
// 默认按比例压缩
var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);
if(w <= h ){
if(w>640){
w = 640
h = w/scale
}
}else{
if(h>640){
h=640
w = h*scale
}
}
var quality = 0.7; // 默认图片质量为0.7
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 创建属性节点
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// 图像质量
// if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
// quality = obj.quality;
// }
// quality值越小所绘制出的图像越模糊
var base64 = canvas.toDataURL('image/jpeg', quality);
// 回调函数返回base64的值
callback(base64);
}
}
function convertBase64UrlToBlob(urlData) {
var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
//取消上传
function cancleUploadFile() {
xhr.abort();
}
//验证表单不为空
function myCheck(checkarray) {
for (var i = 0; i < checkarray.length; i++) {
if (checkarray[i] == "") {
return false;
}
}
return true;
}
//获取当前href的参数==当前dialog的地址
function GetQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var href = $('#dd').dialog('options')['href']
var r = href.split('?')[1].match(reg);
if (r != null) return unescape(r[2]); return null;
}
function GetQueryString2(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var href = $('#userdd').dialog('options')['href']
var r = href.split('?')[1].match(reg);
if (r != null) return unescape(r[2]); return null;
}
//放大和缩小图片
function bigger(o) {
var h = $(document).height()
var mh = h * 0.8
$this = $(o);
var img_content = $this.attr("src");
top.$("body").append(
"<div class='bg-img'>"
+ "<div class='tra-img' >"
+ "<img src='" + img_content + "' height='" + mh + "'>"
+ "</div></div>"
);
top.$(".bg-img").animate({
width: "100%",
height: "100%",
bottom: "0",
left: "0",
}, "normal")
$('.bg-img').on("click", function () {
$(this).remove();
})
}
//加载menutree列表
function convertmenu(rows) {
function exists(rows, parentid) {
for (var i = 0; i < rows.length; i++) {
if (rows[i].menuid == parentid) return true;
}
return false;
}
var nodes = [];
// get the top level nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (!exists(rows, row.parentid)) {
nodes.push({
id: row.menuid,
text: row.menuname,
checked: row.checked,
iconCls: row.icon,
attributes: row.url
});
}
}
var toDo = [];
for (var i = 0; i < nodes.length; i++) {
toDo.push(nodes[i]);
}
while (toDo.length) {
var node = toDo.shift(); // the parent node
// get the children nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.parentid == node.id) {
var child = { id: row.menuid, text: row.menuname, attributes: row.url, iconCls: row.icon, checked: row.checked };
if (node.children) {
node.children.push(child);
} else {
node.children = [child];
}
toDo.push(child);
}
}
}
return nodes;
}
//datagrid加载tree列表
function convert(rows, x) {
var x = x || 'open';
function exists(rows, parentId) {
for (var i = 0; i < rows.length; i++) {
if (rows[i].id == parentId) return true;
}
return false;
}
var nodes = [];
// get the top level nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (!exists(rows, row.parentId)) {
nodes.push({
id: row.id,
text: row.name,
state: x,
pic: row.pic
});
}
}
var toDo = [];
for (var i = 0; i < nodes.length; i++) {
toDo.push(nodes[i]);
}
while (toDo.length) {
var node = toDo.shift(); // the parent node
// get the children nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.parentId == node.id) {
var child = { id: row.id, text: row.name, pic: row.pic };
if (node.children) {
node.children.push(child);
} else {
node.children = [child];
}
toDo.push(child);
}
}
}
return nodes;
}
//关闭dialog-dd
function closeForm() {
$("#dd").dialog("close");
}
//关闭dialog-userdd
function closed2Form() {
$('#userdd').dialog("close");
}
//关闭dialog-userdd
function close3Form() {
$('#questiondd').dialog("close");
}
//新建iframe
function createFrame(url) {
var s = '<iframe id="ifr" scrolling="auto" frameborder="0" src="' + url + '" style="width:100%;height:100%;"></iframe>';
return s;
}
//移除上传的文件或图片或列表
function removep(o) {
$(o).closest('li').remove();
}
//判断是否为数字
function isNumber(val) {
var regPos = /^\d+(\.\d+)?$/; //非负浮点数
//var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
if (regPos.test(val)) {
return true;
} else {
return false;
}
}
//判断是否为整数
function isIntNum(val) {
var regPos = /^\d+$/; // 非负整数
//var regNeg = /^\-[1-9][0-9]*$/; // 负整数
if (regPos.test(val)) {
return true;
} else {
return false;
}
}
// function opendialog(o){
// _clickTab = $(o).attr('url');
// _value = $(o).text();
// if (window.screen) {
// var myh = screen.availHeight * 0.7;
// $("#dd").dialog({
// maximizable: true,
// title: _value,
// width: 600,
// height: myh,
// closed: false,
// cache: false,
// href: _clickTab,
// modal: true,
// border:false,
// });
// $("#dd").window('center');
// }
// }
function changehref(o) {
_clickTab = $(o).attr('url');// 找到链接a中的targer的值
_value = $(o).attr('value');
$("#main").attr('value', _value);
$("#main").panel({ href: _clickTab, title: $(o).attr('title') });
// $.ajax({
// type: "get",
// url: _clickTab,
// async: false,
// success: function (data) {
// $("#main").attr('value',_value);
// $("#main").html(data);
// }
// });
}
//获取dialog-dd传值
function getQueryParam(name) {
var obj = $('#dd').dialog('options');
var queryParams = obj["queryParams"];
return queryParams[name];
}
//部分页面操作函数
//新增隐患
function edityh(troubleid) {
if (window.screen) {
var myh = screen.availHeight * 0.7;
var url = 'addtrouble?a=edityh&troubleid=' + troubleid
$("#dd").dialog({
maximizable: true,
title: '新增隐患',
width: 600,
height: myh,
closed: false,
cache: false,
href: url,
modal: true,
border: false,
});
$("#dd").window('center');
}
}
function choseusers(x) {
var x = x || 'participant';
var myh = screen.availHeight * 0.7;
$('#userdd').dialog({
maximizable: true,
title: '选择人员',
width: 900,
height: myh,
closed: false,
cache: false,
href: 'getusersf?a=' + x,
modal: true,
border: false,
});
$('#userdd').window('center');
}
//导出excel
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData)
: JSONData;
var CSV = '';
//Set Report title in first row or line
CSV += ReportTitle + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var fileName = "MyReport_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g, "_");
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + encodeURI(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
//loading效果
function loading(msg) {
var msg = msg || '请稍等。。';
$('body').loading({
loadingWidth: 220,
title: msg,
titleColor: '#fff',
discColor: '#EDEEE9',
discription: '',
direction: 'column',
type: 'origin',
originBg: '#ECCFBB',
originDivWidth: 40,
originDivHeight: 40,
originWidth: 6,
originHeight: 6,
smallLoading: false,
loadingBg: 'rgba(56,43,14,0.8)',
loadingMaskBg: 'rgba(66,66,66,0.2)'
});
}
//js判断为空
function isEmpty(obj) {
// 检验 undefined 和 null
if (!obj && obj !== 0 && obj !== '') { return true; }
if (Array.prototype.isPrototypeOf(obj) && obj.length === 0) { return true; }
if (Object.prototype.isPrototypeOf(obj) && Object.keys(obj).length === 0) { return true; }
return false;
}
function openlayer(title, href, w) {
var w = w || 600;
if (window.screen) {
var myh = screen.availHeight * 0.7;
$.get(href, function (res) {
layer.open({
type: 1,
content: res,
title: title,
area: [w, myh]
});
})
}
}
//打开dd-dialog
function opendg(title, href, w) {
var w = w || 600;
if (window.screen) {
var myh = screen.availHeight * 0.7;
$("#dd").dialog({
title: title,
width: w,
height: myh,
closed: false,
cache: false,
href: href,
modal: true,
border: false,
}).dialog('center');
}
}
function opendg2(title, href) {
if (window.screen) {
var myh = screen.availHeight * 0.8;
var myW = screen.availWidth * 0.7;
$("#questiondd").dialog({
title: title,
width: myW,
height: myh,
closed: false,
cache: false,
href: href,
modal: true,
border: false,
}).dialog('center');
}
}
/**
* 使用indexOf判断元素是否存在于数组中
* @param {Object} arr 数组
* @param {Object} value 元素值
*/
function isInArray(arr, value) {
if (arr.indexOf && typeof (arr.indexOf) == 'function') {
var index = arr.indexOf(value);
if (index >= 0) {
return true;
}
}
return false;
}
function parseParams(data) {
try {
var tempArr = [];
for (var i in data) {
var key = encodeURIComponent(i);
var value = encodeURIComponent(data[i]);
tempArr.push(key + '=' + value);
}
var urlParamsStr = tempArr.join('&');
return urlParamsStr;
} catch (err) {
return '';
}
}
//排序
function jsonSort(jsonObj) {
let arr = [];
for (var key in jsonObj) {
arr.push(key)
}
arr.sort();
let str = '';
for (var i in arr) {
str += arr[i] + "=" + jsonObj[arr[i]] + "&"
}
return str.substr(0, str.length - 1)
}
//map定时显示,每分钟请求一次
function update() {
if ($('#mapshowinput').length) {
source.clear()
$.get('api/mapshow?a=risk', function (res) {
for (let i = 0, len = res.length; i < len; i++) {
setPolygon(res[i])
}
})
$.get('api/mapshow?a=trouble', function (res) {
for (let i = 0, len = res.length; i < len; i++) {
var data = res[i]
data.id = data.yhqy__id
data.num = data.num
data.polygon = data.yhqy__polygon
data.name = data.yhqy__name
data.type = 'yh'
setPoint(data)
}
})
$.get('api/mapshow?a=miss', function (res) {
for (let i = 0, len = res.length; i < len; i++) {
var data = res[i]
data.id = data.missqy__id
data.num = data.num
data.polygon = data.missqy__polygon
data.name = data.missqy__name
data.type = 'ws'
setPoint(data)
}
})
$.get('api/mapshow?a=operation', function (res) {
console.log(res)
for (let i = 0, len = res.length; i < len; i++) {
var data = res[i]
data.id = data.zyqy__id
data.num = data.num
data.polygon = data.zyqy__polygon
data.name = data.zyqy__name
data.type = 'zy'
setPoint(data)
}
})
}
}
var t1 = window.setInterval(update, 1000 * 60)