var VarValue = []; var VarSnapshotTime = {}; var alarmColorData = {}; var intervalTimers = []; var PAGEROOTDIR = decodeURIComponent(location.href); var $window = $window || $(window); var _exchangeCount = 0; (function () { var index = PAGEROOTDIR.lastIndexOf('/Html5/') === -1 ? (PAGEROOTDIR.lastIndexOf('/html5/') === -1 ? -1 : PAGEROOTDIR.lastIndexOf('/html5/')) : PAGEROOTDIR.lastIndexOf('/Html5/'); if (index !== -1) { PAGEROOTDIR = PAGEROOTDIR.substr(0, index + 7); } else { PAGEROOTDIR = (location.origin || location.protocol + '//' + location.host) + '/'; } })(); function Cmd(CmdStr) { var a; try { eval('a = ' + CmdStr + ";"); } catch (err) { a = 0; alert("表达式错误: " + CmdStr + "\n请在组态程序中修正后重新发布!"); } return a; } ht.Chart = function (option, w, h) { var self = this, view = self._view = document.createElement('div'); view.style.width = w + 'px'; view.style.height = h + 'px'; view.style.position = 'absolute'; view.style.setProperty('box-sizing', 'border-box', null); self._option = option; self._chart = echarts.init(self.getView()); if (option) self._chart.setOption(option); self._FIRST = true; }; function getDateString(d) { var curr_date = d.getDate(); var curr_month = d.getMonth() + 1; var curr_year = d.getFullYear(); var hr = d.getHours(); var min = d.getMinutes(); var sec = d.getSeconds(); var dateStr = curr_year + "/" + curr_month + "/" + curr_date + " " + hr + ":" + min + ":" + sec; return dateStr; } function GetDital(value, number) { var returnValue = value; if (returnValue == null || returnValue == undefined) return 0; var valuearr = returnValue.toString().split('.'); var decimalCount = valuearr.length < 2 ? 0 : valuearr[1].length; if (typeof (returnValue) === 'number') { if (isNaN(returnValue)) { return 0; } else { if (number < 0) { return decimalCount <= 7 ? returnValue : returnValue.toFixed(7); } else { if (number > 7) { number = 7; } return decimalCount <= number ? returnValue : returnValue.toFixed(number); } } } if (typeof (returnValue) === 'string') { if (isNaN(returnValue)) { return 0; } else { returnValue = parseFloat(returnValue); if (number < 0) { return decimalCount <= 7 ? returnValue : returnValue.toFixed(7); } else { if (number > 7) { number = 7; } return decimalCount <= number ? returnValue : returnValue.toFixed(number); } } } if (returnValue === true) { return 1; } return 0; } ht.Default.def('ht.Chart', Object, { ms_v: 1, ms_fire: 1, ms_ac: ['chart', 'option', 'isFirst', 'view'], validateImpl: function () { var self = this, chart = self._chart; chart.resize(); if (self._FIRST) { self._FIRST = false; //chart.restore(); } }, setSize: function (w, h) { var view = this._view; view.style.width = w + 'px'; view.style.height = h + 'px'; } }); ht.DataModel.prototype.isAutoAdjustIndex = function () { return false; }; function submitAddSingle(varName, value, time, quality, desc, groupid) { if (!isdowncontrol()) { return; } // var device; // if (varName.indexOf('.') != -1) { // device = varName.split('.')[0]; // } // desc = desc + ":" + value; if (isAuthEnable == "True" && groupid >= 0) { getAuthInfoByGroupId(groupid, function (data) { if (data) { sendRequest(varName, value, time, quality, desc, groupid); } }); } else if (isAuthEnable == "True" && groupid == -1) { sendRequest(varName, value, time, quality, desc, groupid); } else { sendRequest(varName, value, time, quality, desc, groupid, false); } } function sendRequest(varName, value, time, quality, desc, groupid, isAddOpera) { isAddOpera = isAddOpera === undefined ? true : isAddOpera; var data = { TagName: varName, Time: time, Value: value, Quality: quality }; if (data.Time === "") { //var d = new Date(); //var curr_date = d.getDate(); //var curr_month = d.getMonth() + 1; //var curr_year = d.getFullYear(); //var hr = d.getHours(); //var min = d.getMinutes(); //var sec = d.getSeconds(); //var dateStr = curr_year + "/" + curr_month + "/" + curr_date + " " + hr + ":" + min + ":" + sec; //data.Time = dateStr; data.Time = "1900-01-01 00:00:00"; } var jsonStr = JSON.stringify(data); $.ajax({ url: "http://" + webServiceIP + ":" + webServicePort + "/api/Snapshot/?isSingleData=True", type: "POST", data: jsonStr, contentType: "application/json; charset=utf-8", success: function (data) { if (data || data == "True") { if (isAddOpera) { //将当前记录写入到操作记录中 addOpera(varName, varName.split('.')[0], value, groupid, desc, quality, function (data) { }); } } if ((typeof data == 'string') && data.constructor == String) //数据库版本2.x { if (data !== "True") GD.createErrorDialog(300, 160, data); } else ////数据库版本3.x { var errorList = data.ErrorList; if (errorList != null && errorList.length > 0) { GD.createErrorDialog(300, 160, errorList[0].ErrorMsg); } } }, error: function (data) { if (data.responseText === "") GD.createErrorDialog(300, 160, '网络链接错误'); else GD.createErrorDialog(300, 160, data.responseText); }, complete: function (XHR, TS) { XHR = null; }, }); } function getHisTrendData(option, cmdStr, dictagdesc, callBack, areaStyleShow) { var paras = cmdStr.split('&'); str = "http://" + webServiceIP + ":" + webServicePort + "/api/HistoryInterval?tagName="; //+ cmdStr; str = str + encodeURIComponent(paras[0]) + "&" + paras[1] + "&" + paras[2] + "&" + paras[3] + "&" + paras[4]; //str = encodeURI(str); $.ajax({ url: str, type: 'GET', dataType: 'json', cache: false, success: function (data) { if (data === null) { var k = 0; var test_data = {}; for (tag in dictagdesc) { test_data[tag] = []; option.series[k] = {}; option.series[k].name = dictagdesc[tag]; option.series[k].type = 'line'; option.series[k].showSymbol = false; option.series[k].sampling = 'average'; option.series[k].symbol = "none"; option.series[k].animation = false; if (option.yAxis && option.yAxis.length > 1) { dictagdesc[tag + 'index'] && (option.series[k].yAxisIndex = dictagdesc[tag + 'index']); } if (areaStyleShow) { option.series[k].areaStyle = { normal: {} }; } //option.legend.data.push(tag); // option.legend.data.push(dictagdesc[tag]); for (var i = 0; i < 1; i++) { var currentTime = Date.now(); test_data[tag][i] = { name: currentTime, value: [ currentTime, null ] }; } option.series[k].data = test_data[tag]; k++; } } //return; else { var hisValues = data; //判断快照是否为空 var k = 0; var date = []; var test_data = {}; if (hisValues != null) { for (tag in hisValues) { test_data[tag] = []; option.series[k] = {}; //option.series[k].name = tag; option.series[k].name = dictagdesc[tag]; option.series[k].type = 'line'; option.series[k].showSymbol = false; option.series[k].sampling = 'average'; option.series[k].symbol = "none"; option.series[k].animation = false; if (option.yAxis && option.yAxis.length > 1) { dictagdesc[tag + 'index'] && (option.series[k].yAxisIndex = dictagdesc[tag + 'index']); } if (areaStyleShow) { option.series[k].areaStyle = { normal: {} }; } //option.legend.data.push(tag); option.legend && option.lengend[0] && option.lengend[0].data.push(dictagdesc[tag]); for (var i = 0; i < hisValues[tag].length; i++) { var time = hisValues[tag][i].Time; var timepts = time.split(' '); var timepars = timepts[0].split('/'); if (timepars[1] < 10) { time = time.replace("/" + timepars[1] + "/", "/0" + timepars[1] + "/"); } if (timepars[2] < 10) { time = time.replace("/" + timepars[2] + " ", "/0" + timepars[2] + " "); } //2017-04-01 15:34:28.000 time = time.replace("/", "-"); time = time.replace("/", "-"); time = time.replace(" ", "T"); var tagTime = moment(time).format(); var tagValue = parseFloat(hisValues[tag][i].Value).toFixed(2); test_data[tag][i] = { name: tagTime, value: [ tagTime, tagValue ] }; } option.series[k].data = test_data[tag]; k++; } } } callBack(option); return test_data; }, complete: function (XHR, TS) { XHR = null; }, error: function (data) { var k = 0; var test_data = {}; for (tag in dictagdesc) { test_data[tag] = []; option.series[k] = {}; option.series[k].name = dictagdesc[tag]; option.series[k].type = 'line'; option.series[k].showSymbol = false; option.series[k].sampling = 'average'; option.series[k].symbol = "none"; option.series[k].animation = false; //option.legend.data.push(tag); // option.legend.data.push(dictagdesc[tag]); for (var i = 0; i < 1; i++) { var currentTime = new Date(); test_data[tag][i] = { name: currentTime, value: [ currentTime, null ] }; } option.series[k].data = test_data[tag]; k++; } callBack(option); return test_data; } }); } function getHisScatterData(chart, option, cmdStr, dictagdesc, pointArr, typeArr, digit, ymin, ymax, deviceType) { var paras = cmdStr.split('&'); str = "http://" + webServiceIP + ":" + webServicePort + "/api/HistoryInterval?tagName="; paras[0] = encodeURIComponent(paras[0]); str = str + paras.join('&'); // str = str + encodeURIComponent(paras[0]) + "&" + paras[1] + "&" + paras[2] + "&" + paras[3] + "&" + paras[4] + "&" + paras[5]; var type = paras[paras.length-1].split('=')[1]; // 标准数据 var _standerdData = { 'UP1500-70': [ [3, 3.12], [3.5, 21.87], [4, 46.99], [4.5, 76.41], [5, 111.05], [5.5, 153.66], [6, 206.11], [6.5, 268.91], [7, 342.59], [7.5, 427.81], [8, 525.33], [8.5, 638.43], [9, 755.38], [9.5, 880.36], [10, 1007.83], [10.5, 1136.81], [11, 1259.98], [11.5, 1375.27], [12, 1477.2], [12.5, 1500], [13, 1500], [13.5, 1500], [14, 1500], [14.5, 1500], [15, 1500], [15.5, 1500], [16, 1500], [16.5, 1500], [17, 1500], [17.5, 1500], [18, 1500], [18.5, 1500], [19, 1500], [19.5, 1500], [20, 1500], [20.5, 1500], [21, 1500], [21.5, 1500], [22, 1500], [22.5, 1500], [23, 1500], [23.5, 1500], [24, 1500], [24.5, 1500], [25, 1500] ], 'UP1500-77': [ [3, 9.61], [3.5, 32.66], [4, 62.2], [4.5, 98.55], [5, 141.4], [5.5, 194.47], [6, 260.73], [6.5, 338.4], [7, 428.8], [7.5, 535.47], [8, 658.98], [8.5, 794.86], [9, 941.5], [9.5, 1097.29], [10, 1253.7], [10.5, 1405.08], [11, 1500], [11.5, 1500], [12, 1500], [12.5, 1500], [13, 1500], [13.5, 1500], [14, 1500], [14.5, 1500], [15, 1500], [15.5, 1500], [16, 1500], [16.5, 1500], [17, 1500], [17.5, 1500], [18, 1500], [18.5, 1500], [19, 1500], [19.5, 1500], [20, 1500], [20.5, 1500], [21, 1500], [21.5, 1500], [22, 1500], [22.5, 1500], [23, 1500], [23.5, 1500], [24, 1500], [24.5, 1500], [25, 1500] ], 'UP1500-82': [ [3, 13.45], [3.5, 40.61], [4, 75.35], [4.5, 117.73], [5, 167.55], [5.5, 231.09], [6, 305.77], [6.5, 398.23], [7, 506.15], [7.5, 631.44], [8, 775.54], [8.5, 933.21], [9, 1101.82], [9.5, 1274.34], [10, 1451.66], [10.5, 1500], [11, 1500], [11.5, 1500], [12, 1500], [12.5, 1500], [13, 1500], [13.5, 1500], [14, 1500], [14.5, 1500], [15, 1500], [15.5, 1500], [16, 1500], [16.5, 1500], [17, 1500], [17.5, 1500], [18, 1500], [18.5, 1500], [19, 1500], [19.5, 1500], [20, 1500], [20.5, 1500], [21, 1500], [21.5, 1500], [22, 1500], [22.5, 1500], [23, 1500], [23.5, 1500], [24, 1500], [24.5, 1500], [25, 1500] ], 'UP1500-86': [ [3, 15.25], [3.5, 45.21], [4, 82.31], [4.5, 130.21], [5, 185.47], [5.5, 255.27], [6, 337.94], [6.5, 439.39], [7, 558.02], [7.5, 695.24], [8, 852.84], [8.5, 1022.71], [9, 1200.46], [9.5, 1384.56], [10, 1500], [10.5, 1500], [11, 1500], [11.5, 1500], [12, 1500], [12.5, 1500], [13, 1500], [13.5, 1500], [14, 1500], [14.5, 1500], [15, 1500], [15.5, 1500], [16, 1500], [16.5, 1500], [17, 1500], [17.5, 1500], [18, 1500], [18.5, 1500], [19, 1500], [19.5, 1500], [20, 1500], [20.5, 1500], [21, 1500], [21.5, 1500], [22, 1500], [22.5, 1500], [23, 1500], [23.5, 1500], [24, 1500], [24.5, 1500], [25, 1500] ], 'UP1500-97': [ [3, 35.99], [3.5, 70.24], [4, 118.45], [4.5, 189.36], [5, 271.06], [5.5, 373.13], [6, 485.66], [6.5, 618.62], [7, 773.69], [7.5, 938.57], [8, 1134], [8.5, 1325], [9, 1500], [9.5, 1500], [10, 1500], [10.5, 1500], [11, 1500], [11.5, 1500], [12, 1500], [12.5, 1500], [13, 1500], [13.5, 1500], [14, 1500], [14.5, 1500], [15, 1500], [15.5, 1500], [16, 1500], [16.5, 1500], [17, 1500], [17.5, 1500], [18, 1500], [18.5, 1500], [19, 1500], [19.5, 1500], [20, 1500], [20.5, 1500], [21, 1500], [21.5, 1500], [22, 1500], [22.5, 1500], [23, 1500], [23.5, 1500], [24, 1500], [24.5, 1500], [25, 1500] ], 'UP2000-87': [ [3, 39.13], [3.5, 69.2], [4, 115.97], [4.5, 169.56], [5, 237.72], [5.5, 322.17], [6, 424.52], [6.5, 543.48], [7, 681.04], [7.5, 839.33], [8, 1017.78], [8.5, 1218.45], [9, 1434.4], [9.5, 1664.34], [10, 1901.03], [10.5, 2000], [11, 2000], [11.5, 2000], [12, 2000], [12.5, 2000], [13, 2000], [13.5, 2000], [14, 2000], [14.5, 2000], [15, 2000], [15.5, 2000], [16, 2000], [16.5, 2000], [17, 2000], [17.5, 2000], [18, 2000], [18.5, 2000], [19, 2000], [19.5, 2000], [20, 2000], [20.5, 2000], [21, 2000], [21.5, 2000], [22, 2000], [22.5, 2000], [23, 2000], [23.5, 2000], [24, 2000], [24.5, 2000], [25, 2000] ], 'UP2000-96': [ [3, 21.9], [3.5, 50.77], [4, 93.07], [4.5, 152.92], [5, 224.24], [5.5, 313.3], [6, 421.61], [6.5, 549.9], [7, 700.66], [7.5, 873.8], [8, 1072.22], [8.5, 1296.27], [9, 1535.54], [9.5, 1776.91], [10, 2000], [10.5, 2000], [11, 2000], [11.5, 2000], [12, 2000], [12.5, 2000], [13, 2000], [13.5, 2000], [14, 2000], [14.5, 2000], [15, 2000], [15.5, 2000], [16, 2000], [16.5, 2000], [17, 2000], [17.5, 2000], [18, 2000], [18.5, 2000], [19, 2000], [19.5, 2000], [20, 2000], [20.5, 2000], [21, 2000], [21.5, 2000], [22, 2000], [22.5, 2000], [23, 2000], [23.5, 2000], [24, 2000], [24.5, 2000], [25, 2000] ], 'UP2000-103': [ [3, 25.84], [3.5, 59.25], [4, 110.59], [4.5, 176.41], [5, 256.57], [5.5, 358.22], [6, 480.73], [6.5, 625.08], [7, 793.84], [7.5, 989.98], [8, 1212.58], [8.5, 1458.06], [9, 1705.04], [9.5, 1961.65], [10, 2000], [10.5, 2000], [11, 2000], [11.5, 2000], [12, 2000], [12.5, 2000], [13, 2000], [13.5, 2000], [14, 2000], [14.5, 2000], [15, 2000], [15.5, 2000], [16, 2000], [16.5, 2000], [17, 2000], [17.5, 2000], [18, 2000], [18.5, 2000], [19, 2000], [19.5, 2000], [20, 2000], [20.5, 2000], [21, 2000], [21.5, 2000], [22, 2000], [22.5, 2000], [23, 2000], [23.5, 2000], [24, 2000], [24.5, 2000], [25, 2000] ], 'UP2000-105': [ [3, 31.9], [3.5, 67.13], [4, 123.02], [4.5, 190.82], [5, 276.72], [5.5, 384.98], [6, 515.37], [6.5, 669.48], [7, 850.74], [7.5, 1058.97], [8, 1289.89], [8.5, 1536.96], [9, 1787.9], [9.5, 2000], [10, 2000], [10.5, 2000], [11, 2000], [11.5, 2000], [12, 2000], [12.5, 2000], [13, 2000], [13.5, 2000], [14, 2000], [14.5, 2000], [15, 2000], [15.5, 2000], [16, 2000], [16.5, 2000], [17, 2000], [17.5, 2000], [18, 2000], [18.5, 2000], [19, 2000], [19.5, 2000], [20, 2000], [20.5, 2000], [21, 2000], [21.5, 2000], [22, 2000], [22.5, 2000], [23, 2000], [23.5, 2000], [24, 2000], [24.5, 2000], [25, 2000] ], 'UP2000-111': [ [3, 41.47], [3.5, 81.58], [4, 140.27], [4.5, 214.03], [5, 309.1], [5.5, 428.09], [6, 571.28], [6.5, 739.81], [7, 937.01], [7.5, 1165.17], [8, 1408.25], [8.5, 1645.76], [9, 1882.77], [9.5, 2000], [10, 2000], [10.5, 2000], [11, 2000], [11.5, 2000], [12, 2000], [12.5, 2000], [13, 2000], [13.5, 2000], [14, 2000], [14.5, 2000], [15, 2000], [15.5, 2000], [16, 2000], [16.5, 2000], [17, 2000], [17.5, 2000], [18, 2000], [18.5, 2000], [19, 2000], [19.5, 2000], [20, 2000], [20.5, 2000], [21, 2000], [21.5, 2000], [22, 2000], [22.5, 2000], [23, 2000], [23.5, 2000], [24, 2000], [24.5, 2000], [25, 2000] ], 'UP2000-115': [ [3, 20.62], [3.5, 86.52], [4, 159.21], [4.5, 245.16], [5, 346.11], [5.5, 463.73], [6, 619.51], [6.5, 786.99], [7, 985.67], [7.5, 1229], [8, 1510], [8.5, 1862], [9, 2000], [9.5, 2000], [10, 2000], [10.5, 2000], [11, 2000], [11.5, 2000], [12, 2000], [12.5, 2000], [13, 2000], [13.5, 2000], [14, 2000], [14.5, 2000], [15, 2000], [15.5, 2000], [16, 2000], [16.5, 2000], [17, 2000], [17.5, 2000], [18, 2000], [18.5, 2000], [19, 2000], [19.5, 2000], [20, 2000], [20.5, 2000], [21, 2000], [21.5, 2000], [22, 2000], [22.5, 2000], [23, 2000], [23.5, 2000], [24, 2000], [24.5, 2000], [25, 2000] ], 'UP2000-121': [ [3, 32.728], [3.5, 102.384], [4, 186.87], [4.5, 290.566], [5, 415.484], [5.5, 550.916], [6, 711.338], [6.5, 893.586], [7, 1068.206], [7.5, 1249.736], [8, 1462.6], [8.5, 1731.828], [9, 1911.05], [9.5, 2000], [10, 2000], [10.5, 2000], [11, 2000], [11.5, 2000], [12, 2000], [12.5, 2000], [13, 2000], [13.5, 2000], [14, 2000], [14.5, 2000], [15, 2000], [15.5, 2000], [16, 2000], [16.5, 2000], [17, 2000], [17.5, 2000], [18, 2000], [18.5, 2000], [19, 2000], [19.5, 2000], [20, 2000] ], 'UP2100-121': [ [3, 19.99], [3.5, 52.61], [4, 139.07], [4.5, 245.15], [5, 367.82], [5.5, 515.07], [6, 691.68], [6.5, 900.32], [7, 1144], [7.5, 1424], [8, 1745], [8.5, 2100], [9, 2100], [9.5, 2100], [10, 2100], [10.5, 2100], [11, 2100], [11.5, 2100], [12, 2100], [12.5, 2100], [13, 2100], [13.5, 2100], [14, 2100], [14.5, 2100], [15, 2100], [15.5, 2100], [16, 2100], [16.5, 2100], [17, 2100], [17.5, 2100], [18, 2100], [18.5, 2100], [19, 2100], [19.5, 2100], [20, 2100], [20.5, 2100], [21, 2100], [21.5, 2100], [22, 2100], [22.5, 2100], [23, 2100], [23.5, 2100], [24, 2100], [24.5, 2100], [25, 2100] ], 'UP3000-108': [ [3, 112.73], [3.5, 192.94], [4, 286.15], [4.5, 397.02], [5, 528.27], [5.5, 683], [6, 865.06], [6.5, 1073.3], [7, 1310.46], [7.5, 1573.22], [8, 1855.97], [8.5, 2147.44], [9, 2437.76], [9.5, 2735.59], [10, 2997.89], [10.5, 2997.89], [11, 2997.89], [11.5, 2997.89], [12, 2997.89], [12.5, 2997.89], [13, 2997.89], [13.5, 2997.89], [14, 2997.89], [14.5, 2997.89], [15, 2997.89], [15.5, 2997.89], [16, 2997.89], [16.5, 2997.89], [17, 2997.89], [17.5, 2997.89], [18, 2997.89], [18.5, 2997.89], [19, 2997.89], [19.5, 2997.89], [20, 2997.89], [20.5, 2997.89], [21, 2997.89], [21.5, 2997.89], [22, 2997.89], [22.5, 2997.89], [23, 2997.89], [23.5, 2997.89], [24, 2997.89], [24.5, 2997.89], [25, 2997.89] ], 'UP2000-129': [ [3, 39.46343239], [3.5, 125.6432788], [4, 219.4714609], [4.5, 329.5487529], [5, 457.4521127], [5.5, 607.3637197], [6, 787.3911529], [6.5, 997.9767531], [7, 1233.68128], [7.5, 1463.094124], [8, 1689.342548], [8.5, 1895.26058], [9, 2000], [9.5, 2000], [10, 2000], [10.5, 2000], [11, 2000], [11.5, 2000], [12, 2000], [12.5, 2000], [13, 2000], [13.5, 2000], [14, 2000], [14.5, 2000], [15, 2000], [15.5, 2000], [16, 2000], [16.5, 2000], [17, 2000], [17.5, 2000], [18, 2000], [18.5, 2000], [19, 2000], [19.5, 2000], [20, 2000] ], 'UP3000-146': [ [3, 77.147], [3.5, 185.877636], [4, 293.9956907], [4.5, 428.4692409], [5, 594.4768116], [5.5, 785.2404187], [6, 1007.887492], [6.5, 1258.856802], [7, 1525.997884], [7.5, 1808.595136], [8, 2096.963], [8.5, 2438.74932], [9, 2667.47688], [9.5, 2828], [10, 2929.1], [10.5, 2985], [11, 3000], [11.5, 3000], [12, 3000], [12.5, 3000], [13, 3000], [13.5, 3000], [14, 3000], [14.5, 3000], [15, 3000], [15.5, 3000], [16, 3000], [16.5, 3000], [17, 3000], [17.5, 3000], [18, 3000], [18.5, 3000], [19, 3000], [19.5, 3000], [20, 3000] ], 'UPT300-16': [ [0.7,0], [0.8,3.21709], [0.9,12.2613], [1,23.3403], [1.1,36.9281], [1.2,53.3618], [1.3,72.7074], [1.4,95.261], [1.5,121.28], [1.6,151.017], [1.7,184.635], [1.8,220.949], [1.9,259.063], [2,298.231], [3,300.023], [4,300.023] ], 'ErrorData': [ [0.7,0], [0.8,2.944], [0.9,11.232], [1,20.324], [1.1,34.9281], [1.2,50.3618], [1.3,68.7074], [1.4,86.261], [1.5,113.28], [1.6,131.017], [1.7,166.635], [1.8,203.949], [1.9,235.063], [2,268.231], [2.1,268.231], [2.2,268.231], [2.3,268.231], [2.4,268.231], [2.5,268.231], [2.6,268.231], [2.7,268.231], [2.8,268.231], [2.9,268.231], [3,272.023], [3.1,272.023], [3.2,272.023], [3.3,272.023], [3.4,272.023], [3.5,272.023], [3.6,272.023], [3.7,272.023], [3.8,272.023], [3.9,272.023], [4,272.023] ] } var standerdData = chart._standerdData; function percent5Filter(speedValue, powerValue, dtype, low, high) { var standerdValue, bigValue, smallValue, percent; low = low || 0.95; high = high || 1.05; if (!standerdData[dtype] && !standerdData[dtype].data) { return true; } for (var i = 1, len = standerdData[dtype].data.length; i < len; i++) { if (standerdData[dtype].data[i - 1][0] <= speedValue && standerdData[dtype].data[i][0] >= speedValue) { bigValue = standerdData[dtype].data[i]; smallValue = standerdData[dtype].data[i - 1]; break; } } if (!bigValue || !smallValue) { return false; } standerdValue = (bigValue[1] - smallValue[1]) / (bigValue[0] - smallValue[0]) * (speedValue - smallValue[0]) + smallValue[1]; percent = Math.abs(powerValue / standerdValue); return (percent <= high && percent >= low); } function getStanderdData(standerdDataKey) { if (!standerdData[standerdDataKey]) return ; return { "name": standerdDataKey, "data": standerdData[standerdDataKey].data, "type": "line", "symbolSize": 5, "smooth": true, "itemStyle": { "normal": { "color": standerdData[standerdDataKey].color } }, "lineStyle": { "normal": { "width": 2, "type": "solid" } }, "zlevel": 0, "z": 2, "coordinateSystem": "cartesian2d", "legendHoverLink": true, "hoverAnimation": true, "clipOverflow": true, "label": { "normal": { "position": "top" }, "emphasis": { "position": "top" } }, "step": false, "smoothMonotone": null, "symbol": "emptyCircle", "symbolRotate": null, "showSymbol": true, "showAllSymbol": false, "connectNulls": false, "sampling": "none", "animationEasing": "linear", "progressive": 0, "hoverLayerThreshold": null } } $.ajax({ url: str, type: 'GET', dataType: 'json', cache: false, success: function (data) { if (data === null) { } else { var hisValues = data; var k = 0, isChaoLiuNeng; (function () { var key; for (var k in standerdData) { if (standerdData.hasOwnProperty(k)) { key = k; break; } } if (key.substr(0,3) === 'UPT') { isChaoLiuNeng = key; } })(); // 潮流能假数据 if (isChaoLiuNeng && (typeArr[0] === '1' || typeArr[0] === '0')) { (function () { var key ; for (var k in standerdData) { if (standerdData.hasOwnProperty(k)) { key = k; break ; } } var errData = key ? (standerdData[key].data || _standerdData.ErrorData) : _standerdData.ErrorData, t; var xData = [], yData = []; hisValues = {}; t = moment(Date.now()).format('YYYY-MM-DD HH-mm-ss'); for (var i = 0, len = errData.length; i < len; i++) { xData.push({ "Ms": 0, "Value": errData[i][0], "Time": t }); yData.push({ "Ms": 0, "Value": errData[i][1] - Math.random()*50, "Time": t }); } for (var i = 0, len = pointArr.length; i < len; i++) { hisValues[pointArr[i][0]+'trendX'] = xData; hisValues[pointArr[i][1]+'trendY'] = yData; } })(); } for (var key in hisValues) { for (var i = 1, len = hisValues[key].length; i < len; i++) { if (hisValues[key][i - 1].Value !== 'NaN' && hisValues[key][i].Value === 'NaN') { hisValues[key][i].Value = hisValues[key][i - 1].Value; } } } for (var i = 0; i < pointArr.length; i++) { var seriesdata = []; seriesdata.length = 0; var type = typeArr[i]; if (type == "0" && i == 0) { var data1 = hisValues[pointArr[i][0]]; var data2 = hisValues[pointArr[i][1]]; if (typeof data1 == "undefined" || typeof data2 == "undifined") continue; if (data1.length == data2.length) { for (var j = 0; j < data1.length; j++) { var partaldata = []; partaldata.length = 0; partaldata.push(GetDital(parseFloat(data1[j].Value), digit)); partaldata.push(GetDital(parseFloat(data2[j].Value), digit)); seriesdata.push(partaldata); } } } else if (type == "1") { var data1 = hisValues[pointArr[i][0] + "trendX"]; var data2 = hisValues[pointArr[i][1] + "trendY"]; option.series[k].type = "line"; option.series[i].symbol = 'emptyCircle'; if (typeof data1 != "undefined" && data2 != "undefined") { if (data1.length == data2.length) { for (var j = 0; j < data1.length; j++) { var partaldata = []; partaldata.length = 0; if (data1[j].Value != "NaN" && data2[j].Value != "NaN" && data1[j].Value >= ymin && data1[j].Value <= ymax && data2[j].Value <= ymax && data2[j].Value >= ymin) { partaldata.push(GetDital(parseFloat(data1[j].Value), digit)); partaldata.push(GetDital(parseFloat(data2[j].Value), digit)); seriesdata.push(partaldata); } } } } } else { var data1 = hisValues[pointArr[i][0] + "purveX"]; var data2 = hisValues[pointArr[i][1] + "purveY"]; var dType = deviceType[pointArr[i][0]]; option.series[k].type = "scatter"; option.series[i].symbol = 'circle'; if (typeof data1 == "undefined" || typeof data2 == "undifined") continue; if (data1.length == data2.length) { for (var j = 0; j < data1.length; j++) { var partaldata = []; partaldata.length = 0; // 过滤%5 if (isChaoLiuNeng) { // dType = 'UPT300-16'; if (percent5Filter(parseFloat(data1[j].Value), parseFloat(data2[j].Value), isChaoLiuNeng, 0.95, 1.1)) { partaldata.push(GetDital(parseFloat(data1[j].Value), digit)); partaldata.push(GetDital(parseFloat(data2[j].Value), digit)); seriesdata.push(partaldata); } } else { partaldata.push(GetDital(parseFloat(data1[j].Value), digit)); partaldata.push(GetDital(parseFloat(data2[j].Value), digit)); seriesdata.push(partaldata); } } } } option.series[k].data = seriesdata; k++; } } }, error: function () { console.log('error'); }, complete: function (XHR, TS) { //typeArr 0,1为曲线,2为散点 曲线图设置为多选,散点图设置为单选 var sers = option.series, hasStd1 = false, hasStd2 = false, hasStd3 = false, hasStd4 = false, newSeries = [], tempSelected; if (true || typeArr[0] === '1' || typeArr[0] === '0') { if (!chart._hadSetStanderdData) { chart._standCurvalLine = chart._standCurvalLine || []; chart._standCurvalLine.length = 0; for (var key in standerdData) { if (!standerdData.hasOwnProperty(key)) continue; if (sers) { sers.push(getStanderdData(key)); } if (option.legend && option.legend[0] && option.legend[0].data) { option.legend[0].data.indexOf(key) === -1 && option.legend[0].data.unshift(key); } } chart._standCurvalLine.push(key); chart._hadSetStanderdData = true; } option.legend && option.legend[0] && (option.legend[0].selectedMode = 'multiple'); if (typeArr[0] !== '1' && typeArr[0] !== '0') { if (option && option.legend && option.legend[0]) { tempSelected = detectSelectedLegend(option.legend[0].selected, 1); } for (var i = 0, len = chart._standCurvalLine.length; i < len; i++) { if (option.legend[0].selected.hasOwnProperty(chart._standCurvalLine[i])) tempSelected[chart._standCurvalLine[i]] = option.legend[0].selected[chart._standCurvalLine[i]] } option.legend[0].selected = tempSelected; } else { if (option && option.legend && option.legend[0]) { option.legend[0].selected = detectSelectedLegend(option.legend[0].selected, 8); } } } else { } chart.clear(); chart.setOption(option, true); XHR = null; } }); } // 检测被选中的图例是否超过了limit个,如果超过只保留前面的,后面的设置为false function detectSelectedLegend(selected, limit) { var result = {}; var selectedCount = 0; for (var key in selected) { if (selected[key]) { selectedCount++; } if (selectedCount > limit) { result[key] = false; } else { result[key] = selected[key]; } } return result; } //获取标签点名称 function getPointsSelect(pageIndex, count, tablename, tagDesc, tagsDataModel, form) { var start = (pageIndex - 1) * count; str = "http://" + webServiceIP + ":" + webServicePort + "/api/Point?start=" + start + "&count=" + count + "&filter=" + tagDesc + "&tabfilter=" + tablename; str = encodeURI(str); $.ajax({ url: str, type: 'GET', dataType: 'json', cache: false, success: function (data) { if (data == null) return; pointpros = data.PointsPros; if (pointpros == null) { form.v('pagecount', "1"); return; } else { var pageCount = Math.ceil(data.Count / count); form.v('pagecount', pageCount.toString()); } var datalen = pointpros.length; for (var i = 0; i < datalen; i++) { datas = new ht.Data(); datas.setId(i + 1); datas.a('index', (i + 1).toString()); datas.a('configPointDesc', pointpros[i].Desc); datas.a('configPointName', pointpros[i].TagName); datas.a('pintunit', pointpros[i].Uint); datas.a('pointtype', pointpros[i].Type); datas.a('snapvalue', ""); datas.a('timestamp', ""); tagsDataModel.add(datas); } tagsDataModel.sm().ss(data); }, complete: function (XHR, TS) { XHR = null; } }); } function getKeyFromDic(dic, value) { for (var key in dic) { if (dic[key] == value) { return key; } } } function SetRotatPositionRelative(Node1, Node2, Angle) { var x = Node1.getPosition().x - Node2.getPosition().x; var y = Node1.getPosition().y - Node2.getPosition().y; Node1.setPosition(Math.cos(Angle) * x - Math.sin(Angle) * y + Node2.getPosition().x, Math.cos(Angle) * y + Math.sin(Angle) * x + Node2.getPosition().y); } function SetRotatPositionAbsolute(Node1, x0, y0, Angle) { var x = Node1.getPosition().x - x0; var y = Node1.getPosition().y - y0; Node1.setPosition(Math.cos(Angle) * x - Math.sin(Angle) * y + x0, Math.cos(Angle) * y + Math.sin(Angle) * x + y0); } var dataModel, graphView, view, selectionModel, serialData, $view; function initPage() { dataModel = dataModel || new ht.DataModel(); graphView = graphView || new ht.graph.GraphView(dataModel); view = view || graphView.getView(); graphView.enableFlow(); graphView.enableToolTip(); selectionModel = selectionModel || dataModel.getSelectionModel(); view.className = 'main'; // $view = $(view); // document.body.appendChild(view); // window.addEventListener('resize', function(e) { //graphView.invalidate(); // graphView.fitContent(false, 0, true); // }, false); graphView.graphViewList = graphView.graphViewList || []; serialData = serialData || dataModel.serialize(); } function hisRefresh(option, chart) { str = "http://" + webServiceIP + ":" + webServicePort + "/api/Snapshot?tagName=" + "demo.demo_ai001,demo.demo_ai002,demo.demo_ai003,demo.demo_ai004"; //str = encodeURI(str); $.ajax({ url: str, type: 'GET', dataType: 'json', cache: false, success: function (data) { if (data === null) return; var snapshots = eval(data); //判断快照是否为空 if (snapshots != null) { var newOption = {}; var varList = testHisOption.legend.data; var dataChanged = false; newOption.series = option.series; for (var i = 0; i < snapshots.length; i++) { var index = varList.indexOf(snapshots[i].TagName); if (index >= 0 && index < varList.length) { var tagValue = parseFloat(snapshots[i].Value); var tagTime = new Date(snapshots[i].Time); var len = newOption.series[index].data.length; if (len == undefined || len <= 0 || newOption.series[index].data[len - 1][0].toString() !== tagTime.toString() || newOption.series[index].data[len - 1][1] !== tagValue) { dataChanged = true; var newData = []; newData.push(tagTime); newData.push(tagValue.toFixed(2)); newOption.series[index].data.push(newData); if (newOption.series[index].data.length > 20000) { newOption.series[index].data.splice(0, newOption.series[index].data.length - 20000); } } } } if (dataChanged) { chart.setOption(newOption); } } }, complete: function (XHR, TS) { XHR = null; } }); } function getDivText(id) { return $(id).text(); } function creatTree(tree, treeDataModel, parent) { var data = new ht.Data(); data.setName(tree.name); treeDataModel.add(data); if (parent !== undefined) data.setParent(parent); if (tree.child !== undefined) { for (var i = 0; i < tree.child.length; i++) { creatTree(tree.child[i], treeDataModel, data); } } return data; } var dataAdapter = { IP: webServiceIP, port: webServicePort, init: function () { this.IP = webServiceIP; this.port = webServicePort; } }; function getTableHisData(paneNode, cmdStr, dm, columns, rows) { var paras = cmdStr.split('&'); str = "http://" + webServiceIP + ":" + webServicePort + "/api/HistoryInterval?tagName="; //+ cmdStr; str = str + encodeURIComponent(paras[0]) + "&" + paras[1] + "&" + paras[2] + "&" + paras[3] + "&" + paras[4] + "&" + paras[5] + "&" + paras[6]; dm.clear(); $.ajax({ url: str, type: 'GET', dataType: 'json', cache: false, success: function (hisdata) { if (hisdata === null) return; var data = hisdata["Datas"]; var pageCount = hisdata["PageCount"]; paneNode.v("pagecount", pageCount.toString()); if (data === null) return; var hisValues = eval(data); if (hisValues != null) { var once = false; } var length = 0; for (var key in hisValues) { if (hisValues[key].length > length) { length = hisValues[key].length; } } var tagInfos = getTagInfos(columns, rows); var tagInfosArr = tagInfos.split(","); //var rowArr=rows.split(","); //var rowCount=rowArr.length; //var columnsArr=columns.split(","); //var columnsCount=columnsArr.length; var rowArr, rowCount, columnsArr, columnsCount; if (columns == "") { rowArr = rows.split(","); columnsArr = rowArr; rowCount = 1; columnsCount = columnsArr.length; } else { rowArr = rows.split(","); rowCount = rowArr.length; columnsArr = columns.split(","); columnsCount = columnsArr.length; } for (var i = 0; i < length; i++) { if (rowCount <= 0) return; if (columnsCount > 0) { var index = 0, data = new ht.Data(), rowIndex = 0; for (var j = 0; j < tagInfosArr.length; j++) { if (columns != "") { var indicatorName = columnsArr[index].split(":")[0]; if (typeof hisValues[tagInfosArr[j]] == "undefined") { data.a(indicatorName, "无"); } else { var value = hisValues[tagInfosArr[j]][i]["Value"]; data.a(indicatorName, GetDital(value, 2)); } if (index == 0) { if (columns != "") { data.a("shebei", rowArr[rowIndex].split(":")[1]); } if (hisValues[tagInfosArr[j]]) { data.a("time", hisValues[tagInfosArr[j]][i]["Time"]); index = index + 1; } } else if (index == columnsCount - 1) { if (rowArr[rowIndex].split(":")[2] != "false") { dm.add(data); } index = 0; rowIndex = rowIndex + 1; data = new ht.Data(); } else { index = index + 1; } } else { var indicatorName = columnsArr[j].split(":")[0]; if (!data.a("time")) { data.a("time", hisValues[tagInfosArr[j]][i]["Time"]); } var value = hisValues[tagInfosArr[j]][i]["Value"]; data.a(indicatorName, GetDital(value, 2)); if (j == tagInfosArr.length - 1) { dm.add(data); } } } } } return; }, complete: function (XHR, TS) { XHR = null; } }); } var drawPoints = function (g, points, segments) { var reverse = false; /* if(g.beginPath){ g.beginPath(); }else{ reverse = true; } if(isList(points)){ points = points._as; } if(isList(segments)){ segments = segments._as; } */ if (segments && segments.length) { var pointIndex = 0, segment, p0, p1, p2, segmentIndex = 0, segmentCount = segments.length; for (; segmentIndex < segmentCount; segmentIndex++) { segment = segments[segmentIndex]; // 1: moveTo if (1 === segment) { p0 = points[pointIndex++]; g.moveTo(p0.x, reverse ? -p0.y : p0.y); } // 2: lineTo else if (2 === segment) { p0 = points[pointIndex++]; g.lineTo(p0.x, reverse ? -p0.y : p0.y); } // 3: quadraticCurveTo else if (3 === segment) { p0 = points[pointIndex++]; p1 = points[pointIndex++]; g.quadraticCurveTo(p0.x, reverse ? -p0.y : p0.y, p1.x, reverse ? -p1.y : p1.y); } // 4: bezierCurveTo else if (4 === segment) { p0 = points[pointIndex++]; p1 = points[pointIndex++]; p2 = points[pointIndex++]; g.bezierCurveTo(p0.x, reverse ? -p0.y : p0.y, p1.x, reverse ? -p1.y : p1.y, p2.x, reverse ? -p2.y : p2.y); } // 5: closePath else if (5 === segment) { g.closePath(); } } if (segment !== 5) { g.closePath(); } } else { var point, i, value, n = points.length; if (n > 0) { point = points[0]; g.moveTo(point.x, reverse ? -point.y : point.y); for (i = 1; i < n; i++) { value = points[i]; g.lineTo(value.x, reverse ? -value.y : value.y); } //if(closePath){ g.closePath(); //} } } }; function getVarValue(tag) { if (tag === undefined || tag === null) { return 0; } if ($.isNumeric(tag)) { return tag; } if (window[tag] !== undefined) { return window[tag]; } // for(var i=0; i ' + labelStr1 + VarValue[i].toFixed(2) + labelStr2 + ''; } else { html = '' + labelStr1 + VarValue[i].toFixed(2) + labelStr2 + ''; } return html; } catch (err) { return 0; } } else { var html = ""; //判断该测点是否在报警中和已确认两个报警状态中 if (alarmColorData[tag.toLowerCase()]) { html = '' + labelStr1 + VarValue[i] + labelStr2 + ''; } else { html = '' + labelStr1 + VarValue[i] + labelStr2 + ''; } return html; } } } if (tag) { varList.push(tag); VarValue.push(0); return '' + labelStr1 + '0' + labelStr2 + ''; } } function checkNumber(number) { var re = /^(-)?\d+(\.\d+)?$/; return re.test(number); } //获取控件的值 function getControlValue(node, isNumber) { var value; if (node.getSelectedItem) { value = node.getSelectedItem(); } if (node.getValue) { value = node.getValue(); } if (isNumber) { if (checkNumber(value)) { return value; } else { return 0; } } else { return value; } } //设置填充颜色透明度 function setShapeOpacity(node, opacity, nodename) { var nodebackStyle, backcolor, nodegradientcolor, gradientcolor, bc, sc; if (!isTextComps(node)) { bc = node.s("shape.background") || ''; nodebackStyle = bc.split(','); if (nodebackStyle.length >= 3) { backcolor = node.getStyle("shape.background").replace(nodebackStyle[3] || 1, opacity + ')'); node.s({ 'shape.background': backcolor }); } sc = node.s("shape.gradient.color") || ''; nodegradientcolor = sc.split(','); if (nodegradientcolor.length >= 3) { gradientcolor = node.getStyle("shape.gradient.color").replace(nodegradientcolor[3] || 1, opacity + ')'); node.s({ 'shape.gradient.color': gradientcolor }); } } else { if (!node.a("node.background")) { return; } bc = node.a("node.background") || ''; nodebackStyle = bc.split(','); if (nodebackStyle.length >= 3) { backcolor = bc.replace(nodebackStyle[3] || 1, opacity + ')'); node.a('node.background', backcolor); } sc = node.a("node.gradientcolor") || ''; nodegradientcolor = sc.split(','); if (nodegradientcolor.length >= 3) { gradientcolor = sc.replace(nodegradientcolor[3] || 1, opacity + ')'); node.a('node.gradientcolor', gradientcolor); } } } //设置边框透明度 function setBorderOpacity(node, opacity, nodename) { var nodeborderStyle, nodebordercolor; if (!isTextComps(node)) { nodeborderStyle = node.s("shape.border.color").split(','); if (nodeborderStyle.length >= 3) { nodebordercolor = node.getStyle("shape.border.color").replace(nodeborderStyle[3], opacity + ')'); node.s({ 'shape.border.color': nodebordercolor }); } } else { if (!node.a("node.color")) { return; } nodeborderStyle = node.a("node.color").split(','); if (nodeborderStyle.length >= 3) { nodebordercolor = node.a('node.color').replace(nodeborderStyle[3], opacity + ')'); node.a('node.color', nodebordercolor); } } } //设置边框线样式 function setDashStyle(node, nodename, dashstyle, nodenamewidth) { if (!nodenamewidth) { return; } if (!isTextComps(node)) { if (getDashStyle(dashstyle).length > 0) { node.s({ 'shape.border.width': nodenamewidth }); node.s({ 'shape.border.pattern': getDashStyle(dashstyle) }); } else { node.s({ 'shape.border.width': 0 }); } } else { if (getDashStyle(dashstyle).length > 0) { node.a('node.borderwidth', nodenamewidth); node.a('node.borderPattern', getDashStyle(dashstyle)); } else { node.a('node.borderwidth', 0); } } } function setColor(node, nodename, targetcolor, colortypestr) { if (!isTextComps(node)) { if (colortypestr == "backColor") { node.s('shape.background', targetcolor); } else if (colortypestr == "foreColor") { node.s('shape.gradient.color', targetcolor); } else if (colortypestr == "lineColor") { node.s('shape.border.color', targetcolor); } } else { if (colortypestr == "textBackColor") { node.a('node.background', targetcolor); } else if (colortypestr == "textForeColor") { node.a('node.gradientcolor', targetcolor); } else if (colortypestr == "textColor") { node.a('node.color', targetcolor); } else if (colortypestr == "backColor") { node.a('node.background', targetcolor); } else if (colortypestr == "foreColor") { node.a('node.gradientcolor', targetcolor); } else if (colortypestr == "lineColor") { node.a('node.color', targetcolor); } } } //获取虚线类型 function getDashStyle(dashstyle) { if (dashstyle === "Solid") { return [0, 0]; } else if (dashstyle === "LinePoint") { return [3, 3]; } else if (dashstyle === "LineSegment") { return [8, 8]; } else { return []; } } var getCoorPosition = function (a, r) { var x = r * Math.cos(a); var y = r * Math.sin(a); return { x: x + r, y: y + r }; } var getCoorList = function (a, b, r) { var list = new ht.List(); list.add(getCoorPosition(a, r)); list.add(getCoorPosition(b, r)); return list; } var getMaxValue = function (value, maxValue, minValue) { if (value > maxValue) { return maxValue; } else if (value < minValue) { return minValue; } else { return value; } } var createTableAttr = function (rowheight, rowlinevisible, rowaltercolor, isrowalter, headcolor, headGradientcolor, columnlinevisible, linecolor, backcolor, fontsize, fontcolor, fontfamily) { var obj = new Object(); obj.rowheight = rowheight; obj.rowlinevisible = rowlinevisible; obj.rowaltercolor = rowaltercolor; obj.isrowalter = isrowalter; obj.headcolor = headcolor; obj.headGradientcolor = headGradientcolor; obj.columnlinevisible = columnlinevisible; obj.linecolor = linecolor; obj.backcolor = backcolor; obj.fontsize = fontsize; obj.fontcolor = fontcolor; obj.fontfamily = fontfamily; return obj; } var setTableStyle = function (htmodel, obj) { var htmodelView = htmodel.getTableView(); var htmodelHead = htmodel.getTableHeader(); htmodelView.setRowHeight((obj.rowheight || 25) * ratio.ratioY); htmodelHead.setHeight((obj.headheight || 25) * ratio.ratioY); htmodelView.setRowLineVisible(obj.rowlinevisible); htmodelView.setColumnLineVisible(obj.columnlinevisible); htmodelHead.setColumnLineVisible(obj.columnlinevisible); htmodelHead.setColumnLineColor(obj.linecolor); htmodelView.setColumnLineColor(obj.linecolor); htmodelView.setRowLineColor(obj.linecolor); htmodelHead.setColumnLineColor(obj.linecolor); htmodelView.setScrollBarColor(obj.scrollBarColor || 'rgba(122,122,122,0.7)'); //htmodel.getView().style.backgroundColor="red"; htmodelView.getLabelColor = function () { return obj.fontcolor }; htmodelView.getLabelFont = function () { return obj.bodyfontstyle + ' ' + obj.fontsize * ratio.ratioY + "px " + obj.fontfamily }; htmodelHead.getLabelColor = function () { return obj.headFontColor; } htmodelHead.getLabelFont = function () { return obj.headerfontstyle + ' ' + obj.headerfontsize * ratio.ratioY + 'px ' + obj.headerfontfamily; } htmodelView.drawRowBackground = function (g, data, selected, x, y, width, height) { if (obj.isrowalter) { var index = htmodelView.getRowIndex(data); if (index % 2 == 0) { g.fillStyle = obj.backcolor; } else { g.fillStyle = obj.rowaltercolor; } g.beginPath(); g.rect(x, y, width, height); g.fill(); } }; if (!!obj.headerbackimage) { $(htmodelHead.getView()).css({ background: 'url(' + PAGEROOTDIR + obj.headerbackimage + ') no-repeat center center', }).addClass('back-size100'); } else { htmodelHead.getView().style.background = "-webkit-linear-gradient(" + obj.headcolor + "," + obj.headGradientcolor + ")"; //obj.headcolor+obj.headGradientcolor;//表头背景颜色 } } var isTextComps = function (node) { if (node && node.getImage && node.getImage() == "node_image") { return false; } else { return true; } } //修改渐变方式 var setPrimitiveGradientType = function (node, gradienttype, nodename) { if (!isTextComps(node)) { if (gradienttype == "NoFill") { node.s("shape.gradient", ""); node.s("shape.background", ""); node.s("shape.gradient.color", ""); } else { node.s("shape.gradient", gradienttype); } } else { //restRect.a("restRect"+".gradient","linear.north"); if (gradienttype == "NoFill") { node.a("node.background", ""); node.a("node.gradient", ""); node.a("node.gradientcolor", ""); } else { node.a("node.gradient", gradienttype); } } } //修改填充图形的渐变方式 // var setFillShapeColor=function(node,value,nodename,gradienttype,backcolor,forecolor,directfunc,borderfillwidth){ // node.a(nodename+".isFill","true"); // node.a(nodename+".borderwidth",borderfillwidth); // if(value>1) {value=1} // if(value<0) {value=0} // var width= node.originWidth || node.getWidth(); // var height= node.originHeight || node.getHeight(); // var fillold= 0,fillrect= 0,rectFill=[0,0,0,0],rectOld=[0,0,0,0]; // if(directfunc==="Horizontal"){ // fillold=height*(1-value); // fillrect=height*value; // rectFill=[0,fillold,width,fillrect]; // rectOld=[0,0,width,fillold]; // }else{ // fillold=width*(1-value); // fillrect=width*value; // rectFill=[0,0,fillrect,height]; // rectOld=[fillrect,0,fillold,height]; // } // if(node.a(nodename+".original")!=null){ // node.a(nodename+".original",rectOld); // } // if(node.a(nodename+".fillrect")!=null){ // node.a(nodename+".fillrect",rectFill); // } // if(gradienttype=="NoFill") { // node.a(nodename+".fillbackcolor",""); // node.a(nodename+".fillgradient",""); // node.a(nodename+".fillgradientcolor",""); // }else{ // node.a(nodename+".fillgradient",gradienttype); // } // node.a(nodename+'.fillbackcolor',backcolor); // node.a(nodename+'.fillgradientcolor',forecolor); // } var setFillShapeColor = function (node, value, nodename, gradienttype, backcolor, forecolor, directfunc) { var borderfillwidth = node.borderFillwidth || 0; node.a( "node.isFill", "true"); node.a( "node.borderwidth", borderfillwidth); if (value > 1) { value = 1 } if (value < 0) { value = 0 } var width = node.getWidth(); var height = node.getHeight(); var fillold = 0, fillrect = 0, rectFill = [0, 0, 0, 0], rectOld = [0, 0, 0, 0]; if (directfunc === "fromBottomToTop") { fillold = height * (1 - value); fillrect = height * value; rectFill = [0, fillold, width, fillrect]; rectOld = [0, 0, width, fillold]; } else if (directfunc === "fromLeftToRight") { fillold = width * (1 - value); fillrect = width * value; rectFill = [0, 0, fillrect, height]; rectOld = [fillrect, 0, fillold, height]; } else if (directfunc === "fromTopToBottom") { fillold = height * (1 - value); fillrect = height * value; rectFill = [0, 0, width, fillrect]; rectOld = [0, fillrect, width, fillold]; } else if (directfunc === "fromRightToLeft") { fillold = width * (1 - value); fillrect = width * value; rectFill = [fillold, 0, fillrect, height]; rectOld = [0, 0, fillold, height]; } if (node.a( "node.original") != null) { node.a( "node.original", rectOld); } if (node.a( "node.fillrect") != null) { node.a( "node.fillrect", rectFill); } if (gradienttype == "NoFill") { node.a( "node.fillbackcolor", ""); node.a( "node.fillgradient", ""); node.a( "node.fillgradientcolor", ""); } else { node.a( "node.fillgradient", gradienttype); } node.a( 'node.fillbackcolor', backcolor); node.a( 'node.fillgradientcolor', forecolor); } //将像素位置转换为HT位置 function toScreenPosition(p) { var tx = graphView.tx(); var ty = graphView.ty(); var scale = graphview.getZoom(); return { x: p.x * scale + tx, y: p.y * scale + ty }; } //风机矩阵 var GraphPaneContainer = function (paneDataModel, x, y, width, height, backColor) { var graphView = this._graphView = new ht.graph.GraphView(paneDataModel); this._view = this._graphView.getView(); var style = this._view.style; style.width = width + "px"; style.height = height + "px"; this.invalidate(); //graphView.fitContent(false,0,true); }; ht.Default.def(GraphPaneContainer, Object, { getView: function () { return this._view; }, getGraphView: function () { return this._graphView; }, invalidate: function () { //ht.Default.callLater(this.validate, this); }, validate: function () { //var height = this._view.clientHeight; //if(height < 0) height = 0; //this._graphView.getView().style.height = height + 'px'; //this._graphView.invalidate(); } }); function addNodeToContainer(quanjuDataModel, paneContainer, graphPane, nodesList) { if (nodesList.length <= 0) return; var paneDataModel = graphPane.getDataModel(); var containerBlockList = [], block, nodes, node, width, maxWidth = 0, maxNode, nx; var allowChildScale = !!paneContainer._allowChildScale; // paneDataModel._libModel = paneDataModel._libModel || new LibModel(); for (var i = 0; i < nodesList.length; i++) { block = nodesList[i]; nodes = block.childNodes; maxWidth = 0; block.scalable = allowChildScale; for (var j = 0, len = nodes.length; j < len; j++) { node = nodes[j]; if (typeof node == 'undefined') continue; node.scalable = allowChildScale; // width = node.getWidth(); // if (width > maxWidth) { // maxWidth = width; // maxNode = node; // } // 图元容器内的图形不缩放,把已缩放的恢复 if (!allowChildScale) { resizeOneNodes(node, 1 / ratio.ratioX, 1 / ratio.ratioY, true); } if (node._nodeType === 'pieDoughnut') { // 如果是环形图,要把内部的另外两个node也移动 (function () { nx = node.__background; nx && quanjuDataModel.remove(nx); nx && paneDataModel.add(nx); node.addChild(nx); nx = node.__text; nx && quanjuDataModel.remove(nx); nx && paneDataModel.add(nx); node.addChild(nx); nx = node.__pie; nx && quanjuDataModel.remove(nx); nx && paneDataModel.add(nx); node.addChild(nx); })(); } quanjuDataModel.remove(node); paneDataModel.add(node); } // block.maxWidth = block.getWidth(); // block.maxNode = block; // 重新计算图元大小 block.calcSize(); block.nodeList = nodes; containerBlockList.push(block); // dataModel._libModel.remove(block); // paneDataModel._libModel.add(block); } graphPane.blockList = containerBlockList; //把事件添加到容器上的graphView copyEventFromView(graphPane, paneContainer) } function copyEventFromView(targetGraphView, targetGraphViewContainer) { var eventList, type, offset, beforeShow; setTimeout(function () { eventList = view && view.eventList || {}; for (var key in eventList) { if (eventList.hasOwnProperty(key)) { if (key === 'contextMenu') { beforeShow = eventList[key].beforeShow || function () { }; eventList[key].beforeShow = function (e) { if (targetGraphView && targetGraphView.getDataAt(e)) { e.originEvent && e.originEvent.stopPropagation(); } beforeShow.call(this, e, targetGraphView); } eventList[key].addTo(targetGraphView.getView()) } else { targetGraphView.getView()['on'+key] = function (e) { type = e.type; offset = targetGraphViewContainer.getPosition(); // if (targetGraphView.getDataAt(e) && type !== 'mousemove') { // e.stopPropagation(); // } if (typeof eventList[type] === 'function') { eventList[type](e, targetGraphView, { x: offset.x - targetGraphViewContainer.getWidth() / 2, y: offset.y - targetGraphViewContainer.getHeight() / 2 }); } e.preventDefault(); }; } } } }, 800) } function nodesToMap(mapcontainer, mapnode, nodes, nodenameDataModel, nodenameGraphView) { if (nodes.length <= 0) return; var position, lonLat, diagonalPoint, w, h, n, ns, z, isFixed, offset = mapcontainer.getPosition(); graphView.graphViewList = graphView.graphViewList || []; graphView.graphViewList.push(nodenameGraphView); for (var i = 0; i < nodes.length; i++) { ns = nodes[i] && nodes[i].node; isFixed = nodes[i] && nodes[i].isFixed; if (!ns) { continue; } if (ns._baseClass && ns._baseClass.match('ht.lib.')) { ns = ns.childNodes; } else { ns = [ns]; } for (var j = 0, len = ns.length; j < len; j++) { n = ns[j]; position = n.getPosition(); dataModel.remove(n); w = n.getWidth(); h = n.getHeight(); lonLat = mapnode.pixelToPoint({ x: position.x - offset.x, y: position.y - offset.y }); diagonalPoint = mapnode.pixelToPoint({ x: position.x + w - offset.x, y: position.y + h - offset.y }); n.lonLat = lonLat; n.diagonalPoint = diagonalPoint; n.isFixed = isFixed; if (isFixed) { z = graphView.getZoom(); n.originPositionAndSize = { x: (position.x - offset.x + mapcontainer.getWidth() / 2) * z, y: (position.y - offset.y + mapcontainer.getHeight() / 2) * z, w: n.getWidth(), h: n.getHeight() } n.lonLat = null; n.diagonalPoint = null; } nodenameDataModel.add(n); } } //把事件添加到地图上的graphView copyEventFromView(nodenameGraphView, mapcontainer) } ; (function (window, BMap) { if (!BMap) return; BMap.HtNodeOverlay = function (htNode) { this._htNode = htNode; }; BMap.HtNodeOverlay.prototype = new BMap.Overlay(); BMap.HtNodeOverlay.prototype.initialize = function (map) { var markerPane, mapSize, div, dataModel, graphView, node, view, w, h, self; markerPane = map.getPanes().markerPane; this._map = map; self = this; dataModel = new ht.DataModel; graphView = new ht.graph.GraphView(dataModel); view = graphView.getView(); node = this._htNode; this._graphView = graphView; this._dataModel = dataModel; this._view = view; w = node.getWidth(); h = node.getHeight(); node.setPosition(w / 2 + 1, h / 2 + 1); view.style.width = w + 2 + 'px'; view.style.height = h + 2 + 'px'; view.style.postion = 'absolute'; view.style.overflow = 'visible'; graphView.setEditable = function (editable) { var self = this; this.setInteractors([]) } graphView.setEditable(false); markerPane.appendChild(view); dataModel.add(node); setTimeout(function () { self.resetPosition(); }, 200) return view; } BMap.HtNodeOverlay.prototype.draw = function () { this.resetPosition(); } BMap.HtNodeOverlay.prototype.resetPosition = function () { var htNode = this._htNode; var position = this._map.pointToOverlayPixel(htNode.lonLat); var width = htNode.getWidth(); var height = htNode.getHeight(); var graphView = this._graphView; var view = this._view; view.style.left = position.x - width / 2 + 'px'; view.style.top = position.y - height / 2 + 'px'; } BMap.HtNodeOverlay.prototype.show = function () { var view = this._view; view.style.display = ''; } BMap.HtNodeOverlay.prototype.hide = function () { var view = this._view; view.style.display = 'none'; } })(window, window.BMap); function resetPosition(map, mapDataModel, mapGraphView, zoom) { mapGraphView.tx(0); mapGraphView.ty(0); mapDataModel.each(function (data) { var lonLat, position, diagonalPixel, w, h, z; if (data instanceof ht.Node) { if (!!data.lonLat && !data.isFixed) { lonLat = data.lonLat; position = map.pointToPixel(lonLat); if (!!zoom) { diagonalPixel = map.pointToPixel(data.diagonalPoint); w = diagonalPixel.x - position.x; h = diagonalPixel.y - position.y; data.setWidth(w); data.setHeight(h); } data.setPosition(position.x, position.y); } else if (!!data.lonLat && data.isFixed) { lonLat = data.lonLat; position = map.pointToPixel(lonLat); data.setPosition(position.x, position.y); data.lonLat = null; } else if (!!data.originPositionAndSize && data.isFixed) { z = graphView.getZoom(); position = data.originPositionAndSize; data.setPosition(position.x * z, position.y * z); data.setWidth(position.w * z); data.setHeight(position.h * z); } } }); } //将节点绑定到地图上 /*function createPageTooltip(node,x,y,backcolor,str){ node.setPosition(x+node.getWidth()*0.5,y+(node.getHeight()*0.5)); node.setHtml('
' + str + '
'); node.s('2d.visible',true); } function changeToolTipContent(node,backcolor,str){ if(typeof node!="undefined"){ node.setHtml('
' + str + '
'); } }*/ function createPageTooltip(node, x, y, headStrInfo, bodyStrInfo,pos) { GD.hideTagInfo(); pos = pos || 'def'; node.setPosition(x + node.getWidth() * 0.5, y + (node.getHeight() * 0.5)); node.setHtml('
' + '
  • ' + headStrInfo.value + '
  • ' + bodyStrInfo.value + '
' + '
'); node.s('2d.visible', true); node.tip = null; // console.log(node.getWidth()+"-------------"+node.getHeight()); // console.log(x+"-------------"+y); switch(pos.toLowerCase()){ case "up": x=x-node.getWidth()/2, y=y-node.getHeight() break; case "down": x=x-node.getWidth()/2, y=y+node.getHeight()/2 break; case "left": x=x-node.getWidth(), y=y-node.getHeight()/2 break; case "right": x=x+node.getWidth()/2, y=y-node.getHeight()/2 break; case "leftup": x=x-node.getWidth(), y=y-node.getHeight() break; case "leftdown": x=x-node.getWidth() break; case "rightup": y=y-node.getHeight() break; } //console.log(x+"-------------"+y); createDomToolTip(node, x, y); } function changeToolTipContent(node, headStrInfo, bodyStrInfo) { if (typeof node != "undefined" && node.s('2d.visible') === true) { var html = '
' + '
' + '
'; node.setHtml('
' + html + '
'); if (typeof node.getStyle === 'function' && node.getStyle('2d.visible')) createDomToolTip(node, 0, 0, html); } } function changeToolTipContentColor(node, headStrInfo, bodyStrInfo) { if (typeof node != "undefined" && node.s('2d.visible') === true) { var html = '
' + '
' + '
'; node.setHtml('
' + html + '
'); if (typeof node.getStyle === 'function' && node.getStyle('2d.visible')) createDomToolTip(node, 0, 0, html); } } function getAlarmDataColor() { var flagnum = 'datacolor' var eventName = "/alarm/GetTagState"; if (window.socket != null && window.socket != "") { socket.alarmPost(eventName, varList, function (data) { if (data && data.success) { var result = data.data; alarmColorData = {}; for (var i = 0; i < result.length; i++) { //报警中和已确认的变色 if (result[i].state == 2 || result[i].state == 4) { alarmColorData[result[i].name.toLowerCase()] = ARGB2HexString(result[i].color); } } } }); } } function createDomToolTip(node, x, y, content) { var $tip = node.tip || $(node.getHtml()); if (content) { $tip.html(content); return; } // 先隐藏其它悬浮窗,页面内只能同时有一个 destoryDomToolTip(); var totalWidth = $window.width(); var totalHeight = $window.height(); var nodeWidth = node.getWidth(); var nodeHeight = node.getHeight(); if (x + nodeWidth > totalWidth) { x = x - nodeWidth; } if (y + nodeHeight > totalHeight) { y = y - nodeHeight; } $tip.width('auto'); $tip.height('auto'); $tip.css({ position: 'absolute', top: y, left: x }) $('body').append($tip); node.tip = $tip; } function destoryDomToolTip() { $('.tooltip').remove(); } function canvasTextAutoLine(str, initX, initY, width, height, lineHeight, align, fillstyle, font, maucount, g) { g.fillStyle = fillstyle; g.font = font; g.textAlign = align; var ctx = g; if (typeof str == "number") { str = str.toString(); } if (align == "center") { initX += width * 0.5; } if (align == "right") { initX += width; } var totalwidth = ctx.measureText(str).width; var lineCount = Math.floor(totalwidth / width) + maucount; initY = (height - (lineCount - 1) * lineHeight) / 2; var lineWidth = 0; var lastSubStrIndex = 0; // for (var i = 0; i < str.length; i++) { // lineWidth += ctx.measureText(str[i]).width; // if (lineWidth > width || (str[i] == "\$" && str[i + 1] == "\#")) { // ctx.fillText(str.substring(lastSubStrIndex, i).replace("\$\#", "\n"), initX, initY); // initY += lineHeight; // lineWidth = 0; // lastSubStrIndex = i; // } // if (i == str.length - 1) { // ctx.fillText(str.substring(lastSubStrIndex, i + 1).replace("\$\#", "\n"), initX, initY); // } // } ctx.textBaseLine = 'top'; var _width = ctx.measureText('口').width; var _count = Math.floor(width / _width); var _lineCount = Math.ceil(str.length / _count); var _height = _lineCount * lineHeight; if (_height > height) { initY = 0; } else { initY = (height-_height) * 0.5; } ctx.wrapFillText(str, initX, initY+lineHeight, width, lineHeight); g.closePath(); } if (CanvasRenderingContext2D.prototype.ellipse == undefined) { CanvasRenderingContext2D.prototype.ellipse = function (x, y, radiusX, radiusY, rotation, startAngle, endAngle, antiClockwise) { this.save(); this.translate(x, y); this.rotate(rotation); this.scale(radiusX, radiusY); this.arc(0, 0, 1, startAngle, endAngle, antiClockwise); this.restore(); } } if (!CanvasRenderingContext2D.prototype.wrapFillText) { CanvasRenderingContext2D.prototype.wrapFillText = function(value, x, y, maxWidth, lineHeight) { var ctx = this; var fillStyle = this.font; var getTextSize = (ht && ht.Default && ht.Default.getTextSize) || function(fillStyle, value) { return { width: ctx.measureText(value).width + 20, height: ctx.measureText('口').width + 4 } } var textSize = getTextSize(fillStyle, value) || {}; if (textSize.width < maxWidth) { ctx.fillText(value, x, y); return; } lineHeight = lineHeight || textSize.height; var arr = value.split(''); var testLine = '', line, l = arr.length - 1, lineCount = 0; for (var i = 0, a; a = arr[i]; i++) { line = testLine; testLine += a; if (ctx.measureText(testLine).width > maxWidth) { if (testLine.length <= 1) { line = a; } ctx.fillText(line, x, y + lineCount * lineHeight); testLine = testLine.substr(line.length); len = 0; lineCount++; } } testLine.length && ctx.fillText(testLine, x, y + lineCount * lineHeight); } } //绘制圆角矩形 function drawRoundRect(g, x, y, width, height, nwidth, nheight, bordercolor, borderwidth) { var nleft = x, ntop = y, rectwidth = width, rectheight = height; if (nwidth <= 0) { nwidth = 1; } if (nheight <= 0) { nheight = 1; } nwidth = nwidth * 2; nheight = nheight * 2; if (nwidth > rectwidth) { nwidth = rectwidth; } if (nheight > rectheight) { nheight = rectheight; } g.beginPath(); g.strokeStyle = bordercolor; g.lineWidth = borderwidth || 1; g.ellipse(nleft + 0.5 * nwidth, ntop + nheight * 0.5, nwidth * 0.5, nheight * 0.5, 0, Math.PI, Math.PI * 1.5); g.lineTo((nleft + rectwidth - nwidth * 0.5), ntop); g.ellipse(nleft + rectwidth - nwidth * 0.5, ntop + nheight * 0.5, nwidth * 0.5, nheight * 0.5, 0, Math.PI * 1.5, Math.PI * 2); g.lineTo((nleft + rectwidth), ntop + rectheight - nheight * 0.5); g.ellipse(nleft + rectwidth - nwidth * 0.5, ntop + rectheight - nheight * 0.5, nwidth * 0.5, nheight * 0.5, 0, 0, Math.PI * 0.5); g.lineTo((nleft + 0.5 * nwidth), ntop + rectheight); g.ellipse(nleft + 0.5 * nwidth, ntop + rectheight - nheight * 0.5, nwidth * 0.5, nheight * 0.5, 0, Math.PI * 0.5, Math.PI); g.closePath(); g.stroke(); } //绘制矩形 function drawRect(g, x, y, w, h, bordercolor) { g.beginPath(); g.moveTo(x, y); g.lineTo(w, y); g.lineTo(w, h); g.lineTo(x, h); g.closePath(); if (!!bordercolor) { g.strokeStyle = bordercolor; g.stroke(); } } function getArrMatch(arr, str) { if (arr.length <= 0) return; for (var i = 0; i < arr.length; i++) { var index = str.indexOf(arr[i]); if (index > 0) { return arr[i]; } } } function setSnapshotValue(dataModel) { var datas = dataModel._datas._as; for (var i = 0; i < datas.length; i++) { var data = dataModel.getDataById(datas[i]._id); var tagname = data.a("configPointName"); data.a("snapvalue", getVarValue(tagname)); //VarSnapshotTime[tagname.toLowerCase()] data.a("timestamp", VarSnapshotTime[tagname.toLowerCase()]); } } //导出csv文件 function exportCsv(obj) { var title = obj.title; var titleForKey = obj.titleForKey; var data = obj.data; var str = []; str.push(obj.title.join(",") + "\n"); for (var i = 0; i < data.length; i++) { var temp = []; for (var j = 0; j < titleForKey.length; j++) { temp.push(data[i][titleForKey[j]]); } str.push(temp.join(",") + "\n"); } var uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(str.join("")); var downloadLink = document.createElement("a"); downloadLink.href = uri; downloadLink.download = "export" + moment(new Date).format("YYYYMDDTHHmmss") + ".csv"; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } /* 十进制颜色值转16进制字符串 */ function ARGB2HexString(argbValue) { if (argbValue > 0) { var argbValue = parseInt(argbValue, 10); var colorValue = argbValue.toString(16); if (colorValue.length < 6) { colorValue += "00"; } } return '#' + colorValue; } function exportInterExcel(starttime, endtime, interval, valueType, tagsInfo) { if (!tagsInfo) { tagsInfo = ""; } var uri = "beginTime=" + starttime; uri += "&endTime=" + endtime; uri += "&interval=" + interval; uri += "&tagName=" + encodeURIComponent(tagsInfo); uri += "&valueType=" + valueType; var link = document.createElement("a"); link.download = "exportExcel"; link.href = "http://" + webServiceIP + ":" + webServicePort + "/api/ExportToExcelInterpo?" + encodeURI(uri); link.click(); } //获取百分比数据 function getPercentValue(value, min, max) { if (!jQuery.isNumeric(Number(value))) { return 0; } if (!jQuery.isNumeric(Number(min))) { return 0; } if (!jQuery.isNumeric(Number(max))) { return 0; } return (Number(value) - Number(min)) / (Number(max) - Number(min)) * 100; } // dataModel里所有的节点重新设置大小和位置 function resizeAllNodes(dm, ratioX, ratioY) { if (!ratioX || !ratioY) { return; } dm.each(function (d) { resizeOneNodes(d, ratioX, ratioY); }) // 重新计算图元大小 if (dm === dataModel) { _libModel.each(function (data) { resizeOneNodes(data, ratioX, ratioY); }) } } function resizeOneNodes(d, ratioX, ratioY, force) { var w, h, x, y, p, pas, _ratioX, _ratioY, _ratio, rotation; if ((d.scalable === false || d.__parentLib || d.__blockChild) && !force) { return; } ratioX = ratioX || graphView.ratioX; ratioY = ratioY || graphView.ratioY; if (d && typeof d.getRotation === 'function') { rotation = d.getRotation() * 180 / Math.PI; } else { rotation = 0; } _ratio = GD.getRatioWithRotation(rotation * Math.PI / 180, ratioX, ratioY); if (d._zoomBy) { if (d._zoomBy === 'False' || d._zoomBy === 'false') { _ratioX = 1; _ratioY = 1; } else if (d._zoomBy === 'Default') { _ratioX = _ratio.ratioX; _ratioY = _ratio.ratioY; } else if (d._zoomBy === 'X') { _ratioX = _ratio.ratioX; _ratioY = _ratio.ratioX; } else if (d._zoomBy === 'Y') { _ratioX = _ratio.ratioY; _ratioY = _ratio.ratioY; } } else { _ratioX = _ratio.ratioX; _ratioY = _ratio.ratioY; } w = d.getWidth(); h = d.getHeight(); p = d.getPosition(); x = p.x + 5; y = p.y + 5; d.originWidth = d.originWidth || w; d.originHeight = d.originHeight || h; d.originPosition = d.originPosition || p; w *= _ratioX; h *= _ratioY; if (!!d.isEqualRatio) { d.lastWidth = d.lastWidth || d.originWidth; d.lastHeight = d.lastHeight || d.originHeight; d.lastWidth *= _ratioX; d.lastHeight *= _ratioY; w = d.lastWidth > d.lastHeight ? d.lastHeight : d.lastWidth; h = w; } d.setWidth(w); d.setHeight(h); d.setPosition(x * ratioX, y * ratioY); if (d.originPositionAndSize) { pas = d.originPositionAndSize; pas.x *= ratioX; pas.y *= ratioY; pas.w *= _ratioX; pas.h *= _ratioY; } } // 绘制椭圆 function drawEllipse(ctx, x, y, w, h) { var kappa = .5522848, ox = (w / 2) * kappa, // control point offset horizontal oy = (h / 2) * kappa, // control point offset vertical xe = x + w, // x-end ye = y + h, // y-end xm = x + w / 2, // x-middle ym = y + h / 2; // y-middle ctx.beginPath(); ctx.moveTo(x, ym); ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); ctx.closePath(); // not used correctly, see comments (use to close off open path) // ctx.stroke(); } // 显示页面 function showPage() { // graphView.setDataModel(dataModel); graphView.tx(0); graphView.ty(0); graphView.setZoom(1); document.body.appendChild(view); setTimeout(function () { window.refreshAlarmInfoWindow && refreshAlarmInfoWindow(); }, 500) } // 固定列表格 ; (function (W, $, ht) { if (!ht) { return; } ht.widget = ht.widget || {}; ht.widget.FrozenTable = function (dm) { var self = this; dm = dm || new ht.DataModel(); this._borderPane = new ht.widget.BorderPane(); this._frozenTablePane = new ht.widget.TablePane(dm); this._normalTablePane = new ht.widget.TablePane(dm); this._frozenTableHeader = this._frozenTablePane.getTableHeader(); this._frozenTableView = this._frozenTablePane.getTableView(); this._normalTableHeader = this._normalTablePane.getTableHeader(); this._normalTableView = this._normalTablePane.getTableView(); this._dm = dm; this._selectionModel = dm.getSelectionModel(); this.init(); } ht.Default.def('ht.widget.FrozenTable', Object, { init: function () { var frozenTableView = this.getFrozenTableView(); var normalTableView = this.getNormalTableView(); frozenTableView.setScrollBarSize(0); this._borderPane.setLeftView(this._frozenTablePane, 200); this._borderPane.setCenterView(this._normalTablePane); frozenTableView.mp(function (e) { if (e.property === 'translateY') { normalTableView.ty(e.newValue); } }); normalTableView.mp(function (e) { if (e.property === 'translateY') { frozenTableView.ty(e.newValue); } }); this._setColumnClickEvent(); this._setDrawColumnFunc(); this.setAutoHideScrollBar(false); }, getFrozenTableView: function () { return this._frozenTableView; }, getFrozenTableHeader: function () { return this._frozenTableHeader; }, setFrozentableScrollBarColor: function (color) { this._normalTableView.setScrollBarColor(color); }, getFrozentableScrollBarColor: function () { return this._normalTableView.getScrollBarColor(); }, setFrozentableScrollBarSize: function (size) { this._normalTableView.setScrollBarSize(size) }, getFrozentableScrollBarSize: function () { return this._normalTableView.getScrollBarSize(); }, getNormalTableView: function () { return this._normalTableView; }, getNormalTableHeader: function () { return this._normalTableHeader; }, getDataModel: function () { return this._normalTableView.getDataModel(); }, getSelectionModel: function () { return this._dm.getSelectionModel();; }, calcColumnWidthByDisplayName: function (displayName, fontsize) { fontsize = fontsize || 12; fontsize *= 0.5; var nameLen = GD.getStrLength(displayName); return Math.ceil((nameLen + 4) * fontsize); }, addColumns: function (columns) { var frozenColumns = []; var normalColumns = []; var frozenTableWidth = 0; var that = this; function sortColumns(a, b) { if (a.sortId > b.sortId) { return 1; } else if (a.sortId < b.sortId) { return -1; } return 0; } for (var i = 0, len = columns.length; i < len; i++) { if (!columns[i]) { continue; } columns[i].sortable = false; columns[i].width = columns[i].width ? columns[i].width : this.calcColumnWidthByDisplayName(columns[i].displayName); if (!!columns[i].isFrozenColumn) { frozenColumns.push(columns[i]); if (columns[i].visible) frozenTableWidth += columns[i].width; } else { normalColumns.push(columns[i]); } } frozenColumns.sort(sortColumns); normalColumns.sort(sortColumns); frozenTableWidth += this._frozenTableView.isCheckMode() ? this._frozenTableView.getCheckColumn().getWidth() : 0; this._frozenTableView.addColumns(frozenColumns); this._normalTableView.addColumns(normalColumns); this._borderPane.setLeftWidth(frozenTableWidth); }, resetLeftPaneWidth: function () { var w = 0; columnModel = this._frozenTableView.getColumnModel(); columnModel.each(function (data) { if (data.isVisible()) w += data.getWidth(); }); this._borderPane.setLeftWidth(w); }, getBorderPane: function () { return this._borderPane; }, isCheckMode: function () { return this._frozenTableView.isCheckMode(); }, setCheckMode: function (checkMode, fontOption) { var that = this; this._frozenTableView.setCheckMode(checkMode); }, selectAll: function () { var selectModel = this.getSelectionModel(); selectModel.selectAll(); }, invertSelection: function () { var tableModel = this._dm; var selectModel = this.getSelectionModel(); tableModel.each(function (item) { if (selectModel.contains(item)) { selectModel.removeSelection(item); } else { selectModel.appendSelection(item); } }) }, clearSelection: function () { var selectionModel = this.getSelectionModel(); selectionModel.clearSelection(); }, setRowHeight: function (rowHeight) { this._frozenTableView.setRowHeight(rowHeight); this._normalTableView.setRowHeight(rowHeight); this._normalTableHeader.setHeight(rowHeight); this._frozenTableHeader.setHeight(rowHeight); }, getRowHeight: function () { return this._normalTableView.getHeight(); }, setHeaderHeight: function (height) { if (!$.isNumeric(height)) { return this; } height += 0; this._frozenTableHeader.setHeight(height); this._normalTableHeader.setHeight(height); }, getHeaderHeight: function () { return this._normalTableHeader.getHeight(); }, setBackground: function (backColor) { this.getFrozenTableView().getView().style.background = backColor; this.getNormalTableView().getView().style.background = backColor; }, getCheckIcon: function (unSelData, selData) { var sm = this._selectionModel; this._selData = selData; this._unSelData = unSelData; this._frozenTableView.getCheckIcon = function (d) { if (sm.contains(d)) { return selData } return unSelData; }; }, setHeaderGradientColor: function (headColor, headGradientcolor) { this.getFrozenTableHeader().getView().style.background = "-webkit-linear-gradient(" + headColor + "," + headGradientcolor + ")"; //obj.headcolor+obj.headGradientcolor;//表头背景颜色 this.getNormalTableHeader().getView().style.background = "-webkit-linear-gradient(" + headColor + "," + headGradientcolor + ")"; //obj.headcolor+obj.headGradientcolor;//表头背景颜色 }, getLabelColor: function (fontColor) { this.getFrozenTableHeader().getLabelColor = function () { return fontColor; } this.getNormalTableHeader().getLabelColor = function () { return fontColor; } }, getLabelFont: function (fontSize, fontFamily, fontStyle) { this.getFrozenTableHeader().getLabelFont = function () { return fontStyle + ' ' + fontSize * ratio.ratioY + "px " + fontFamily; } this.getNormalTableHeader().getLabelFont = function () { return fontStyle + ' ' + fontSize * ratio.ratioY + "px " + fontFamily; } }, setHeaderLabelFont: function (fontSize, fontFamily, fontStyle) { // this._headerLabelFont = fontStyle + ' ' + fontSize + "px " + fontFamily; this._headerFontStyle = fontStyle; this._headerFontSize = fontSize; this._headerFontFamily = fontFamily; }, setBodyLabelFont: function (fontSize, fontFamily, fontStyle) { // this._bodyLabelFont = fontStyle + ' ' + fontSize + "px " + fontFamily; this._bodyFontStyle = fontStyle; this._bodyFontSize = fontSize; this._bodyFontFamily = fontFamily; }, getHeaderLabelFont: function () { return this._headerFontStyle + ' ' + this._headerFontSize * ratio.ratioY + "px " + this._headerFontFamily; }, getBodyLabelFont: function () { return this._bodyFontStyle + ' ' + this._bodyFontSize * ratio.ratioY + "px " + this._bodyFontFamily; }, setRowLineColor: function (lineColor) { this._frozenTableView.setRowLineColor(lineColor); this._normalTableView.setRowLineColor(lineColor); // this._frozenTableHeader.setRowLineColor(lineColor); // this._normalTableHeader.setRowLineColor(lineColor); }, getRowLineColor: function () { return this._normalTableView.getRowLineColor(); }, getColumnLineColor: function () { return this._normalTableHeader.getColumnLineColor(); }, setColumnLineColor: function (lineColor) { this._frozenTableHeader.setColumnLineColor(lineColor); this._normalTableHeader.setColumnLineColor(lineColor); this._frozenTableView.setColumnLineColor(lineColor); this._normalTableView.setColumnLineColor(lineColor); }, isColumnLineVisible: function () { return this._normalTableHeader.isColumnLineVisible(); }, setColumnLineVisible: function (isVisible) { this._normalTableHeader.setColumnLineVisible(isVisible); this._frozenTableHeader.setColumnLineVisible(isVisible); this._frozenTableView.setColumnLineVisible(isVisible); this._normalTableView.setColumnLineVisible(isVisible); }, setRowLineVisible: function (isVisible) { this.getFrozenTableView().setRowLineVisible(isVisible); this.getNormalTableView().setRowLineVisible(isVisible); }, drawRowBackground: function (backColor, isRowAlter, rowAlterColor, selectedRowColor) { var tableView, self = this; selectedRowColor = selectedRowColor || 'rgba(100, 100, 100, 0.3)'; function drawRowBack(g, data, selected, x, y, width, height) { var index = this.getRowIndex(data); if (isRowAlter) { if (index % 2 == 0) { g.fillStyle = backColor; } else { g.fillStyle = rowAlterColor; } } else { g.fillStyle = backColor; } if (selected && selectedRowColor) { g.fillStyle = selectedRowColor } g.beginPath(); g.rect(x, y, width, height); g.fill(); } self.getFrozenTableView().drawRowBackground = function () { tableView = self.getFrozenTableView(); drawRowBack.apply(tableView, arguments); } self.getNormalTableView().drawRowBackground = function () { tableView = self.getNormalTableView(); drawRowBack.apply(tableView, arguments); } }, drawCell: function (g, data, selected, column, x, y, w, h, tableView) { var tagName = data._name + column._name; var name = column.getName(); var columnData = column[name] || {}; var textAlign = 'center' || column.getAlign(); var text = data.a(name) || 0; var color = columnData.a('color') || 'balck', font = columnData.a('fontStyle') || null; var selectedColor = columnData.a('selectedRowColor') || 'rgba(100, 100, 100, 0.3)'; var statusMap = columnData.a('statusMap') || []; var statusArr = []; var status = ''; var _x, _y; function drawRoundRectPath(cxt, x, y, width, height, radius) { cxt.moveTo(x + radius, y); cxt.lineTo(x + width - radius, y); cxt.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2); cxt.lineTo(x + width, y + height - radius); cxt.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5); cxt.lineTo(x + radius, y + height); cxt.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI); cxt.lineTo(x, y + radius); cxt.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5); cxt.closePath(); } // draw background // g.fillStyle = selected ? selectedColor : 'rgba(0,0,0,0)'; // g.beginPath(); // g.rect(x, y, w, h); // g.fill(); if (statusMap.length > 0) { for (var i = 0, len = statusMap.length; i < len; i++) { sk = statusMap[i] || {}; pt = parseFloat(text); if (sk.min === 'min' && pt < sk.max) { status = sk; break; } if (pt >= sk.min && sk.max === 'max') { status = sk; break; } if ((pt >= sk.min && pt < sk.max) || (pt === sk.min && pt === sk.max)) { status = sk; break; } } switch (textAlign) { case 'center': _x = x + w * 0.1; _y = y + h / 4; break; case 'right': _x = x + w * 0.2; _y = y + h / 4; break; case 'left': _x = x; _y = y + h / 4; break; default: _x = x; _y = y + h / 4; break; } status = status || {}; color = status.backColor || 'rgba(0,0,0,0)'; g.beginPath(); // g.fillStyle = selected ? ht.Default.darker(color) : color; g.fillStyle = selected ? color : color; drawRoundRectPath(g, _x, _y, w * 0.8, h * 0.5, 4); g.fill(); } // draw label color = columnData.a('color'); // color = selected ? ht.Default.darker(color) : color; //判断是否报警变色 if (alarmColorData[tagName.toLowerCase()]) { color = alarmColorData[tagName.toLowerCase()]; } if (status) { color = status.fontColor; text = status.text; } var textWidth = this.calcColumnWidthByDisplayName(text, this._bodyFontSize * ratio.ratioY); if (textWidth > column.getWidth()) { column.setWidth(textWidth); this.resetLeftPaneWidth(); } ht.Default.drawText(g, text, font, color, x, y, w, h, textAlign); }, refresh: function (columnDM) { var frozenTableView = this.getFrozenTableView(), normalTableView = this.getNormalTableView(), frozenTableColumnModel = frozenTableView.getColumnModel(), normalTableColumnModel = normalTableView.getColumnModel(), tempData; columnDM && columnDM.each(function (cd) { tempData = frozenTableColumnModel.getDataByTag(cd.a('name')) || normalTableColumnModel.getDataByTag(cd.a('name')); tempData.setVisible(cd.a('visible')); }); frozenTableView.redraw(); normalTableView.redraw(); }, redraw: function () { var frozenTableView = this.getFrozenTableView(), normalTableView = this.getNormalTableView(); frozenTableView.redraw(); normalTableView.redraw(); }, addRowData: function () { var columnDM = this.getCustomDM('columnDM'); var rowDM = this.getCustomDM('rowDM'); var tableModel = this.getDataModel(); rowDM.each(function (data) { var rowName = data.a('name'); var rowDisplayName = data.a('displayName'); var d = new ht.Data(); columnDM.each(function (dt) { var columnName = dt.a('name'); var tag = '' + rowName + columnName; d.a(columnName, getVarValue(tag)); if (columnName === 'device') { d.a(columnName, rowDisplayName); } }) d.setName(rowName); d.setTag(rowName); d.a('displayName', rowDisplayName); d.a('visible', data.a('visible')); d.a('name', rowName); tableModel.add(d); }) }, refreshRowData: function () { var tableModel = this.getDataModel(), attrObj, rowName; tableModel.each(function (data) { attrObj = data.getAttrObject(); rowName = data.getName(); for (var key in attrObj) { if (attrObj.hasOwnProperty(key)) { if (key === 'visible' || key === 'device' || key === 'displayName' || key === 'name') { continue; } data.a(key, getVarValue(rowName + key)); } } }); this.getFrozenTableView().invalidateModel(); this.getNormalTableView().invalidateModel(); }, refreshStyleRowData: function (data) { var tabledata = data; var tableModel = this.getDataModel(), attrObj, rowName; tableModel.each(function (data) { attrObj = data.getAttrObject(); rowName = data.getName(); for (var i = 0; i < tabledata.length; i++) { //var obj=tabledata[i]._attrObject; if (attrObj.name == tabledata[i].name) { data.a('visible', tabledata[i].visible); break; } } for (var key in attrObj) { if (attrObj.hasOwnProperty(key)) { if (key === 'visible' || key === 'device' || key === 'displayName' || key === 'name') { continue; } data.a(key, getVarValue(rowName + key)); } } }); this.getFrozenTableView().invalidateModel(); this.getNormalTableView().invalidateModel(); }, addCustomDM: function (dmName, dm) { if (this['_' + dmName]) { return; } if (dm.constructor === ht.DataModel) { this['_' + dmName] = dm; } else { this['_' + dmName] = new ht.DataModel(); } }, getCustomDM: function (dmName) { return this['_' + dmName]; }, setVisibleFunc: function (func) { this.getNormalTableView().setVisibleFunc(func); this.getFrozenTableView().setVisibleFunc(func); }, getFrozenColumnModel: function () { return this.getFrozenTableView().getColumnModel(); }, getNormalColumnModel: function () { return this.getNormalTableView().getColumnModel(); }, clear: function () { return this._dm.clear(); }, setAutoHideScrollBar: function (autoHide) { this._normalTableView.setAutoHideScrollBar(autoHide); }, defaultDisplayGridLine: function (display, rowCount, colCount) { if (!display) { return; } var dm = this.getDataModel(); for (var i = 0; i < rowCount; i++) { var data = new ht.Data(); dm.add(data); } var columns = []; for (i = 0; i < colCount; i++) { var col = {}; col.displayName = ''; col.width = 100; col.width = 100; col.align = 'center'; if (i === 0) { col.isFrozenColumn = true; col.displayName = '时间'; } else { col.isFrozenColumn = false; } columns.push(col); } this.addColumns(columns); }, setDataModel: function (dataModel) { this._dm = dataModel; this._normalTableView.setDataModel(dataModel); this._frozenTableView.setDataModel(dataModel); }, sort: function (sortColumn, sortOrder) { var newDM = new ht.DataModel(); var len = this._dm._datas._as.length; if (sortOrder === 'default') { if (this._defaultDM) { // this.setDataModel(this._defaultDM); this._copyDM2DataModel(this._defaultDM); } this._defaultDM = null; return; } if (!this._defaultDM) { this._defaultDM = new ht.DataModel(); this._defaultDM.deserialize(this._dm.serialize()); } for (var i = 0; i < len; i++) { newDM.add(this.getOrderData(sortColumn, sortOrder)); } // this.setDataModel(newDM); this._copyDM2DataModel(newDM); }, getOrderData: function (sortColumn, sortOrder) { var datas = this._dm._datas._as; var data = datas[0]; var d1, d2; for (var i = 1, len = datas.length; i < len; i++) { d1 = data.a(sortColumn); d2 = datas[i].a(sortColumn); if ($.isNumeric(d1)) { d1 = d1 - 0; } if ($.isNumeric(d2)) { d2 = d2 - 0; } if (sortOrder === 'desc' || sortOrder === 'Desc' || sortOrder === 'DESC') { d1 < d2 && (data = datas[i]); } else { d1 > d2 && (data = datas[i]); } } this._dm.remove(data); return data; }, _copyDM2DataModel: function (dm1, dm2) { if (!dm1) return; var dm2 = dm2 || this.getDataModel(); dm2.clear(); dm2.deserialize(dm1.serialize()); }, _setColumnClickEvent: function () { var that = this; function func(column, event) { var columnName = column.getName() || column.a('name') || column.getDisplayName() || column.a('displayName') || ''; var sortOrder = column.getSortOrder() || 'asc'; that.sort(columnName, sortOrder); that._clearColumnIcon(); if (sortOrder === 'asc') { column.setSortOrder('desc'); } else if (sortOrder === 'desc') { column.setSortOrder('default'); } else if (sortOrder === 'default') { column.setSortOrder('asc'); } column._isCustomSortColumn = true; } this.onColumnClicked = func; this._frozenTableView.onColumnClicked = func; this._normalTableView.onColumnClicked = func; }, _clearColumnIcon: function () { var frozenColumnModel = this._frozenTableView.getColumnModel(); var normalColumnModel = this._normalTableView.getColumnModel(); frozenColumnModel.each(function (data) { data._isCustomSortColumn = false; data.setSortOrder('asc'); }); normalColumnModel.each(function (data) { data._isCustomSortColumn = false; data.setSortOrder('asc'); }); }, _setDrawColumnFunc: function (func) { var that = this; function defaultFunc(g, column, x, y, width, height) { var displayName = column.getDisplayName() || column.a('displayName') || column.getName(); var color = column.getColor() || column.a('color') || "black"; var font = that.getHeaderLabelFont() || null; var checkIcon; if (column === that._frozenTableView.getCheckColumn()) { if (that._frozenTableHeader._checkIcon === 'uncheck') { checkIcon = that._unSelData; } else { checkIcon = that._selData; } ht.Default.drawImage(g, checkIcon, x + (width - checkIcon.width) * 0.5, y + (height - checkIcon.height) * 0.5, checkIcon.width, checkIcon.height, column, that._normalTableView); return; }; ht.Default.drawText(g, displayName, font, color, x, y, width, height, 'center'); that._selectAllBtn && that._selectAllBtn.setLabelFont(that.getHeaderLabelFont()); that._selectInvertBtn && that._selectInvertBtn.setLabelFont(that.getHeaderLabelFont()); var sortIcon, sortOrder; sortOrder = column.hasOwnProperty('_sortOrder') ? column._sortOrder : ''; // 三种状态循环 switch (sortOrder) { case 'desc': sortIcon = that._normalTableHeader.getSortAscIcon(); break; case 'default': sortIcon = that._normalTableHeader.getSortDescIcon(); break; case 'asc': default: sortIcon = null; break; } if (!column._isCustomSortColumn) { sortIcon = null; } ht.Default.drawImage(g, sortIcon, x + width - 14, y + (height - 16) * 0.5, 16, 16, column, that._normalTableView); } func = func || defaultFunc; this._frozenTableHeader.drawColumn = func; this._normalTableHeader.drawColumn = func; }, validate: function () { this._frozenTableView.validate(); this._normalTableView.validate(); } }) })(window, jQuery, ht); function batchOpertation(tagfirststr, tagsencondstr, value, quality, desc, groupid) { if (tagfirststr.length <= 0) return; var tagFirstNames = tagfirststr.split(";"); if (tagFirstNames.length <= 0) return; var dataList = [], groupid = groupid || 0; for (var i = 0; i < tagFirstNames.length; i++) { var data = { TagName: tagFirstNames[i] + tagsencondstr, Time: "", Value: value, Quality: quality }; if (data.Time === "") { data.Time = "1900-01-01 00:00:00"; } dataList.push(data); } if (isAuthEnable == "True" && groupid >= 0) { getAuthInfoByGroupId(groupid, function (data) { if (data) { submitBatch(dataList, desc); } }); } else if (isAuthEnable == "True" && groupid == -1) { submitBatch(dataList, desc); } else { submitBatch(dataList, desc); } // submitBatch(dataList, desc, groupid); } function submitBatch(_data, desc) { desc = desc || ''; if (!isdowncontrol()) { return; } var jsonStr = JSON.stringify(_data); $.ajax({ url: "http://" + webServiceIP + ":" + webServicePort + "/api/Snapshot/", type: "POST", data: jsonStr, contentType: "application/json; charset=utf-8", success: function (data) { if ((typeof data == 'string') && data.constructor == String) //数据库版本2.x { if (data !== "True") GD.createErrorDialog(360, 160, data); } else ////数据库版本3.x { var errorList = data.ErrorList; if (errorList != null && errorList.length > 0) { GD.createErrorDialog(360, 160, errorList[0].ErrorMsg); } else { (function () { var varName, value, groupid, d, quality; groupid = GD.getParams('userGroup') || 0; for (var i = 0, len = _data.length; i < len; i++) { d = _data[i]; varName = d.TagName || ''; value = d.Value; quality = d.Quality; addOpera(varName, varName.split('.')[0], value, groupid, desc, quality, function (data) { }); } })(); } } }, error: function (data) { if (data.responseText === "") GD.createErrorDialog(360, 160, '网络链接错误'); else GD.createErrorDialog(360, 160, data.responseText); }, complete: function (XHR, TS) { XHR = null; } }); } function convertNumberToIntAndFloat(text, precision) { var result = {}, textArr, textObj; text = parseFloat(text); text = text ? text : 0; precision = parseInt(precision); precision = precision !== precision ? 2 : precision; text = text.toFixed(precision, 10); textArr = text.split('.'); result.int = textArr[0]; result.float = textArr[1] || '0'; return result; } function searchStrToObj(searchStr) { var searchArr, tempArr, result = {}; searchStr = searchStr || window.location.search; searchStr = decodeURIComponent(searchStr); searchStr = searchStr.indexOf('?') === -1 ? searchStr : searchStr.substr(searchStr.indexOf('?') + 1); searchArr = searchStr.split('&'); for (var i = 0, len = searchArr.length; i < len; i++) { if (searchArr[i].indexOf('=') === -1) { continue; } tempArr = searchArr[i].split('='); if (!!tempArr[1]) { result[tempArr[0]] = tempArr[1]; } } return result; } ; (function (W, $, ht) { if (!ht) { return; } W.pageContainerFactory = function (x, y, width, height, angle, src) { var htmlNode = new ht.HtmlNode(); var $content, timer; $content = $(''); htmlNode.setScalable(false); htmlNode.setPadding(0); htmlNode.setHtml($content[0]); htmlNode.setWidth(width); htmlNode.setHeight(height); htmlNode.setPosition(x, y); htmlNode.setRotation(angle * Math.PI / 180); htmlNode.s({ '2d.selectable': true, '2d.movable': false }) htmlNode.__clickable = false; htmlNode.changeSrc = function (src) { if (!src) { return; } $content.attr('src', src); } htmlNode.changeWidth = function (width) { $content.attr('width', width); htmlNode.setWidth(width); } htmlNode.changeHeight = function (height) { $content.attr('height', height); htmlNode.setHeight(height); } htmlNode.changeAttr = function (src, width, height) { this.changeSrc(src); this.changeWidth(width); this.changeHeight(height); } htmlNode.refresh = function () { $content.attr('src', $content.attr('src')); } htmlNode.resizeContent = function (ratioX, ratioY, zoom) { var self = this; $content.on('load', function () { $content[0].contentWindow.postMessage({ action: 'resizeNodes', args: { ratioX: ratioX, ratioY: ratioY, zoom: zoom } }, '*'); }); } return htmlNode; } })(window, jQuery, ht); (function (W, $, ht) { if (!ht || !$) { return; } W.paginationFactory = function (totalPages, visiblePages, currentPage) { var $pagination = $(''); $.jqPaginator($pagination, { totalPages: totalPages, visiblePages: visiblePages || 5, currentPage: currentPage || 1, prev: '', next: '', page: '
  • {{page}}
  • ', onPageChange: function (num, type) { typeof $pagination.onPageChange === 'function' && $pagination.onPageChange(num, type); } }); return $pagination; } })(window, jQuery, ht); // 监听对象属性变化方法 (function () { if (!Object.prototype.watch) { Object.defineProperty(Object.prototype, "watch", { enumerable: false, configurable: true, writable: false, value: function (prop, handler) { var oldval = this[prop], newval = oldval, getter = function () { return newval; }, setter = function (val) { oldval = newval; return newval = handler.call(this, prop, oldval, val); }; if (delete this[prop]) { // can't watch constants Object.defineProperty(this, prop, { get: getter, set: setter, enumerable: true, configurable: true }); } } }); } // object.unwatch if (!Object.prototype.unwatch) { Object.defineProperty(Object.prototype, "unwatch", { enumerable: false, configurable: true, writable: false, value: function (prop) { var val = this[prop]; delete this[prop]; // remove accessors this[prop] = val; } }); } })(); var getIndicatorAndSheBeiArr = function (equipObj, indicatorObj) { var obj = {}; var shebeiArr = []; var indicatorArr = []; var colorArr = []; var statisticsTypeObj = {}; var tagArr = [], tag; for (var i = 0; i < indicatorObj.length; i++) { var dName = indicatorObj[i]["displayName"] || indicatorObj[i]["Desc"]; indicatorArr.push(dName); colorArr.push(indicatorObj[i]['color']); } for (var j = 0; j < equipObj.length; j++) { shebeiArr.push(equipObj[j]["displayName"]); } for (var i = 0, len = equipObj.length; i < len; i++) { for (var j = 0, leng = indicatorObj.length; j < leng; j++) { tag = '' + equipObj[i].Name + indicatorObj[j].Name; tagArr.push(tag); var statisticsType = indicatorObj[j]['statisticsType']; if (statisticsType) { switch (statisticsType.toLowerCase()) { case 'min': statisticsType = 'Min'; break; case 'max': statisticsType = 'Max'; break; case 'avg': case 'calcavg': statisticsType = 'CalcAvg'; break; case 'difference': statisticsType = 'Difference'; break; case 'total': statisticsType = 'Total'; break; case 'poweravg': statisticsType = 'PowerAvg'; break; } } statisticsTypeObj[tag] = statisticsType } } obj["shebeiArr"] = shebeiArr; obj["indicatorArr"] = indicatorArr; obj['tagArr'] = tagArr; obj['colorArr'] = colorArr; obj['statisticsTypeObj'] = statisticsTypeObj; return obj; }; //获取series var getIndicatorOrShebeiInfo = function (equipObj, indicatorObj, seriesStyle) { var series = []; for (var i = 0; i < indicatorObj.length; i++) { var seriesData = [], _type = indicatorObj[i]['DrawType'] === 0 ? 'bar' : 'line', _smooth = indicatorObj[i]['DrawType'] === 2; for (var j = 0; j < equipObj.length; j++) { var tagValue = '' + equipObj[j].Name + indicatorObj[i].Name; seriesData.push(parseFloat(getVarValue(tagValue))); } series.push({ name: indicatorObj[i]["displayName"] || indicatorObj[i]["Desc"], type: _type, smooth: _smooth, data: seriesData, itemStyle: { normal: { shadowBlur: 10, shadowOffsetX: 10, shadowOffsetY: 10, shadowColor: seriesStyle.shadowColor, // color: indicatorObj[i].color }, emphasis: { shadowBlur: 10, shadowOffsetX: 10, shadowOffsetY: 10, shadowColor: seriesStyle.shadowColor } } }); } return series; } // 获取相对时间,如昨天,今天,明天,上周,本周,上个月,本月, 上一年,本年等, 传入参数为一个固定时间,原样返回 function getRelativeDate(paras, format, beginOrEnd) { var d = new Date(); var typeMap = { date: 'YYYY-MM-DD', time: 'HH:mm:ss', datetime: 'YYYY-MM-DD HH:mm:ss', year: 'YYYY', month: 'YYYY-MM' } function formatDate(date, format) { var result = moment(date).format(typeMap[format] || typeMap.datetime); return result === 'Invalid date' ? date : result; } function calcRelativeDate(date, type) { var count = parseInt(type); if (count !== count) { return type; } var t = type.substr(count.toString().length); switch (t) { case 'h': case 'hour': date.setHours(date.getHours() - count); break; case 'd': case 'day': date.setDate(date.getDate() - count); break; case 'm': case 'month': date.setMonth(date.getMonth() - count); break; case 'y': case 'year': date.setFullYear(date.getFullYear() - count); break; default: date = type; break; } return date; } if ('begin' === beginOrEnd) { d.setHours(0); d.setMinutes(0); d.setSeconds(0); d.setMilliseconds(0); } else if ('end' === beginOrEnd) { d.setHours(23); d.setMinutes(59); d.setSeconds(59); d.setMilliseconds(0); } if (paras === '') { // 如果参数为空则返回当前时间 return formatDate(d, format); } d = calcRelativeDate(d, paras); return formatDate(d, format); } // tabView 中添加tab function createTab(tabView, item) { var tabModel = tabView.getTabModel(); var tab = new ht.Tab(); tab.setName(item.name); tab.setTag(item.name); // tab.setView(item.innerView); tab.setView(item.view); tab.a('currentData', item.currentData); // tab.a('curAlarmIndex', item.curAlarmIndex); index tab.a('curAlarmIndex', item.index); tabModel.add(tab); if (item.selected) { tabModel.getSelectionModel().setSelection(tab); } } // 创建带有tab页的弹窗 config: {title: '', titleIcon: ''}, tabConfig: [{name: '', view: '', selected: false}] function createDialogWithTabView(config, tabConfig, twinkle, tablestyle) { var dialog = new ht.widget.Dialog(); var tabView = new ht.widget.TabView(); tabConfig.forEach(function (item, index) { createTab(tabView, item); }); // tabView.setTabBackground('rgb(12, 77, 85)'); tabView.setLabelColor(tablestyle.paneSysFontColor); tabView.setTabBackground(tablestyle.paneSysBackColor); tabView.onTabChanged = tabConfig.onTabChanged; config.content = tabView; dialog.setConfig(config); dialog.tabView = tabView; dialog.tabModel = tabView.getTabModel(); var $dialog = $(dialog.getView()); var $dialogContainer = $dialog.find('.dialog-container'); var $dialogContainerTitle = $dialogContainer.find('.dialog-container-title'); var twinkleFlag = false; var dialogHeight = $dialogContainer.height(); var dialogTop = parseInt($dialogContainer.css('top')); var dialogTitleHeight = $dialogContainerTitle.height() || 24; $dialogContainer.css({ 'zIndex': 99, 'top': '', 'left': '', 'right': '5px', 'bottom': '28px' }); $dialogContainerTitle.find('span').html('待确认故障10项'); dialog.$dialogTitle = $dialogContainerTitle.find('span>strong'); var $minimize = $(''); $minimize.click(function (e) { e.stopPropagation(); var str = $minimize.text(); if (str === '—') { $dialogContainerTitle.siblings().css('display', 'none'); $minimize.text('+'); $dialogContainer.css({ top: dialogTop + dialogHeight - dialogTitleHeight, height: 'auto' }); } else { $dialogContainer.css({ top: dialogTop, height: dialogHeight }); $dialogContainerTitle.siblings().css('display', ''); $minimize.text('—'); } }); $dialogContainerTitle.find('.dialog-title-controls').html($minimize); setTimeout(function () { $dialogContainer.css('opacity', 0.3); $dialogContainer.off('mouseenter').on('mouseenter', function (e) { e.stopPropagation(); $dialogContainer.css('opacity', 1); }).off('mouseleave').on('mouseleave', function (e) { e.stopPropagation(); $dialogContainer.css('opacity', 0.3); }); }, 3000); if (twinkle) { setInterval(function () { // var bkc = twinkleFlag ? 'rgb(249, 37, 38)' : 'rgb(12, 77, 85)'; var bkc = twinkleFlag ? tablestyle.paneTitleChangeBackColor : tablestyle.paneTitleBackColor; $dialogContainerTitle.css('backgroundColor', bkc); $dialogContainer.css('backgroundColor', bkc); twinkleFlag = !twinkleFlag; }, 1000); } return dialog; } function createDialogAlarm(alarmInfoDialog, config, twinkle, tablestyle, sysname) { var dialog; if (typeof (alarmInfoDialog) == "undefined") { dialog = new ht.widget.Dialog(); } else { dialog = alarmInfoDialog } dialog.setConfig(config); var $dialog = $(dialog.getView()); var $dialogContainer = $dialog.find('.dialog-container'); var $dialogContainerTitle = $dialogContainer.find('.dialog-container-title'); var twinkleFlag = false; var dialogHeight = $dialogContainer.height(); var dialogTop = parseInt($dialogContainer.css('top')); var dialogTitleHeight = $dialogContainerTitle.height() || 28; var ensureBtnWidth = parseInt(tablestyle.paneBtnWidth) || 50, ensureBtnHeight = parseInt(tablestyle.paneBtnHeight) || 26; var $dialogBtns = $dialogContainer.find('.dialog-container-buttons'); $dialogBtns.css('padding-bottom', '10px'); $dialogBtns.css('padding-right', ensureBtnWidth / 2 + 'px'); var $btn = $dialogBtns.find('.dialog-button'); var $content = $('
    '); $content.css({ position: 'absolute', width: ensureBtnWidth, height: ensureBtnHeight, lineHeight: ensureBtnHeight + 'px', backgroundColor: tablestyle.paneBtnBackColor, textAlign: 'center', fontSize: tablestyle.paneBtnFontSize + 'px', color: tablestyle.paneBtnFontColor, fontFamily: tablestyle.paneBtnFontFamily, cursor: 'pointer' }) $content.text('确 认'); $btn.prepend($content).find('canvas').css({ visibility: 'hidden' }); $dialogContainer.css({ 'zIndex': 99, 'top': '', 'left': '', 'right': '5px', 'bottom': '28px' }); // $dialogContainerTitle.find('span').html('待确认故障10项'); $dialogContainerTitle.find('span').html(sysname); $dialogContainerTitle.find('span').css('color', tablestyle.paneTitleFontColor); $dialogContainerTitle.find('span').css('font', tablestyle.paneTitleFontSize + 'px ' + tablestyle.paneTitleFontFamily); dialog.$dialogTitle = $dialogContainerTitle.find('span>strong'); var $minimize = $(''); $minimize.click(function (e) { e.stopPropagation(); var str = $minimize.text(); if (str === '—') { $dialogContainerTitle.siblings().css('display', 'none'); $minimize.text('+'); $dialogContainer.css({ top: dialogTop + dialogHeight - dialogTitleHeight, height: 'auto' }); } else { $dialogContainer.css({ top: dialogTop, height: dialogHeight }); $dialogContainerTitle.siblings().css('display', ''); $minimize.text('—'); } }); $dialogContainerTitle.find('.dialog-title-controls').html($minimize); setTimeout(function () { $dialogContainer.css('opacity', 0.78); $dialogContainer.off('mouseenter').on('mouseenter', function (e) { e.stopPropagation(); $dialogContainer.css('opacity', 1); }).off('mouseleave').on('mouseleave', function (e) { e.stopPropagation(); $dialogContainer.css('opacity', 0.78); }); }, 3000); if (twinkle) { setInterval(function () { var bkc = twinkleFlag ? tablestyle.paneTitleChangeBackColor : tablestyle.paneTitleBackColor; $dialogContainerTitle.css('backgroundColor', bkc); $dialogContainer.css('backgroundColor', bkc); twinkleFlag = !twinkleFlag; }, 1000); } return dialog; } function loadScript(url, callback) { callback = callback || function () { }; var script = document.createElement("script") script.type = "text/javascript"; if (script.readyState) { //IE script.onreadystatechange = function () { if (script.readyState == "loaded" || script.readyState == "complete") { script.onreadystatechange = null; callback(); } }; } else { //Others script.onload = function () { callback(); }; script.onerror = function (e) { GD.createErrorDialog(420, 160, '页面不存在或路径设置有误,请查正后重新发布!'); } } script.src = url; document.body.appendChild(script); } // var relies = [PAGEROOTDIR + 'script/a.js', PAGEROOTDIR + 'script/a1.js']; function loadScripts(urls, callback) { callback = callback || function () { }; var loader = function (src, handler) { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = src; script.onload = function () { script.onload = null; script.onerror = null; handler(); }; script.onerror = function () { script.onload = null; script.onerror = null; callback({ message: src + '依赖未加载成功!' }); }; var head = document.getElementsByTagName('head')[0]; (head || document.body).appendChild(script); }; (function run() { if (urls.length > 0) { loader(urls.shift(), run); } else { callback(); } })(); } function clearDataModel (data) { // 清理echarts图表 if (data.getHtml && typeof data.getHtml === 'function') { var htmlData = data.getHtml(), op; if (htmlData._chart && typeof htmlData._chart.setOption === 'function') { htmlData._chart.setOption({}, true); htmlData._chart.clear && htmlData._chart.clear(); htmlData._chart = null; } if (typeof htmlData.getDataModel === 'function') { var dm = htmlData.getDataModel(); dm.each(clearDataModel); dm.clear(); } } if (data.setHtml && typeof data.setHtml === 'function') { data.setHtml(document.createElement('div')); } // 清理图元 if (data.__parent) { data.__parent.childNodes && (data.__parent.childNodes.length = 0); data.__parentLib = null; data.__parent = null; } data.localDynamicVar = null; if(data.hasOwnProperty("setImage")){data.setImage(null)};  data._attrObj = null; data.setWidth = null; data.setHeight = null; data.refresh && (data.refresh = null); data.refreshText && (data.refreshText = null); data.setOption && (data.setOption = null); data._initSize && (data._initSize = null); } function destoryScript() { // 清理interval定时器 for (var i = 0, len = intervalTimers.length; i < len; i++) { clearInterval(intervalTimers[i]); } intervalTimers.length = 0; // 删除body内的script标签 $(document.body).find('script').remove(); // 清除dataModel // window.dataModel && window.dataModel.clear(); if (window.dataModel) { dataModel.each(clearDataModel) dataModel.clear(); } // 清除图元model window._libModel && window._libModel.clear(); // 清除自定义事件 $window.off('graphViewZoomEnded'); window.onkeydown = null; // 清除缓存数据 alarmColorData = {}; // 删除添加的图片 deleteCustomImage(); // 删除DOM绑定的事件 (function () { var ctm, globalVarName, eventNameList = ['handleScroll', 'adjustTranslateY', 'adjustTranslateX', ''] if (typeof graphView !== 'undefined') { graphView._focusData = null; graphView._lastHoverData = null; graphView._pageBackgroundNode = null; if (graphView.graphViewList) { graphView.graphViewList.length = 0; } } if (window.view) { if (view.eventList && !GD.isEmptyObj(view.eventList)) { view.eventList = {}; view.onkeydown = null; } $(view).remove(); view._ht = null; view = null; } while (window.contextMenuOnViewList && (ctm = contextMenuOnViewList.shift())) { if (ctm instanceof ht.widget.ContextMenu) { ctm.afterShow = null; ctm.beforeShow = null; ctm.dispose(); ctm = null; } } if (window.globalVarNameList) { while (globalVarName = globalVarNameList.shift()) { if (!window[globalVarName]) continue; if (typeof window[globalVarName].getView === 'function') { var $view = $(window[globalVarName].getView()); // $view.off('') $view.remove(); } window[globalVarName] = null; } } window.GD && (GD.GetTagsProperty = null); })(); window.zoomNodeList && (window.zoomNodeList.length = 0); // 清除socketio中绑定的事件 // for (var key in socket._callbackDic) { // if (socket._callbackDic.hasOwnProperty(key)) { // socket._callbackDic[key] = null; // } // } // 清除body内容 $('a.btn').off('mouseup, mousedown').remove(); $('div.ht-widget-contextmenu').remove(); $('div.tooltip').remove(); $('div.main').remove(); $('span[gcuielement="gcStringWidthSpan"]').remove(); } function loadPage(hash) { hash = hash || location.hash; hash = decodeURIComponent(hash); hash = hash.match(/^#/) ? hash.substr(1) : hash; hash = hash.replace(/\\/g, '/'); // for (var i = 0, len = intervalTimers.length; i < len; i++) { // clearInterval(intervalTimers[i]); // } if (!hash) return location.reload(); var flag = 0; if (!GD.isLogin() && !GD.isFreeVisitPage(hash) && isAuthEnable !== "False") { GD.createErrorDialog(300, 160, '您还没有登录!页面将在3秒后自动跳转到登录页面!'); setTimeout(function () { dialogTip.dialog && dialogTip.dialog.hide(); var page = GD.getFreeVisitPage(); if (!page) { GD.createErrorDialog(300, 160, '请先配置登录页面!'); return; } location.hash = page; }, 3000) return; } loadScript(PAGEROOTDIR + hash + '.js', function () { var relies = GD && GD.relationship && GD.relationship[hash] || []; for (var timer; timer = intervalTimers.pop();) { clearInterval(timer); } // relies.push(hash + '.js'); for (var i = 0, len = relies.length; i < len; i++) { relies[i] = PAGEROOTDIR + relies[i]; } // destoryScript(); loadScripts(relies, function cb (err) { if (err) { destoryScript(); return console.log(err.message); } if (typeof window.init === 'function') { var t = setTimeout(function () { destoryScript(); init(); clearTimeout(t); }, 0) } }) }) var hashArr = hash.split('/'); document.title = hashArr[hashArr.length - 1]; } function deleteCustomImage() { var imageMap = ht.Default.getImageMap(); for (var key in imageMap) { if (key && imageMap.hasOwnProperty(key) && key.substr(0, 6) === 'image_') { imageMap[key] = null; } } } ////--------------------获取报警区域------------------------- // function getAlarmAreas() { // var reqData = { // "method": "GetAreas", // "param": {} // }; // var eventName = "/alarm/doservice"; // if (socket != null && socket != "") { // socket.post(eventName, reqData, function (data) { // if (data.success) { // var DataType = data.data.data; // for (var i = 0; i < DataType.length; i++) { // alarmAreaDicName[DataType[i].area_name] = DataType[i]; // alarmAreasDic[DataType[i].id] = DataType[i].area_name; // } // } // }); // } // } // hack onpushstate ; (function (window, history) { var pushState = history.pushState; history.pushState = function () { if (typeof window.onpushstate === 'function') { window.onpushstate.apply(history, arguments); } return pushState.apply(history, arguments); } })(window, window.history); window.onload = function () { if (document.hasOwnProperty("ontouchstart")) { istouched = true; } if (location.hash) { return loadPage(); } if (PAGENAME) location.hash = PAGENAME; return; } window.onhashchange = function (e) { _exchangeCount++; if (_exchangeCount > 100) { _exchangeCount = 0; return this.location.reload(); } loadPage(); } // libModel class var LibModel = function () { this.libModelMap = {}; this.libModelArray = []; } LibModel.prototype = { add: function (key, value) { if (value._baseClass && value._baseClass.match('ht.lib.')) { this.libModelMap[key] = value; this.libModelArray.push(value); } return this; }, clear: function () { for (var i = 0, len = this.libModelArray.length; i < len; i++) { this.libModelArray[i] = null; } for (var key in this.libModelMap) { if (this.libModelMap.hasOwnProperty(key)) { this.libModelMap[key] = null; } } this.libModelArray = []; this.libModelMap = {}; }, getDataByKey: function (key) { return this.libModelMap[key]; }, each: function (func) { if (typeof func === 'function') { for (var i = 0, len = this.libModelArray.length; i < len; i++) { func(this.libModelArray[i], i); } } }, remove: function (data) { for (var key in this.libModelMap) { if (this.libModelMap.hasOwnProperty(key) && this.libModelMap[key] === data) { this.libModelMap[key] = null; } } if (this.libModelArray.indexOf(data) != -1) { this.libModelArray.splice(this.libModelArray.indexOf(data), 1); } }, // 页面缩放后有问题,待完善 getDataAt: function (e) { var x = e.x, y = e.y; var result; this.each(function (data) { var w = data.getWidth(), h = data.getHeight(), p = data.getPosition(); px = p.x, py = p.y, w2 = w * 0.5, h2 = h * 0.5; if ((px - w2) < x && (px + w2) > x && (py + h2) > y && (py - h2) < y) { result = data; } }); return result; } } var _libModel = new LibModel(); function resetPageToDefaultSizeAndPosition(gv) { gv = gv || window.graphView; if (!gv) { return; } gv.setZoom(1); gv.tx(0); gv.ty(0); if (!(gv.tx() === 0 || gv.ty() === 0 || gv.getZoom() === 1)) { setTimeout(function () { resetPageToDefaultSizeAndPosition(gv); }, 100) } } // localstorage 保存 页面参数 ; (function (W, storage) { var pageParamsName = 'pageParams'; // 保存参数到localstorage function setParams(params, paramsName) { var errFlag = false; paramsName = paramsName || pageParamsName; if (!params) { storage.setItem(paramsName, '{}'); return; } if (typeof params === 'string') { storage.setItem(paramsName, params); return; } if (typeof params === 'object') { try { params = JSON.stringify(params); } catch (error) { console.log(error.message); storage.setItem(paramsName, '{}'); errFlag = true; } if (errFlag) return; storage.setItem(paramsName, params); return; } console.log('页面传递的参数不合法!'); storage.setItem(paramsName, '{}'); } function getParams(paramsName) { paramsName = paramsName || pageParamsName; var params = storage.getItem(paramsName), errFlag = false; try { params = JSON.parse(params); } catch (error) { console.log(error.message); errFlag = true; } if (errFlag) { return {}; } return params; } // 将传递的参数赋值给页面上的变量 function useParams(paramsName) { paramsName = paramsName || pageParamsName; var params = getParams(paramsName); for (var key in params) { if (params.hasOwnProperty(key)) { if (!(window[key] === undefined)) { window[key] = params[key]; } } } removeParams(paramsName); } // 删除参数 function removeParams(paramsName) { paramsName = paramsName || pageParamsName; storage.removeItem(paramsName); } // 判断用户是否已经登录 function isLogin() { var t = localStorage.getItem('token'); if (t && t.length > 100) { return true; } return false; } // 判断页面是否可访问 function isFreeVisitPage(page) { page = page || location.hash.substr(1); page = decodeURIComponent(page); if (window.__FVPAGE && __FVPAGE[0] === page) { return true; } return false; } // 获取不登录时可打开的页面 function getFreeVisitPage() { if (window.__FVPAGE) { return __FVPAGE[0]; } return ''; } W.GD = W.GD || {}; GD.setParams = setParams; GD.isLogin = isLogin; GD.getFreeVisitPage = getFreeVisitPage; GD.isFreeVisitPage = isFreeVisitPage; GD.getParams = getParams; GD.useParams = useParams; GD.removeParams = removeParams; })(window, localStorage); // 保存页面要传递的参数 function saveLocalParams(paramsObj) { if (typeof paramsObj !== 'object') { return; } GD.setParams(paramsObj); } ; (function (W) { //页面显示相关 var GD = W.GD || {}; // 根据旋转角度计算缩放比例 function getRatioWithRotation(rotation, ratio) { var abs = Math.abs, cos = Math.cos, sin = Math.sin; var ratioX, ratioY; var args = Array.prototype.slice.call(arguments, 0); if (args.length === 2) { if (!ratio) { return { ratioX: 1, ratioY: 1 } } ratioX = ratio.ratioX; ratioY = ratio.ratioY; } else if (args.length >= 3) { ratioX = args[1]; ratioY = args[2]; } if (rotation === 0 || !ratioX || !ratioY) { return { ratioX: ratioX, ratioY: ratioY } } if (rotation < 0) { rotation = rotation % (2 * Math.PI) + 2 * Math.PI; } var ro = rotation % Math.PI; if (ro < Math.PI * 0.25) { rotation = 0; } else if (ro <= Math.PI * 0.75) { rotation = 90 * Math.PI / 180; } else { rotation = Math.PI; } var _ratioX, _ratioY; _ratioX = abs(cos(rotation) * ratioX - sin(rotation) * ratioY); _ratioY = abs(sin(rotation) * ratioX + cos(rotation) * ratioY); return { ratioX: _ratioX, ratioY: _ratioY } } // 组旋转 function groupRotat(bound, node, angle, ratio) { if (!angle || !bound || !node) { return; } ratio = ratio || { ratioX: 1, ratioY: 1 }; if (node.scalable === false) { // 如果图元没有缩放就直接旋转 SetRotatPositionRelative(node, bound, angle); node.setRotation(angle + node.getRotation()); return; } // 还原大小,位置 var boundWidth = bound.getWidth(), boundHeight = bound.getHeight(), boundPosition = bound.getPosition(), boundRotation = typeof bound.getRotation === 'function' ? bound.getRotation() : 0, boundRatio = getRatioWithRotation(boundRotation, ratio); var nodeWidth = node.getWidth(), nodeHeight = node.getHeight(), nodePosition = node.getPosition(), nodeRotation = typeof node.getRotation === 'function' ? node.getRotation() : 0, nodeRatio = getRatioWithRotation(nodeRotation, ratio); if (node._zoomBy === 'False') { nodeRatio.ratioX = 1; nodeRatio.ratioY = 1; } else if (node._zoomBy === 'X') { nodeRatio.ratioY = nodeRatio.ratioX; } else if (node._zoomBy === 'Y') { nodeRatio.ratioX = nodeRatio.ratioY; } bound.setWidth(boundWidth / boundRatio.ratioX); bound.setHeight(boundHeight / boundRatio.ratioY); bound.setPosition(boundPosition.x / ratio.ratioX, boundPosition.y / ratio.ratioY); node.setWidth(nodeWidth / nodeRatio.ratioX); node.setHeight(nodeHeight / nodeRatio.ratioY); node.setPosition(nodePosition.x / ratio.ratioX, nodePosition.y / ratio.ratioY); // 旋转 SetRotatPositionRelative(node, bound, angle); if (node._baseClass && node._baseClass.match('^ht.lib')) { node.setRotation(angle + nodeRotation, { x: node.getPosition().x - bound.getPosition().x, y: node.getPosition().y - bound.getPosition().y }); } else { node.setRotation(angle + nodeRotation); } // 缩放 var _ratio = GD.getRatioWithRotation(angle + nodeRotation, ratio); if (node._zoomBy === 'False') { _ratio.ratioX = 1; _ratio.ratioY = 1; } else if (node._zoomBy === 'X') { _ratio.ratioY = _ratio.ratioX; } else if (node._zoomBy === 'Y') { _ratio.ratioX = _ratio.ratioY; } bound.setWidth(bound.getWidth() * boundRatio.ratioX); bound.setHeight(bound.getHeight() * boundRatio.ratioY); bound.setPosition(bound.getPosition().x * ratio.ratioX, bound.getPosition().y * ratio.ratioY); node.setWidth(node.getWidth() * _ratio.ratioX); node.setHeight(node.getHeight() * _ratio.ratioY); node.setPosition(node.getPosition().x * ratio.ratioX, node.getPosition().y * ratio.ratioY); } // 计算旋转角度 function calcRotation(rotation) { if (rotation < 0) { rotation = rotation % (2 * Math.PI) + 2 * Math.PI; } var ro = rotation % Math.PI; if (ro < Math.PI * 0.25) { rotation = 0; } else if (ro <= Math.PI * 0.75) { rotation = 90 * Math.PI / 180; } else { rotation = Math.PI; } return rotation; } function showTagInfo(tagsInfoDic, tagName, mouseX, mouseY) { hideTagInfo(); if ($('div.tooltip div.tooltop').length > 0) { return ; } // if (tagName.match(/{/)) { // tagName = tagName.replace(/{/g, '').replace(/}/g, ''); // tagName = window[tagName] || ''; // } var _tagName = tagName && tagName.toLowerCase && tagName.toLowerCase(); var $div = $('
    '), clientWidth = $window.width(), clientHeight = $window.height(); var tagInfo = tagsInfoDic[_tagName] || tagsInfoDic[tagName]; if (!tagInfo) return; var x, y, width = 300, height = 350; x = (mouseX + width) >= (clientWidth - 10) ? mouseX - width : mouseX + 8; y = (mouseY + height) >= (clientHeight - 10) ? mouseY - height : mouseY + 8; $div.css({ minWidth: 100, minHeight: 100, maxWidth: width, maxHeight: height, top: y, left: x, position: 'absolute', zIndex: 99 }); var desc = tagInfo.Desc, lowLimit = tagInfo.LowLimit, highLimit = tagInfo.HighLimit, unit = tagInfo.Unit; var titleStr = '
  • 标签名称:' + tagName + '
  • ', descStr = '
  • 描述:' + desc + '
  • ', lowLimitStr = '
  • 量程上限:' + lowLimit + '
  • ', highLimitStr = '
  • 量程下限:' + highLimit + '
  • ', unitStr = '
  • 单位:' + unit + '
  • ', snapshort = '
  • 快照值:' + getVarValue(_tagName) + '
  • ', snapShotTimeStr = '
  • 快照时间:' + moment(VarSnapshotTime[_tagName]).format("YYYY/MM/DD HH:mm:ss") + '
  • '; var htmlStr = '
      ' + titleStr + descStr + unitStr + snapshort + snapShotTimeStr + '
    ' $div.html(htmlStr); $(document.body).append($div); var $width = $div.outerWidth(), $height = $div.outerHeight(); x = (mouseX + $width) >= (clientWidth - 10) ? mouseX - $width - 8 : mouseX + 8; y = (mouseY + $height) >= (clientHeight - 10) ? mouseY - $height - 8 : mouseY + 8; $div.css({ top: y, left: x }) var $snapshot = $div.find('.snapshot'), $snapshottime = $div.find('.snapshottime'); showTagInfo.timer && clearInterval(showTagInfo.timer); showTagInfo.timer = setInterval(function () { $snapshot.text(getVarValue(_tagName)); $snapshottime.text(moment(VarSnapshotTime[_tagName]).format("YYYY/MM/DD HH:mm:ss")); }, 1000); } function hideTagInfo() { $('div.tag-info').remove(); showTagInfo.timer && clearInterval(showTagInfo.timer); } function resetNodeBorderWidth(nodeList, value) { var node, n, w, attr, fw, wv; nodeList = nodeList || zoomNodeList; for (var i = 0, len = nodeList.length; i < len; i++) { node = nodeList[i]; n = node.node; w = n.borderWidth; fw = n.borderFillwidth || 0; attr = node.attr; wv = w * value; if (n.a && (typeof n.a === 'function')) { if (n.a('node.isFill') === 'true' || n.a('node.isFill') === true) { n.borderFillwidth = wv; } else { n.a(attr, wv); n._nodeType === 'roundrect' ? n._borderWidth = wv : ''; } } } } function setPageSizeWithRatio(value, ratio, backSize) { var ox, oy, rx, ry, browserWidth, browserHeight, ps; if (!value) return; ratio = ratio || window.ratio || {}; backSize = backSize || window.backSize || {} // 还原 ox = 1 / ratio.ratioX; oy = 1 / ratio.ratioY; browserWidth = $window.innerWidth(); browserHeight = $window.innerHeight(); if (value === 'adaptWidth') { // 适应宽度 ry = rx = browserWidth / backSize.width; } else if (value === 'adaptHeight') { // 适应高度 rx = ry = browserHeight / backSize.height; } else if (value === 'adaptBrowser') { // 适应浏览器窗口 rx = browserWidth / backSize.width; ry = browserHeight / backSize.height; } else if (value === 'originSize') { // 原始大小 rx = 1; ry = 1; } else if ($.isNumeric(value)) { // 数字 rx = ry = value; } else if (value === 'autoResize') { browserWidth = browserWidth < PageAdaptMode.minWidth ? PageAdaptMode.minWidth : browserWidth; browserHeight = browserHeight < PageAdaptMode.minHeight ? PageAdaptMode.minHeight : browserHeight; rx = browserWidth / backSize.width; ry = browserHeight / backSize.height; if (rx > ry) { rx = ry; } else { ry = rx; } } if ($.isNumeric(value)) { ratio.ratioX = ratio.originRatioX * value; ratio.ratioY = ratio.originRatioY * value; GD.resizePage(ratio.ratioX*ox, ratio.ratioY*oy); } else { ratio.ratioX = rx; ratio.ratioY = ry; ratio.originRatioX = rx; ratio.originRatioY = ry; GD.resizePage(ox * rx, oy * ry); } setPageToCenterOrLeftTop(); autoToggleScrollBar(); setTimeout(function () { graphView.tx(0); graphView.ty(0); graphView.redraw(); }, 0) GD.setParams({ value: value }, 'pageSizeRatioValue') } function autoToggleScrollBar() { var browserWidth = $window.innerWidth(), browserHeight = $window.innerHeight(); graphView.setScrollBarVisible(false); // 页面宽度大于浏览器窗口宽度时显示滚动条,并且允许页面横向拖动,小于时禁止,页面可用鼠标缩放时页面仍可拖动 if (backSize.width * ratio.ratioX > browserWidth + 1) { graphView.setScrollBarVisible(true); graphView.adjustTranslateX = function (value) { var offsetX = browserWidth - backSize.width * ratio.ratioX; (value > 0) && (value = 0); (value < offsetX && offsetX < 0) && (value = offsetX); return value }; } else { !window.PAGESCALABLE && (graphView.adjustTranslateX = function () { return 0 }); } // 页面高度大于浏览器窗口高度时显示滚动条,并且允许页面纵向拖动,小于时禁止,页面可用鼠标缩放时页面仍可拖动 if (backSize.height * ratio.ratioY > browserHeight + 1) { graphView.setScrollBarVisible(true); graphView.adjustTranslateY = function (value) { var offsetY = browserHeight - backSize.height * ratio.ratioY; (value > 0) && (value = 0); (value < offsetY && offsetY < 0) && (value = offsetY); return value }; } else { !window.PAGESCALABLE && (graphView.adjustTranslateY = function () { return 0 }); } // 如果允许页面可用鼠标拖动,页面可用鼠标缩放时页面仍可拖动 if (graphView.isScrollBarVisible()) { graphView.setPannable(true); graphView.setMovableFunc(function (data) { return true }); } else { if (!window.PAGESCALABLE) { graphView.setPannable(false); graphView.setMovableFunc(function (data) { return false }); } } } function setPageToCenterOrLeftTop() { // position 默认为‘center’, 如果为leftTop,则移到到左上角 var browserHeight = $window.innerHeight(), browserWidth = $window.innerWidth(), offsetX, offsetY, cx,cy,backSize = getBackSize(); var pageBackground = graphView && graphView._pageBackgroundNode, bp; if (!pageBackground) return; if (backSize.width < browserWidth - 2) { cx = browserWidth * 0.5; } else { cx = pageBackground.getWidth() * 0.5; } if (backSize.height < browserHeight -2) { cy = browserHeight * 0.5; } else { cy = pageBackground.getHeight() * 0.5; } bp = pageBackground.getPosition(); offsetX = cx - bp.x; offsetY = cy - bp.y; window.dataModel && dataModel.each(function (data) { if (!(data.__parentLib && data.__parentLib.match(/^ht.lib/) || data.__blockChild)) { var p = data.getPosition(); data.setPosition(p.x + offsetX, p.y + offsetY); } }); window._libModel && _libModel.each(function (data) { var p = data.getPosition(); data.setPosition(p.x + offsetX, p.y + offsetY); }) } function resizePage(ratioX, ratioY) { var windowHeight = window.innerHeight, windowWidth = window.innerWidth; ratioX = ratioX || windowWidth / browserSize.width, ratioY = ratioY || windowHeight / browserSize.height; browserSize.width = windowWidth; browserSize.height = windowHeight; $window.trigger('beforeResize'); resizeAllNodes(dataModel, ratioX, ratioY); var graphViewList = graphView && graphView.graphViewList || []; for (var i = 0, len = graphViewList.length; i < len; i++) { resizeAllNodes(graphViewList[i].getDataModel(), ratioX, ratioY); } showPage(); $window.trigger('resizeOver'); } // 线段中箭头使用,返回的角度为线段终点的角度。 function calcRotationByStartAndEnd(startPoint, endPoint) { var args = Array.prototype.slice.call(arguments, 0), atan = Math.atan, sx, sy, ex, ey, x, y; if (!args.length) return 0; if (args.length === 2 && args[0] && args[0].length && args[1] && args[1].length) { sx = args[0][0]; sy = args[0][1]; ex = args[1][0]; ey = args[1][1]; } else if (args.length === 4) { sx = args[0]; sy = args[1]; ex = args[2]; ey = args[3]; } else { return 0; } x = ex - sx; y = ey - sy; if (x === 0 && y > 0) { return Math.PI; } if (x === 0 && y < 0) { return 0; } if (x > 0 && y === 0) { return Math.PI * 0.5; } if (x < 0 && y === 0) { return -Math.PI * 0.5; } if (x > 0 && y > 0) { return Math.PI - atan(x / y); } if (x > 0 && y < 0) { return atan(x / (-y)); } if (x < 0 && y < 0) { return -1 * (atan(x / y)); } if (x < 0 && y > 0) { return atan((-x) / (y)) - Math.PI; } } function createAlarmSoundConfigDialog(width, height, x, y, angle, styleOption) { styleOption = styleOption || {}; var comboboxValues = styleOption.comboboxValues || [], comboboxValue = styleOption.comboboxValue || '', comboboxBorderColor = styleOption.comboboxBorderColor || 'black', comboboxFontColor = styleOption.comboboxFontColor || 'black', comboboxBackgroundColor = styleOption.comboboxBackgroundColor || 'white', comboboxSelectBackgroundColor = styleOption.comboboxSelectBackgroundColor || 'gray', comboboxIconColor = styleOption.comboboxIconColor || 'gray', labelColor = styleOption.labelColor || 'black', labelFontSize = styleOption.labelFontSize || 10, labelFontFamily = styleOption.labelFontFamily || 'Microsoft Yahei', inputBorderColor = styleOption.inputBorderColor || 'black', inputBackgroundColor = styleOption.inputBackgroundColor || 'rgba(0,0,0,0)', inputFontColor = styleOption.inputFontColor || 'black', buttonLabelColor = styleOption.buttonLabelColor || 'black', buttonBackgroundColor = styleOption.buttonBackgroundColor || 'rgba(0,0,0,0)', buttonSelectBackgroundColor = styleOption.buttonSelectBackgroundColor || 'rgba(0,0,0,0)', paneBackgroundColor = styleOption.paneBackgroundColor || 'rgba(0,0,0,0)'; var fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.style.display = 'none'; fileInput.accept = '.mp3, .wav, .ogg'; document.body.appendChild(fileInput); var borderPane = new ht.widget.BorderPane(); var formPane = new ht.widget.FormPane(); var combobox = new ht.widget.ComboBox(); combobox.setValues(comboboxValues); combobox.setValue(comboboxValue); var soundinput = new ht.widget.TextField(); var formatinput = new ht.widget.TextField(); var displayInfoInput = new ht.widget.TextField(); var playTimeDisplayInfoInput = new ht.widget.TextField(); var playtimeinput = new ht.widget.TextField(); var uploadbtn = new ht.widget.Button(); var changesoundbtn = new ht.widget.Button(); var changeplaytimebtn = new ht.widget.Button(); var $soundText = $('声音:'); var $formatLabel = $('支持格式: mp3,wav或其它支持的格式'); var $playTimeLabel = $('播放时长:'); var $playTimeUnitLabel = $('S/次'); var alarmLevelList = []; uploadbtn.setLabel('上传'); changesoundbtn.setLabel('删除'); changeplaytimebtn.setLabel('保存'); function setButtonStyle(button, clickFunc) { var $mask = $('
    '); var buttonView = button.getView(); buttonView.className = 'uploadbutton'; button.setWidth(80); button.setBackground('rgba(0,0,0,0)'); button.setSelectBackground('rgba(0,0,0,0)'); button.setLabelColor(buttonLabelColor); button.setLabelSelectColor(buttonLabelColor); button.setBorderColor('rgba(0,0,0,0)'); $(buttonView).css({ overflow: 'hidden', cursor: 'pointer', backgroundColor: buttonBackgroundColor }).off('click').on('click', function () { clickFunc = clickFunc || function () { }; clickFunc(); }).off('mousedown').on('mousedown', function () { $(this).css({ backgroundColor: buttonSelectBackgroundColor }) }).off('mouseup').on('mouseup', function () { $(this).css({ backgroundColor: buttonBackgroundColor }) }).hover(function () { $(this).prepend($mask) .css({ borderBottom: '1px solid ' + buttonLabelColor }); }, function () { $mask.remove(); $(this).css({ border: 'none' }) }); } function setComboboxStyle(combobox) { var $comboboxView = $(combobox.getView()), dropDownIcon = combobox.getDropDownIcon(); dropDownIcon.comps[0].borderColor = comboboxIconColor; combobox.setDropDownIcon(dropDownIcon); $comboboxView.css({ borderColor: comboboxBorderColor }); combobox.setBackground(comboboxBackgroundColor); combobox.setLabelColor(comboboxFontColor); combobox.setSelectBackground(comboboxSelectBackgroundColor); } function setTextFieldStyle(textField) { var $textFieldView = $(textField.getElement()); textField.setBackground(inputBackgroundColor); $textFieldView.css({ 'border': 'none', color: inputFontColor, borderBottom: '1px solid ' + inputBorderColor }) if (playtimeinput === textField) { $textFieldView.css({ textAlign: 'center' }) } if (displayInfoInput === textField || playTimeDisplayInfoInput === textField) { $textFieldView.css({ border: 'none' }) } // textField.setLabelColor('rgba(255, 0,0,1)'); } function setLabelStyle($label) { $label.css({ color: labelColor, fontSize: labelFontSize, fontFamily: labelFontFamily, fontWeight: 400 }) } function getSoundFileList(callback) { callback = callback || function () { }; socket.alarmPost('/alarm/GetFilesList', {}, function (data) { var result; if (data.success) { result = data.data && data.data.data || []; if (!result.length) { displayInfoInput.setValue('您还没有上传过声音文件,请先上传!'); // clearDisplayInfo(3); } else { combobox.setValues(result); combobox.setValue(result[0]); } } else { } callback(data.success); }); } function getAlarmLevel(callback) { callback = callback || function () { }; var reqData = { "method": "GetLevels", "param": {} }; // var flagnum = getFlag(); var flagnum = "level"; var eventName = "/alarm/doservice?" + flagnum;; socket.alarmPost(eventName, reqData, callback); } function setAlarmLevels(alarmLevels, callback) { var len = alarmLevels.length, count = 0, alarmLevel, reqData = { "method": "UpdateLevel" } callback = callback || function () { }; for (var i = 0; i < len; i++) { alarmLevel = alarmLevels[i]; reqData.param = alarmLevel; socket.alarmPost('/alarm/doservice/?updatelevel', reqData, function (data) { if (data.success) { count++; if (count >= len) { callback(); } } }) } } function clearDisplayInfo(delay, infoinput) { setTimeout(function () { infoinput.setValue(''); }, delay * 1000) } function getalarmLevelList() { getAlarmLevel(function (data) { if (data.success) { alarmLevelList = data.data && data.data.data || []; if (alarmLevelList.length) { playtimeinput.setValue(alarmLevelList[0].duration); } else { displayInfoInput.setValue('请先配置报警级别!'); } } else { alarmLevelList = []; } }); } getSoundFileList(); getalarmLevelList(); formPane.addRow([combobox, null], [0.85, 0.15]); formPane.addRow([displayInfoInput], [1]); formPane.addRow([$soundText[0], soundinput, null, uploadbtn, changesoundbtn], [50, 0.5, 0.1, 40, 40, 0.22]); formPane.addRow([null], [1]); formPane.addRow([$formatLabel[0], null, null, '', ''], [50, 0.5, 0.1, 0.05, 0.05, 0.22]); formPane.addRow([null], [1]); formPane.addRow([$playTimeLabel[0], playtimeinput, $playTimeUnitLabel[0], null, null], [60, 60, 0.1, 0.4, 40, 0.22]); formPane.addRow([playTimeDisplayInfoInput], [1]); formPane.addRow([null], [1]); formPane.addRow([null, changeplaytimebtn, null], [0.5, 40, 0.5]); function setStyle() { setButtonStyle(uploadbtn, function () { fileInput.click(); }); // 删除 setButtonStyle(changesoundbtn, function () { var fname = soundinput.getValue(); if (!fname) return; if (!confirm('您确定要删除这个声音文件吗?')) return; socket.alarmPost('/alarm/deletefile', { "name": fname }, function (data) { if (data.success && data.data && data.data.data) { displayInfoInput.setValue('删除文件成功!'); clearDisplayInfo(3, clearDisplayInfo); getSoundFileList(); } else { displayInfoInput.setValue('删除文件失败,请重试!'); clearDisplayInfo(3, clearDisplayInfo); } }) }); // 保存 setButtonStyle(changeplaytimebtn, function () { var duration = playtimeinput.getValue(), soundFileName = soundinput.getValue(), alarmLevel; if (!alarmLevelList.length) { playTimeDisplayInfoInput.setValue('请先设置完报警级别再配置报警声音!'); clearDisplayInfo(3, playTimeDisplayInfoInput); return; } if (!duration) { playTimeDisplayInfoInput.setValue('请设置播放时长!'); clearDisplayInfo(3, playTimeDisplayInfoInput); return; } if (!$.isNumeric(duration)) { playTimeDisplayInfoInput.setValue('播放时长只能设置为整数!'); clearDisplayInfo(3, playTimeDisplayInfoInput); return; } if (duration <= 0) { playTimeDisplayInfoInput.setValue('播放时长只能设置为大于0的整数!'); clearDisplayInfo(3, playTimeDisplayInfoInput); return; } if (!soundFileName) { playTimeDisplayInfoInput.setValue('请选择或上传报警声音!'); clearDisplayInfo(3, playTimeDisplayInfoInput); return; } for (var i = 0, len = alarmLevelList.length; i < len; i++) { alarmLevel = alarmLevelList[i]; alarmLevel.duration = duration - 0; alarmLevel['wave_file'] = soundFileName; for (var key in alarmLevel) { if (alarmLevel.hasOwnProperty(key)) { alarmLevel[key] = { value: alarmLevel[key] } } } } setAlarmLevels(alarmLevelList, function () { playTimeDisplayInfoInput.setValue('保存成功!'); clearDisplayInfo(3, playTimeDisplayInfoInput); getalarmLevelList(); }) }); setComboboxStyle(combobox); setTextFieldStyle(soundinput); soundinput.setEditable(false); setTextFieldStyle(displayInfoInput); displayInfoInput.setEditable(false); setTextFieldStyle(playTimeDisplayInfoInput); playTimeDisplayInfoInput.setEditable(false); setTextFieldStyle(formatinput); setTextFieldStyle(playtimeinput); setLabelStyle($soundText); setLabelStyle($formatLabel); setLabelStyle($playTimeLabel); setLabelStyle($playTimeUnitLabel); $(borderPane.getView()).css({ background: paneBackgroundColor }) combobox.onValueChanged = function () { soundinput.setValue(combobox.getValue()); } $(fileInput).off().on('change', function () { if (typeof FileReader !== 'function') { displayInfoInput.setValue('您使用的浏览器版本太低,请更换高版本的浏览器!'); clearDisplayInfo(3, displayInfoInput); return; } var f = fileInput.files && fileInput.files[0] || ''; var fname = f.name || '', size = f.size; var fileList = combobox.getValues(); if (!f) return; if (size > 1024 * 1024 * 2) { displayInfoInput.setValue('您选择的声音文件太大了,请更换声音文件!'); clearDisplayInfo(3, displayInfoInput); return; } if (fileList.indexOf(fname) !== -1) { if (!confirm("您选择的文件名在服务器已保存的文件名冲突,继续上传将会覆盖原有的文件,是否继续?")) { return; } } var reader = new FileReader(); reader.onload = function (e) { var result = this.result; // 发送给后端 socket.alarmPost('/alarm/UploadFile', { "data": result, "name": fname }, function (data) { var result; if (data.success) { result = data.data && data.data.data; if (result) { displayInfoInput.setValue('上传成功!'); clearDisplayInfo(3, displayInfoInput); getSoundFileList(function (success) { if (success) { combobox.setValue(fname); } }) } } else { displayInfoInput.setValue('上传是发生错误,请重新上传!'); clearDisplayInfo(3, displayInfoInput); } }, 20) } reader.readAsDataURL(f); }); } setStyle(); borderPane.setCenterView(formPane); var htmlNode = new ht.HtmlNode(); borderPane.setWidth(width); borderPane.setHeight(height); htmlNode.setHtml(borderPane); htmlNode.setPosition(x, y); htmlNode.setSize(width, height); htmlNode.setPadding(0); htmlNode.setScalable(false); htmlNode.s({ '2d.selectable': true, '2d.moveable': false }); htmlNode.setComboboxValues = function (values) { combobox.setValues(values); } htmlNode.setComboboxValue = function (value) { combobox.setValue(value); } dataModel.add(htmlNode); return htmlNode; } function getFullParams (params, node) { if (!node) { return params; } if (node.__parent && node.__parent.localVarObj) { $.extend(params, node.__parent.localVarObj); } if (node.__parent && typeof node.__parent.localDynamicVar === 'function') { $.extend(params, node.__parent.localDynamicVar()); } if (typeof node.localDynamicVar === 'function') { $.extend(params, node.localDynamicVar()); } return params; } function getBackSize () { var result = {}; var back = graphView._pageBackgroundNode, w = back.getWidth(), h = back.getHeight(); result.width = w; result.height = h; return result; } GD.getFullParams = getFullParams; GD.createAlarmSoundConfigDialog = createAlarmSoundConfigDialog; GD.resetNodeBorderWidth = resetNodeBorderWidth; GD.getRatioWithRotation = getRatioWithRotation; GD.groupRotat = groupRotat; GD.showTagInfo = showTagInfo; GD.hideTagInfo = hideTagInfo; GD.calcRotation = calcRotation; GD.setPageSizeWithRatio = setPageSizeWithRatio; GD.autoToggleScrollBar = autoToggleScrollBar; GD.setPageToCenterOrLeftTop = setPageToCenterOrLeftTop; GD.resizePage = resizePage; GD.calcRotationByStartAndEnd = calcRotationByStartAndEnd; W.GD = GD; })(window); // 页面控件 (function (W) { var GD = W.GD || {}; function createButton(w, h, x, y, angle, option) { var htmlNode = new ht.HtmlNode(), $btnView = $(''), text = option.text || 'Text', visible = !!option.visible, backColor = option.backColor || 'rgba(220,220,220,1)', fontSize = option.fontSize || 12, fontFamily = option.fontFamily || '"Microsoft YaHei"', fontColor = option.fontColor || 'rgba(255, 255, 255, 1)', textAlign = option.textAlign || 'center', btnBorderRadius = option.borderRaidus || '2px', btnBorderColor = option.borderColor || '#ccc', btnShadowColor = option.shadowColor || '#333', btnHoverShadowColor = option.hoverShadowColor || '#eee', bold = !!option.bold, italic = !!option.italic, underline = !!option.underline, deleteline = !!option.deleteline, icon = option.icon, backImage = option.backImage, clickFunc = option.clickFunc, labelFont = fontSize * ratio.ratioY + 'px ' + fontFamily, transparentColor = 'rgba(0,0,0,0)', $mask = $('
    '), _ratio = GD.getRatioWithRotation(angle, ratio); bold && (labelFont = 'bold ' + labelFont); italic && (labelFont = 'italic ' + labelFont); var setWidth = htmlNode.setWidth, setHeight = htmlNode.setHeight; var btn = new ht.widget.Button(), btnbg; btn.setLabel(text); btn.setBackground(transparentColor); btn.setSelectBackground(transparentColor); btn.setBorderColor(transparentColor); btn.setLabelFont(labelFont); btn.setLabelColor(fontColor); icon && btn.setIcon(PAGEROOTDIR + icon); $btnView = $(btn.getView()); if (backImage) { if (!backImage.match(/^http:|^https:/)) { backImage = PAGEROOTDIR + backImage; } $btnView.css({ backgroundImage: 'url('+ backImage +')', backgroundPosition: 'center center', backgroundRepeat: 'no-repeat', backgroundSize: '100% 100%' }) // btnbg = new ht.Node(); // btnbg.setWidth(w); // btnbg.setHeight(h); // btnbg.setPosition(x, y); // btnbg.setRotation(angle); // btnbg.setImage(backImage); // dataModel.add(btnbg); } else { $btnView.css({ background: backColor }) } htmlNode._$btnView = $btnView; htmlNode.setHtml(btn); htmlNode.setScalable(false); htmlNode.setPadding(0); htmlNode.setWidth(w); htmlNode.setHeight(h); htmlNode.setPosition(x, y); htmlNode.setRotation(angle); htmlNode._btn = btn; htmlNode.s({ '2d.selectable': false, '2d.movable': false, '2d.visible': visible }); htmlNode.setLabelColor = function (fc) { this._$btnView.css({ color: fc }); }; htmlNode.setLabel = function (label) { this._btn.setLabel(label); }; htmlNode.setLabelFont = function (lf) { this._btn.setLabelFont(lf); }; htmlNode.getLabelFont = function () { return this._btn.getLabelFont(); }; htmlNode.setBackground = function (bg) { this._$btnView.css({ backgroundColor: bg }) }; htmlNode.addEvent = function (eventname, func) { $btnView = htmlNode._$btnView; func = typeof func === 'function' ? func : function () { }; $btnView.on(eventname, function (e) { func.call(htmlNode, e); }); }; (function ($btnView, $mask, htmlNode, btnbg) { $btnView.css({ 'borderRadius': btnBorderRadius, 'overflow': 'hidden', 'padding': 0, 'margin': 0, 'textAlign': textAlign, cursor: 'pointer', borderColor: btnBorderColor, boxShadow: '0 0 5px ' + btnShadowColor, }).hover(function () { $btnView.append($mask).css({ boxShadow: '0 0 5px ' + btnHoverShadowColor }) }, function () { $mask.remove(); $btnView.css({ boxShadow: '0 0 5px ' + btnShadowColor }) }).on('mousedown', function () { $btnView.parent().css({ padding: '1px 0 0 1px' }) // if (btnbg) { // var p = btnbg.getPosition(); // btnbg.setPosition({ // x: p.x + 1, // y: p.y + 1 // }) // } }).on('mouseup', function () { $btnView.parent().css({ padding: 0 }); // if (btnbg) { // var p = btnbg.getPosition(); // btnbg.setPosition({ // x: p.x - 1, // y: p.y - 1 // }) // } }).find('canvas').css({ 'top': 0, 'left': 0, }); if (option.clickFunc) { htmlNode.addEvent('click', option.clickFunc); } var setHeight = htmlNode.setHeight; htmlNode.setHeight = function (height) { var labelFont = fontSize * ratio.ratioY + 'px ' + fontFamily; bold && (labelFont = 'bold ' + labelFont); italic && (labelFont = 'italic ' + labelFont); btn.setLabelFont(labelFont); setHeight.call(htmlNode, height); } })($btnView, $mask, htmlNode, btnbg); dataModel.add(htmlNode); return htmlNode; } function createMessageDialog(width, height, content, surefunc, canclefunc, borderColor, btns, title, x, y) { var messageDialog = createMessageDialog._messageDialog || new ht.widget.Dialog(); var content = '

    ' + content + '

    ', position; borderColor = borderColor || 'rgb(47, 131, 217)'; title = title || '提示'; btns = btns || [{ label: "确认", className: 'dialog-button-confirm' }, { label: "取消", className: 'dialog-button-cancel' }]; if (messageDialog.isShowing()) { messageDialog.hide(); } if (x && y) { position = {x: x, y: y}; } else { position = 'center'; } messageDialog.setConfig({ title: title, titleAlign: "left", closable: true, draggable: true, //maximizable: true, position: position, width: width, height: height, content: content, contentPadding: 20, buttons: btns, buttonsAlign: "center", action: function (item, e) { if (item.label == "确认" || item.label === '确定') { surefunc(); messageDialog.hide(); } else { canclefunc(); messageDialog.hide(); } } }); messageDialog.setModal(false); createMessageDialog._messageDialog = messageDialog; var $messageView = $(messageDialog.getView()); setDialogStyle($messageView, borderColor, width, height); messageDialog.show(); } function createErrorDialog(width, height, content, surefunc, canclefunc) { surefunc = surefunc || function () { }; canclefunc = canclefunc || function () { }; createMessageDialog(width, height, content, surefunc, canclefunc, 'rgb(207,145,38)', [{ label: '确定', className: 'dialog-button-confirm' }]) } function setDialogStyle($dialogView, borderColor, width, height) { $dialogView.css({ zIndex: 100 }).find('.dialog-container').css({ border: '5px solid ' + borderColor, padding: 0, borderRadius: 5, minWidth: width, minHeight: height, // overflow: 'hidden', boxShadow: '3px 3px 8px rgb(50,50,50)' }).find('.dialog-container-title').css({ backgroundColor: borderColor, height: 30, boxShadow: '0 2px 6px rgb(50,50,50)', left: -5, top: -5, width: width, position: 'absolute', padding: '0 20px 0 20px', borderRadius: 5, lineHeight: '30px' }).find('.dialog-title-control').css({ marginTop: 2 }).end().end().find('.dialog-container-buttons').css({ bottom: 5 }).find('.dialog-button-confirm').css({ background: borderColor, marginRight: 20 }); } function setupDatePicker(dateDiv, datePickerInstance) { var currentValue; var $dateDiv = $(dateDiv); $dateDiv.on('click', function (e) { $dateDiv.focus(); }).on('keyup', function (e) { datePickerInstance.hint($dateDiv.val()); if (e.keyCode === 13) { currentValue = $dateDiv.val(); $('span.laydate-btns-clear').trigger('click'); datePickerInstance.config.value = currentValue; $dateDiv.val(currentValue); $dateDiv.blur(); datePickerInstance._instance && datePickerInstance._instance.checkDate(); } }).on('blur', function (e) { $dateDiv.val(currentValue); }).on('focus', function (e) { currentValue = $dateDiv.val(); }); } function setFrozentableStyle(frozenTable, styleObj) { var rowHeight = styleObj.rowHeight || 20, rowLineVisible = styleObj.rowLineVisible, columnLineVisible = styleObj.columnLineVisible, isRowAlter = styleObj.isRowAlter, rowAlterColor = styleObj.rowAlterColor || 'rgba(0,0,0,0)', selectedRowColor = styleObj.selectedRowColor || 'rgba(0,0,0,0)', backColor = styleObj.backColor || 'rgb(255,255,255)', headColor = styleObj.headColor || 'rgb(125, 125, 125)', headGradientColor = styleObj.headGradientColor || 'rgb(125, 125, 125)', fontColor = styleObj.fontColor || 'black', fontSize = styleObj.fontSize || 12, fontFamily = styleObj.fontFamily || '"Microsoft YaHei"', headerFontSize = styleObj.headerFontSize || 14, headerFontFamily = styleObj.headerFontFamily || '"Microsoft Yahei"', headerFontStyle = styleObj.headerFontStyle || 'normal', headerHeight = styleObj.headerHeight || 26, headerBackImage = styleObj.headerBackImage, bodyFontStyle = styleObj.bodyFontStyle || 'normal', scrollBarColor = styleObj.scrollBarColor || 'rgba(100, 100, 100, 0.3)', lineColor = styleObj.lineColor; frozenTable.setRowHeight(rowHeight); frozenTable.setRowLineVisible(rowLineVisible); frozenTable.setColumnLineVisible(columnLineVisible); frozenTable.drawRowBackground('rgba(0,0,0,0)', isRowAlter, rowAlterColor, selectedRowColor); frozenTable.setBackground(backColor); frozenTable.setHeaderGradientColor(headColor, headGradientColor); frozenTable.getLabelColor(fontColor); frozenTable.getLabelFont(fontSize, fontFamily); frozenTable.setBodyLabelFont(fontSize, fontFamily, bodyFontStyle); frozenTable.setHeaderLabelFont(headerFontSize, headerFontFamily, headerFontStyle); frozenTable.setHeaderHeight(headerHeight); frozenTable.setRowLineColor(lineColor); frozenTable.setColumnLineColor(lineColor); frozenTable.setFrozentableScrollBarColor(scrollBarColor); if (headerBackImage) { var $tableheaderbg = $('
    '); $tableheaderbg.css({ height: headerHeight, left: 0, right: 0, top: 0, position: 'absolute', backgroundImage: 'url(' + PAGEROOTDIR + headerBackImage + ')', backgroundSize: '100% 100%', backgroundRepeat: 'no-repeat', backgroundPosition: 'center center' }); $(frozenTable.getBorderPane().getView()).css({ overflow: 'visible' }).prepend($tableheaderbg); } } function createPagenation() { var toolbar = new ht.widget.Tollbar(); var items = [ { label: "<<", action: function () { pageinputHis.value = 1; alarmHisSearch(); }, unfocusable: true }, { label: "<", action: function () { if (Number(pageinputHis.value) > 1) { pageinputHis.value = Number(pageinputHis.value) - 1; alarmHisSearch(); } }, unfocusable: true }, { label: '页:', element: pageinputHis, unfocusable: true }, { label: '>', action: function () { if (Number(pageinputHis.value) < Number(pageCountHis.getValue())) { pageinputHis.value = Number(pageinputHis.value) + 1; alarmHisSearch(); } }, unfocusable: true }, { label: ">>", action: function () { pageinputHis.value = pageCountHis.getValue(); alarmHisSearch(); }, unfocusable: true }, { label: '共 100 页', unfocusable: true }, { id: 'bottomtoolbarseprator', selected: false, unfocusable: true, button: { width: ((width * 0.5) - 130), editable: false, background: 'rgba(0,0,0,0)', selectBackground: 'rgba(0,0,0,0)', borderColor: 'rgba(0,0,0,0)', } } ] }; function testSearchTime(startTime, endTime) { if (!startTime || !endTime) { GD.createErrorDialog(360, 240, '请先选择查询时间段!'); return false; } var st = +new Date(startTime), et = +new Date(endTime); if (st >= et) { GD.createErrorDialog(360, 240, '开始时间应小于结束时间!'); return false; } return true; } GD.getRectJSON = (function () { function rectClip (g, width, height, data) { width = data.getWidth(); height = data.getHeight(); drawRect(g, 0, 0, width, height); g.clip(); } function ovalClip (g, width, height, data) { width = data.getWidth(); height = data.getHeight(); drawEllipse(g, 0, 0, width, height); g.clip(); } function arcClip (g, width, height, data) {} var rectJSON = { width: {value: 100, func: 'attr@node.width'}, height: {value: 100, func: 'attr@node.height'}, clip: rectClip, comps: [ { type: {value: 'rect', func: 'attr@node.type'}, rect: {value: [0, 0, '', ''], func: 'attr@node.rect'}, background: {value: '', func: 'attr@node.background'}, gradientColor: {value: '', func: 'attr@node.gradientcolor'}, gradient: {value: '', func: 'attr@node.gradient'} }, { type: 'rect', rect: {value: [0,0,0,0], func: 'attr@node.fillrect'}, background: {value: '', func: 'attr@node.fillbackcolor'}, gradientColor: {value: '', func: 'attr@node.fillgradientcolor'}, gradient: {value: '', func: 'attr@node.fillgradient'}, }, { type: {value: 'rect', func: 'attr@node.type'}, rect: {value: [0, 0, 0, 0], func: 'attr@node.rect'}, borderWidth: {value: 2, func: 'attr@node.borderwidth'}, borderColor: {value: '', func: 'attr@node.color'}, borderPattern:{value: [0,0], func: 'attr@node.borderPattern'} } ] }, ovalJSON = { width: {value: 100, func: 'attr@node.width'}, height: {value: 100, func: 'attr@node.height'}, clip: ovalClip, comps: [ { type: {value: 'rect', func: 'attr@node.type'}, rect: {value: [0, 0, 0, 0], func: 'attr@node.rect'}, background: {value: '', func: 'attr@node.background'}, gradientColor: {value: '', func: 'attr@node.gradientcolor'}, gradient: {value: '', func: 'attr@node.gradient'}, arcFrom: {value: 0, func: 'attr@node.arcFrom'}, arcTo: {value: 0, func: 'attr@node.arcTo'}, arcClose: {value: false, func: 'attr@node.arcClose'}, }, { type: 'rect', rect: {value: [0,0,0,0], func: 'attr@node.fillrect'}, background: {value: '', func: 'attr@node.fillbackcolor'}, gradientColor: {value: '', func: 'attr@node.fillgradientcolor'}, gradient: {value: '', func: 'attr@node.fillgradient'}, }, { type: {value: 'rect', func: 'attr@node.type'}, rect: {value: [0, 0, '', ''], func: 'attr@node.rect'}, borderWidth: {value: 2, func: 'attr@node.borderwidth'}, borderColor: {value: '', func: 'attr@node.color'}, borderPattern:{value: [0,0], func: 'attr@node.borderPattern'}, arcFrom: {value: 0, func: 'attr@node.arcFrom'}, arcTo: {value: 0, func: 'attr@node.arcTo'}, arcClose: {value: false, func: 'attr@node.arcClose'}, } ] }, arcJSON = { width: {value: 100, func: 'attr@node.width'}, height: {value: 100, func: 'attr@node.height'}, clip: arcClip, comps: [ { type: {value: 'rect', func: 'attr@node.type'}, rect: {value: [0, 0, 0, 0], func: 'attr@node.rect'}, background: {value: '', func: 'attr@node.background'}, gradientColor: {value: '', func: 'attr@node.gradientcolor'}, gradient: {value: '', func: 'attr@node.gradient'}, arcFrom: {value: 0, func: 'attr@node.arcFrom'}, arcTo: {value: 0, func: 'attr@node.arcTo'}, arcClose: {value: false, func: 'attr@node.arcClose'}, arcOval: {value: true, func: 'attr@node.arcOval'} }, { type: 'rect', rect: {value: [0,0,0,0], func: 'attr@node.fillrect'}, background: {value: '', func: 'attr@node.fillbackcolor'}, gradientColor: {value: '', func: 'attr@node.fillgradientcolor'}, gradient: {value: '', func: 'attr@node.fillgradient'}, }, { type: {value: 'rect', func: 'attr@node.type'}, rect: {value: [0, 0, '', ''], func: 'attr@node.rect'}, borderWidth: {value: 2, func: 'attr@node.borderwidth'}, borderColor: {value: '', func: 'attr@node.color'}, borderPattern:{value: [0,0], func: 'attr@node.borderPattern'}, arcFrom: {value: 0, func: 'attr@node.arcFrom'}, arcTo: {value: 0, func: 'attr@node.arcTo'}, arcClose: {value: false, func: 'attr@node.arcClose'}, arcOval: {value: true, func: 'attr@node.arcOval'} } ] } return function (width, height, type, arcFrom, arcTo, arcClose) { var json; if (type === 'oval') { json = ovalJSON; } else if (type === 'rect') { json = rectJSON; } else if (type === 'arc') { json = arcJSON; } return json; } })(); GD.getTextJSON = (function () { var json = { width: {value: 100, func: 'attr@node.width'}, height: {value: 100, func: 'attr@node.height'}, comps: [ { type: 'rect', rect: {value: [0, 0, 0, 0], func: 'attr@node.rect'}, borderWidth: {value: 0, func: 'attr@node.borderwidth'}, borderColor: {value: '', func: 'attr@node.bordercolor'}, gradient: {value:'', func: 'attr@node.gradient'}, background:{value:'', func: 'attr@node.background'}, gradientColor:{value:'', func: 'attr@node.gradientcolor'}, }, { type:'text', text: {value:'', func: 'attr@node.text'}, align: {value: '', func: 'attr@node.textalign'}, vAlign: {value: '', func: 'attr@node.textvAlign'}, rect: {value: [0, 0, 0, 0], func: 'attr@node.textrect'}, color: {value:'', func: 'attr@node.color'}, font: {value: '', func: 'attr@node.font'}, visible: {value: true, func: 'attr@node.textvisible'} }, { type: {value: function (){}, func: 'attr@node.textfunc'}, visible: {value: true, func: 'attr@node.linefeed'} }, { type: 'shape', borderWidth: {value: 1, func: 'attr@node.underlineBorderWidth'}, borderColor: {value:'', func: 'attr@node.color'}, points:{value: '', func: 'attr@node.underlinepoints'}, segments: [1, 2], visible: {value: true, func: 'attr@node.underlinevisible'} } ] }; return function (width, height, isLineFeed, lineFeed, showUnderLine, fontStyle) { return json; } })(); GD.getPolyLineJSON = (function () { var json; return function () { json = json || { width: {value: 1, func: 'attr@node.width'}, height: {value: 1, func: 'attr@node.height'}, comps: [ { type: 'shape', points: {value: [], func: 'attr@node.points'}, segments: {value: [], func: 'attr@node.segments'}, borderWidth:{value:1, func: 'attr@node.borderwidth'}, borderColor:{value: 'rgb(0,0,0)', func: 'attr@node.color'}, closePath:false, dash: false, borderPattern:{value:getDashStyle(""), func: 'attr@node.borderPattern'} }, { type: 'triangle', background:{value:'rgb(0,0,0)', func: 'attr@node.background'}, gradient: {value:'rgb(0,0,0)', func: 'attr@node.gradient'}, gradientColor:{value:'rgb(0,0,0)', func: 'attr@node.gradientcolor'}, rect:{value: [], func: 'attr@node.endCompspts'}, rotation:{value: 0, func: 'attr@node.endRotation'}, offsetX:{value: 0, func: 'attr@node.offsetEndX'}, offsetY:{value: 0, func: 'attr@node.offsetEndY'}, }, { type: 'triangle', background:{value:'@backcolor@', func: 'attr@node.background'}, gradient: {value:'rgb(0,0,0)', func: 'attr@node.gradient'}, gradientColor:{value:'rgb(0,0,0)', func: 'attr@node.gradientcolor'}, rect:{value: [], func: 'attr@node.startCompspts'}, rotation:{value:0, func: 'attr@node.startRotation'}, offsetY:{value: 0, func: 'attr@node.offsetStartY'}, offsetX:{value: 0, func: 'attr@node.offsetStartX'} } ] } return json; }; })(); GD.getPolyGonJSON = (function () { var json; return function getPolyGonJSON() { json = json || { width:{value: 10, func: 'attr@node.width'}, height:{value: 10, func: 'attr@node.height'}, clip: {value: function(){}, func: 'attr@node.clip'}, comps: [ { type: {value: 'rect', func: 'attr@node.type'}, points:{value: [], func: 'attr@node.comsPoints'}, segments: {value: [], func: 'attr@node.segments'}, closePath: {value: true, func: 'attr@node.closePath'}, borderWidth: {value:1, func: 'attr@node.borderwidth'}, borderColor:{value: 'rgb(0,0,0)', func: 'attr@node.color'}, background:{value:'rgb(0,0,0)', func: 'attr@node.background'}, gradient: {value:'', func: 'attr@node.gradient'}, gradientColor:{value:'rgb(0,0,0)', func: 'attr@node.gradientcolor'}, // borderPattern:{value:"", func: 'attr@node.borderPattern'}, isFill:{value:"false", func: 'attr@node.isFill'} }, { type: 'rect', rect: {value:[0,0,0,0], func: 'attr@node.original'}, background:{value:'rgb(0,0,0)', func: 'attr@node.background'}, gradient: {value:'', func: 'attr@node.gradient'}, gradientColor:{value:'rgb(0,0,0)', func: 'attr@node.gradientcolor'}, }, { type: 'rect', rect: {value:[0,0,0,0], func: 'attr@node.fillrect'}, background:{value:'rgb(0,0,0)', func: 'attr@node.fillbackcolor'}, gradient: {value:'', func: 'attr@node.fillgradient'}, gradientColor:{value:'rgb(0,0,0)', func: 'attr@node.fillgradientcolor'} }, { type: {value: 'rect', func: 'attr@node.type'}, points:{value: [], func: 'attr@node.comsPoints'}, segments: {value: [], func: 'attr@node.segments'}, closePath: {value: true, func: 'attr@node.closePath'}, borderWidth: {value:1, func: 'attr@node.borderwidth'}, borderColor:{value: 'rgb(0,0,0)', func: 'attr@node.color'}, borderJoin: 'miter', borderPattern:{value:"", func: 'attr@node.borderPattern'} } ] } return json; } })(); GD.getBowJSON = (function () { var json; return function getBowJson() { json = json || { width: {value: 10, func: 'attr@node.width'}, height: {value: 10, func: 'attr@node.height'}, comps: [ { type: 'arc', rect: {value: [0, 0, 100, 100], func: 'attr@node.rect'}, arcFrom:{value: 0, func: 'attr@node.arcFrom'}, arcTo:{value: 0, func: 'attr@node.arcTo'}, arcClose: false, arcOval:true, borderWidth: {value:1, func: 'attr@node.borderwidth'}, borderColor:{value: 'rgb(0,0,0)', func: 'attr@node.color'}, background:{value:'rgb(0,0,0)', func: 'attr@node.background'}, dash: false, gradient: {value:'', func: 'attr@node.gradient'}, gradientColor:{value:'rgb(0,0,0)', func: 'attr@node.gradientcolor'}, borderPattern:{value:'', func: 'attr@node.borderPattern'} }, { type:'shape', borderWidth:{value:1, func: 'attr@node.borderwidth'}, borderColor: {value: 'rgb(0,0,0)', func: 'attr@node.borderColor'}, points:{value: [], func: 'attr@node.points'}, borderPattern:{value:getDashStyle("@borderPattern@"), func: 'attr@node.borderPattern'}, segments: [1,2] } ] } return json; } })(); // 创建报警弹窗 (function (w) { var alarmWindow = {}; function createAlarmWindow(callback) { callback = callback || function () { }; function createTabTitle (index, isCurrent, title, k) { var str = '
  • '+ title +'
  • '; return str; } function createTabContent (index, isCurrent, contentObj) { var arr = []; arr.push('
  • '); arr.push('
      '); arr.push('
    • 设备编号:

      '+ contentObj.alarmAreaName +'

    • '); arr.push('
    • 故障名称:

      '+ contentObj.alarmDesc +'

    • '); arr.push('
    • '); arr.push('故障时间:'); arr.push('

      '); arr.push(''+ contentObj.alarmTime.split(' ')[0] +''); arr.push(''+ contentObj.alarmTime.split(' ')[1] +''); arr.push('

  • '); return arr.join(''); } function createDom() { var htmlStr = '', htmlArr = []; htmlArr.push('
    '); htmlArr.push('
    '); htmlArr.push('

    待确认故障3

    '); htmlArr.push('
    -
    '); htmlArr.push('
    '); htmlArr.push('
    '); htmlArr.push('
    '); htmlArr.push('
      '); // htmlArr.push('
    • t1
    • '); // htmlArr.push('
    • t2
    • '); // htmlArr.push('
    • t3
    • '); // htmlArr.push('
    • t4
    • '); htmlArr.push('
    '); htmlArr.push('
    '); htmlArr.push('
    '); htmlArr.push('
    ') htmlArr.push('
      '); // htmlArr.push('
    • '); // htmlArr.push('
        '); // htmlArr.push('
      • 风机编号:

        发电机启动

      • '); // htmlArr.push('
      • 故障名称:

        发电机启动异常发电机启动异常发电机启动

      • '); // htmlArr.push('
      • '); // htmlArr.push('故障时间:'); // htmlArr.push('

        '); // htmlArr.push('2018-1-30'); // htmlArr.push('10:30:00'); // htmlArr.push('

    • '); // htmlArr.push('
    • b2
    • '); // htmlArr.push('
    • b3
    • '); // htmlArr.push('
    • b4
    • '); htmlArr.push('
    '); htmlArr.push('
    '); htmlArr.push('
    '); htmlArr.push('
    确认
    '); htmlArr.push('
    '); return $(htmlArr.join(''))[0]; } function addEventToDom(dom) { var $alarmWindow = $(dom), $alarmTab = $alarmWindow.find('.alarm-window-body-tab'), $alarmContent = $alarmWindow.find('.alarm-window-body-content'), $tabBtns = $alarmTab.find('li'), $contents = $alarmContent.find('li'), $confirmBtn = $alarmWindow.find('.alarm-window-confirmbtn'), $headToggleBtn = $alarmWindow.find('.alarm-window-head-btns-toggle'); $tabBtns.off('click').on('click', function () { var $this = $(this), target = '.' + $this.data('target'), index = $this.data('index'); $tabBtns.removeClass('current'); $this.addClass('current'); $contents.removeClass('current').parent().find(target).addClass('current'); // 将当前标签对应的数据设置为当前数据,确认时使用 alarmWindow.currentData = alarmWindow.alarmData && alarmWindow.alarmData[index]; }); $headToggleBtn.off('click').on('click', function () { var state = $headToggleBtn.data('state'); if (state === 'max') { $headToggleBtn.text('+'); $headToggleBtn.data('state', 'min'); alarmWindow.alarmWindowMinify(); } else { $headToggleBtn.text('-'); $headToggleBtn.data('state', 'max'); alarmWindow.alarmWindowReduction(); } }).off('mousedown').on('mousedown', function (e) { e.stopPropagation(); }) $confirmBtn.off('click').on('click', function () { callback(); }); $alarmWindow.off('mouseenter').on('mouseenter', function (e) { e.stopPropagation(); if (!alarmWindow.isHide()) $alarmWindow.stop().fadeTo(300, 1); }).off('mouseleave').on('mouseleave', function (e) { e.stopPropagation(); if (!alarmWindow.isHide()) $alarmWindow.stop().fadeTo(1000, 0.3); }) } function bindDataToDom(dataObj) { if (!dataObj) return; var $dom = alarmWindow._$dom || $(alarmWindow._dom), $tabTitleContainer = $dom.find('.alarm-window-tab-title-container'), $contentContainer = $dom.find('.alarm-window-body-content-container'), $count = alarmWindow._$count || $dom.find('.alarm-count'), d, i = 0, isCurrent; alarmWindow.alarmData = dataObj; $tabTitleContainer.children().remove(); $contentContainer.children().remove(); for (var key in dataObj) { if (key !== 'count' && dataObj.hasOwnProperty(key)) { d = dataObj[key]; if (!d) continue; $tabTitleContainer.append($(createTabTitle(i, !!d.isCurrent, d.systemName, key))); $contentContainer.append($(createTabContent(i, !!d.isCurrent, d))); if (d.isCurrent) { alarmWindow.currentData = d; } i++; } } $count.text(dataObj.count || 0); } function refreshData(data) { // 如果数据条数为0则隐藏弹窗 if (!data || !data.count) { alarmWindow.alarmWindowHide(); return; } bindDataToDom(data); if (alarmWindow.isHide()) { alarmWindow.alarmWindowShow(); } } function alarmWindowMinify() { var $dom = alarmWindow._$dom || $(alarmWindow._dom); $dom.addClass('alarm-window-minify'); $dom.css({ left: 'auto', top: 'auto' }) } function alarmWindowReduction() { var $dom = alarmWindow._$dom || $(alarmWindow._dom); $dom.removeClass('alarm-window-minify'); } function alarmWindowDragable(dragable) { if (!dragable) return; var $dom = alarmWindow._$dom || $(alarmWindow._dom), $head = $dom.find('.alarm-window-head'), $h3 = $head.find('h3'), $body = $(document.body), mousemoveFunc, offsetX, offsetY, $window = $(window), mousemoveFunc = function (e) { var clientX = e.clientX, clientY = e.clientY; var l = clientX - offsetX, t = clientY - offsetY, wx = $window.width(), wh = $window.height(), w = $dom.width(), h = $dom.height(), ox = wx - w, oh = wh - h; l = l <= 0 ? 0 : l; t = t <= 0 ? 0 : t; l = l >= ox ? ox : l; t = t >= oh ? oh : t; $dom.css({ left: l, top: t }) } $h3.on('mousedown', function (evt) { evt.stopPropagation(); }) $head.on('mousedown', function (evt) { evt.stopPropagation(); offsetX = evt.offsetX, offsetY = evt.offsetY; $body.on('mousemove', mousemoveFunc) }) $body.on('mouseup', function (e) { $body.off('mousemove', mousemoveFunc); }).on('mouseleave', function () { $body.off('mousemove', mousemoveFunc); }) } function alarmWindowHide() { var $dom = alarmWindow._$dom || $(alarmWindow._dom); alarmWindow._isHide = true; $dom.stop().hide(); } function alarmWindowShow() { var $dom = alarmWindow._$dom || $(alarmWindow._dom); alarmWindow._isHide = false; $dom.stop().show(); } function delayFade(t) { var $dom = alarmWindow._$dom || $(alarmWindow._dom); setTimeout(function () { if (!alarmWindow.isHide()) $dom.stop().fadeTo(500, 0.3); }, t); } function isHide() { return alarmWindow._isHide; } function setFlagShaly() { var $dom = alarmWindow._$dom || $(alarmWindow._dom), $flag = $dom.find('.alarm-window-body-flag'); alarmWindow._timer && clearInterval(alarmWindow._timer); alarmWindow._timer = setInterval(function () { var flag = $flag.data('flag'); if (flag === 'flag1') { $flag.data('flag', 'flag2'); $flag.css({ backgroundPosition: 'right center' }) } else { $flag.data('flag', 'flag1'); $flag.css({ backgroundPosition: 'left center' }) } }, 500) } alarmWindow._dom = alarmWindow._dom || createDom(); alarmWindow.refreshData = refreshData; alarmWindow.alarmWindowMinify = alarmWindowMinify; alarmWindow.alarmWindowReduction = alarmWindowReduction; alarmWindow.alarmWindowDragable = alarmWindowDragable; alarmWindow.alarmWindowShow = alarmWindowShow; alarmWindow.alarmWindowHide = alarmWindowHide; alarmWindow.addEventToDom = addEventToDom; alarmWindow.isHide = isHide; alarmWindow.delayFade = delayFade; alarmWindow.setFlagShaly = setFlagShaly; alarmWindow.delayFade(3000); alarmWindowHide(); return alarmWindow; } w.createAlarmWindow = createAlarmWindow; })(GD); GD.testSearchTime = testSearchTime; GD.createPagenation = createPagenation; GD.setFrozentableStyle = setFrozentableStyle; GD.setupDatePicker = setupDatePicker; GD.setDialogStyle = setDialogStyle; GD.createMessageDialog = createMessageDialog; GD.createErrorDialog = createErrorDialog; GD.createButton = createButton; W.GD = GD; })(window); // http (function (W) { var GD = W.GD || {}; function getHisTrendData(cmdStr, callback) { var paras = cmdStr.split('&'), result; str = "http://" + webServiceIP + ":" + webServicePort + "/api/HistoryInterval?tagName="; str = str + encodeURIComponent(paras[0]) + "&" + paras[1] + "&" + paras[2] + "&" + paras[3] + "&" + paras[4]; $.ajax({ url: str, type: 'GET', dataType: 'json', cache: false, success: function (data) { result = data; }, complete: function (XHR, TS) { XHR = null; callback(result); }, error: function (data) { result = null; } }); } GD.getHisTrendData = getHisTrendData; W.GD = GD; })(window); // 封装socketio (function (W, io) { var GD = W.GD || {}; if (!io) { return }; var TIMEOUTERRORDATA = { success: false, error: { code: 408, detail: '请求超时', status: 'Request Timeout' }, api: '' }, LOGOUTERRORDATA = { success: false, error: { code: 401, detail: '用户未登录', status: 'User Logout' }, api: '' }; // 封装sokcetio function IO(url, params) { this._url = url; this._params = params; this.socketio = io(url, params); this._alarmPostCount = 0; this._callbackDic = {}; this.init(); } IO.prototype = { init: function () { var that = this, callback; // console.log(_data); // 接收到数据时回调 function cb(data) { data = JSON.parse(data); var eventName = data.api, timenum; if (eventName == "alarmservice.call") { timenum = data.body && data.body.json && data.body.json.split('{')[0]; if (that._callbackDic["alarmservice.call"]) { if (typeof that._callbackDic[eventName][timenum] === 'function') { that._callbackDic[eventName][timenum](that._depackAlarmData(data)); that._callbackDic[eventName][timenum] = null; } } } else if (eventName === "alarmservice.sub") { callback = that._callbackDic["alarmservice.sub"] || function () { }; callback(that._depackAlarmData(data)); } else { // 清除接收消息事件 if (typeof that._callbackDic[eventName] === 'function') { that._callbackDic[eventName](data); that._callbackDic[eventName] = null; } } callback = null; } that.socketio.on('message', cb); }, on: function (eventName, callback) { callback = callback || function () { }; this.socketio.on(eventName, function (result) { var data; try { data = JSON.parse(result); } catch (error) { data = { success: false, error: { code: '417', detail: '返回参数格式错误', status: 'format error' }, api: eventName } } callback(data) }); }, alarmOn: function (eventname, callback) { var that = this; callback = callback || {}; that.on(eventName, function (result) { var _result = {}; if (result && result.success) { _result = that._depackAlarmData(result); } else { _result = result; } _result.api = eventname; callback(_result); }) }, post: function (eventName, data, callback, timeout) { var that = this; var args; if (!that.socketio.connected) { if (that.socketio.reconnection === false) { return; } args = Array.prototype.slice.call(arguments, 0); (function (args, that) { setTimeout(function () { that.post.apply(that, args); }, 100) })(args, that); return; } timeout = timeout || 8; if (typeof data === 'function') { callback = data; data = {}; } else { data = data || {}; callback = callback || function () { } } var header = {}, _data = {}; if (eventName != 'auth.authenticate') { var token = localStorage.getItem('token'); if (!token) { // 如果没有token,未登录,返回未登录信息 LOGOUTERRORDATA.api = eventName; callback(LOGOUTERRORDATA); return; } token = token.replace(/^\s+/g, '').replace(/\s+$/g, '').replace(/^"/g, '').replace(/"$/g, ''); // 删除token两端的 " // token = token.substr(1, token.length-2); header.token = token; _data.header = header; } _data.api = eventName; _data.request = data; _data = JSON.stringify(_data); that._callbackDic[eventName] = callback; // 发送请求 that.socketio.emit('message', _data, function () { }); // 开始计时,5S未收到返回会超时,并回调超时信息。 var timer = setTimeout(function () { // 清除接收消息事件,避免重复接收 TIMEOUTERRORDATA.api = eventName; var cb; //返回超时信息 cb = that._callbackDic[eventName]; if (typeof cb === 'function') { cb(TIMEOUTERRORDATA); that._callbackDic[eventName] = null; } }, timeout * 1000); }, /** * 请求数据: * { * "method": "GetGroups", * "param": {} * } * 返回格式: * { * success: true, * data: { * data: { * user: 'admin' * } * } * } * 错误时: * { * success: false, * data: {}, * error: { * code: '400', * status: 'bad request', * detail: '无效的请求参数' * } * } * */ alarmPost: function (eName, data, callback, timeout) { var that = this; var args, _data = {}; if (!that.socketio.connected) { if (that.socketio.reconnection === false) { // 如果没有自动重连,直接返回 return; } args = Array.prototype.slice.call(arguments, 0); (function (args, that) { setTimeout(function () { that.alarmPost.apply(that, args); }, 100); })(args, that); return; } timeout = timeout || 10; if (typeof data === 'function') { callback = data; data = {}; } else { data = data || {}; callback = callback || function () { } } var _data = {}; var eventName = eName.split('?')[0]; var flag = '_'; var postApi; that._alarmPostCount += 1; if (that._alarmPostCount > 100) { that._alarmPostCount = 1; } flag += that._alarmPostCount; // 配合报警服务,把数据序列化 if (eventName === '/alarm/SubscribeNotify') { _data.json = flag + JSON.stringify({ data: data }); postApi = "alarmservice.sub"; // 保存回调函数 // that._callbackDic[postApi] = that._callbackDic[postApi] || []; that._callbackDic[postApi] = callback; } else { _data.json = flag + JSON.stringify({ data: data, url: eventName }); postApi = "alarmservice.call"; // 保存回调函数 that._callbackDic[postApi] = that._callbackDic[postApi] || {}; that._callbackDic[postApi][flag] = callback; } var token = localStorage.getItem('token'), header = {}, alarmData = {}; if (!token) { // 如果没有token,未登录,返回未登录信息 LOGOUTERRORDATA.api = postApi; callback(LOGOUTERRORDATA); return; } token = token.replace(/^\s+/g, '').replace(/\s+$/g, '').replace(/^"/g, '').replace(/"$/g, ''); // 删除token两端的 " // token = token.substr(1, token.length-2); header.token = token; alarmData.header = header; alarmData.api = postApi; alarmData.request = _data; alarmData = JSON.stringify(alarmData) that.socketio.send(alarmData); // that.post(postApi, alarmData, function (result) { // var _result = {}, // jsonStr; // // if (result && result.success) { // _result = that._depackAlarmData(result); // } else { // _result = result; // } // _result.api = eventName; // callback(_result); // }, timeout) }, reconnect: function (callback) { callback = callback || function () { }; this.socketio.reconnect(callback); }, disconnect: function (callback) { callback = callback || function () { }; this.socketio.disconnect(callback); }, getNewToken: function () { }, _depackAlarmData: function (result) { var _result = {}, jsonStr, flagnum; try { if (result.api == "alarmservice.call") { flagnum = result.body.json.split('{')[0]; jsonStr = GD.deEscape(result.body.json.substring(result.body.json.indexOf('{'))); if (jsonStr[jsonStr.length - 1] != '}') { jsonStr += '}'; } _result = JSON.parse(jsonStr); _result.flagnum = flagnum; } else if (result.api == "alarmservice.sub") { jsonStr = GD.deEscape(result.body.json); _result = JSON.parse(jsonStr); } _result.success = true; } catch (error) { _result.success = false; _result.data = {}; _result.error = { code: "", status: '', detail: error.message } } return _result; }, _packAlarmData: function () { } } GD.io = function (url, params) { return new IO(url, params); } W.GD = GD; })(window, _io); // webAPI交互 (function (W) { var GD = W.GD || {}; GD.exportElectricIndicates = function (beginTime, endTime, tags, typeArr) { tags = tags.join(','); var uri = 'tags=' + tags + "&"; uri += 'beginTime=' + beginTime + "&"; uri += 'endTime=' + endTime + '&'; uri += 'valueType=' + typeArr.join(','); var link = document.createElement("a"); link.download = "exportExcel"; link.href = "http://" + webServiceIP + ":" + webServicePort + "/api/ExportToExcelInterpo?" + encodeURIComponent(uri); link.click(); }; GD.exportArrToCsv = function exportTagsToCSV(arr, fileName) { fileName = fileName || 'data'; if (!arr) return; var tempArr = [], result; for (var i = 0, len = arr.length; i < len; i++) { tempArr.push(arr[i].join(',')); } result = tempArr.join('\r\n'); result = '\uFEFF' + result; var blob = new Blob([result], { type: 'text/csv;charset=UTF-8' });// saveAs(blob, fileName + Date.now() + '.csv'); } GD.getCurrentUserName = function (fromService) { var localParams = GD.getParams('user') || {}; if (!fromService) { return localParams.name || ''; } } GD.getCurrentUserGroup = function (groupid) { return '' } W.GD = GD; })(window); (function (W) { var GD = W.GD || {}; function deEscape(str) { if (!str) { return ""; } // str = str.replace(/\u0000/g, ""); // str = unescape(str.replace(/\\(u[0-9a-fA-F]{4})/g, '%$1')); str = unescape(str.replace(/\\(u[0-9a-fA-F]{4})/gm, '')); return str; } function eascape(str) { return str; } function getStrLength(str) { if (!str) return 0; str.toString && (str = str.toString()); return str.replace(/[^\x00-\xff]/g, "01").length; } // 节流函数 function throttle(func, time) { time = time || 200; func = typeof func === 'function' ? func : function () { }; func._timer_ && clearTimeout(func._timer_); var args = Array.prototype.slice.call(arguments, 2); func._timer_ = setTimeout(function () { func._timer_ = null; func.apply(null, args); }, time) } function getSearchObjFromUrl(urlStr) { urlStr = urlStr || location.href; var index, searchStr, searchArr, tempArr, searchObj = {}; index = urlStr.indexOf('?') === -1 ? 0 : urlStr.indexOf('?') + 1; var searchStr = urlStr.substr(index); var searchArr = searchStr.split('&'); for (var i = 0, len = searchArr.length; i < len; i++) { tempArr = searchArr[i].split('='); if (tempArr[0] && tempArr[1]) { searchObj[tempArr[0]] = tempArr[1]; } } return searchObj; } function removeRepeated(arr, changeOrigin) { var obj = {}, newArr = [], temp; for (var i = 0, len = arr.length; i < len; i++) { temp = arr[i]; if (!obj[temp]) { newArr.push(temp); obj[temp] = true; } } if (changeOrigin) { arr.length = 0; for (i = 0, len = newArr.length; i < len; i++) { arr.push(newArr[i]); } } return newArr; } function getMaxAndMinFromSeries(series) { var max = min = 0, s, d, l, v; for (var i = 0, len = series.length; i < len; i++) { s = series[i]; d = s.data || []; for (var j = 0, l = d.length; j < l; j++) { v = d[j] - 0; max = v > max ? v : max; min = v < min ? v : min; } } return { max: max, min: min } } function getRelativeDate(dt, format, beginOrEnd) { var d = new Date(); var typeMap = { date: 'YYYY-MM-DD', time: 'HH:mm:ss', datetime: 'YYYY-MM-DD HH:mm:ss', year: 'YYYY', month: 'YYYY-MM' } dt = $.trim(dt); var count = parseInt(dt), type = dt.substr(count.toString().length), result; function formatDate(date, format) { var result = moment(date).format(typeMap[format] || typeMap.datetime); return result; } function calcRelativeDate(date, type, bod) { switch (type) { case 'h': case 'hour': date.setHours(date.getHours() - count); if (bod === 'begin') { date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); } if (bod === 'end' && count !== 0) { date.setMinutes(59); date.setSeconds(59); date.setMilliseconds(0); } break; case 'd': case 'day': date.setDate(date.getDate() - count); if (bod === 'begin') { date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); } if (bod === 'end' && count !== 0) { date.setHours(23); date.setMinutes(59); date.setSeconds(59); date.setMilliseconds(0); } break; case 'm': case 'month': date.setMonth(date.getMonth() - count); if (bod === 'begin') { date.setDate(1); date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); } if (bod === 'end' && count !== 0) { date.setMonth(date.getMonth() + 1); date.setDate(1); date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); date = new Date(+new Date(date) - 1000); } break; case 'y': case 'year': date.setFullYear(date.getFullYear() - count); if (bod === 'begin') { date.setMonth(0); date.setDate(1); date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); } if (bod === 'end' && count !== 0) { date.setFullYear(date.getFullYear() + 1); date.setMonth(0); date.setDate(1); date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setMilliseconds(0); date = new Date(+new Date(date) - 1000); } break; default: date = dt; } return date; } result = calcRelativeDate(d, type, beginOrEnd); return formatDate(result, typeMap[format]); } function isEmptyObj(obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) { return false; } } return true; } var measureCanvasText = (function () { var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'); return function (text, fontStyle) { ctx.font = fontStyle; return ctx.measureText(text).width; } })(); function eval(str) { var fun = new Function('return ' + str); var result; try { result = fun(); } catch (error) { console.log(error.message); result = error; } return result; } GD.eval = eval; GD.isEmptyObj = isEmptyObj; GD.deEscape = deEscape; GD.getRelativeDate = getRelativeDate; GD.getMaxAndMinFromSeries = getMaxAndMinFromSeries; GD.eascape = eascape; GD.getStrLength = getStrLength; GD.measureCanvasText = measureCanvasText; GD.throttle = throttle; GD.getSearchObjFromUrl = getSearchObjFromUrl; GD.removeRepeated = removeRepeated; W.GD = GD; })(window); $window.off('customEventJump').on('customEventJump', function (e, args) { if (!args || !args.hash) return; var hash = window.location.hash || '#'; hash = hash.substr(1); if (args.params) { saveLocalParams && saveLocalParams(args.params); } window.location.hash = args && args.hash; if (hash === args.hash) { loadPage(hash); } }); $window.off('customEventSetPageSizeWithRatio').on('customEventSetPageSizeWithRatio', function (e, args) { var ratio = args && args.ratio; if (!ratio) return; window.GD && GD.setPageSizeWithRatio(ratio); }); // 当页面被嵌入其它框架时(跨域),将登录后的用户信息、token信息通过查询字符串传给,加载common时将信息保存到localStorage (function () { var search = location.search; if (!search) return; var obj = searchStrToObj(search) || {}; if (obj.user) { localStorage.setItem('user', obj.user); } if (obj.token) { localStorage.setItem('token', obj.token); } if (obj.userGroup) { localStorage.setItem('userGroup', obj.userGroup); } if (obj.userLevel) { localStorage.setItem('userLevel', obj.userLevel); } if (obj.extra) { localStorage.setItem('extra', obj.extra); } })(); function createHisBackDialog(callback) { var stopTime = 0; var time = new Date(); var cur_month = (time.getMonth() + 1) < 10 ? "0" + (time.getMonth() + 1) : (time.getMonth() + 1); var cur_day = time.getDate() < 10 ? "0" + time.getDate() : time.getDate(); var cur_hour = time.getHours() < 10 ? "0" + time.getHours() : time.getHours(); var cur_minu = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes(); var cur_sec = time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds(); var beginDate = time.getFullYear() + "-" + cur_month + "-" + cur_day + "T" + cur_hour + ":" + cur_minu + ":" + cur_sec; var endDate = beginDate; var nowspeed = 1, dataTime = ""; var htmlStr = '', htmlArr = [], ptime = "", interTimers = []; htmlArr.push('
    '); htmlArr.push('   '); htmlArr.push(''); htmlArr.push('
    x1'); htmlArr.push(''); htmlArr.push(''); htmlArr.push(''); htmlArr.push(''); htmlArr.push('
    '); htmlStr = $(htmlArr.join(''))[0]; // console.log(htmlStr); dialog.setConfig({ title: "历史回放", closable: true, draggable: true, width: 530, height: 100, contentPadding: 5, titleBackground: '#8DB6CD', content: htmlStr, buttons: [ ], buttonsAlign: "right" }); dialog.setModal(false); dialog.show(); $("#palyTime").click(function () { if ($("#palyTime").val() == "播放") { ptime = $("#beginDate").val().replace("T", " "); var end = $("#endDate").val().replace("T", " "); var beginTime = new Date(ptime).getTime(); var endTime = new Date(end).getTime(); //点击播放页面停止取快照 if (stopTime == 0) { clearInterval(intervalTimers[0]); intervalTimers.shift(intervalTimers[0]); stopTime++; } $("#palyTime").val("暂停"); var timeid = setInterval(function () { if (beginTime > endTime) { clearInterval(interTimers[0]); interTimers.shift(interTimers[0]); $("#palyTime").val("播放"); } else { $("#showTime").val(moment(ptime).format("YYYY/MM/DD h:mm:ss")); if (varList.length <= 0) { return; } var cmdStr = ""; var ajaxdata = {}; var ajaxtype = 'GET'; var str = "http://" + webServiceIP + ":" + webServicePort + "/api/History?tagName="; for (var i = 0; i < varList.length; i++) { cmdStr += encodeURIComponent(varList[i]) + "," } cmdStr = cmdStr.substring(0, cmdStr.length - 1); str = str + cmdStr + "&Time=" + ptime; if (str.length > 2000) { para = encodeURIComponent(cmdStr); str = "http://" + webServiceIP + ":" + webServicePort + "/api/History"; ajaxdata = { 'tagname': cmdStr,'time':ptime }; ajaxtype = 'POST'; } $.ajax({ url: str, type: ajaxtype, dataType: 'json', data: ajaxdata, cache: false, success: function (data) { if (data === null) return; var hisdata = data; if (hisdata != null) { for (var tagName in hisdata) { // console.log(moment(ptime).format("yyyy-MM-dd hh:mm:ss")); //console.log(hisdata[tagName].Time.toString("yyyy-MM-dd hh:mm:ss")); if (moment(ptime).format("YYYY-MM-DD h:mm:ss") == moment(hisdata[tagName].Time).format("YYYY-MM-DD h:mm:ss")) { if (parseFloat(hisdata[tagName].Value).toString() == hisdata[tagName].Value) { varListObj[tagName.toLowerCase()] = parseFloat(hisdata[tagName].Value); VarSnapshotTime[tagName.toLowerCase()] = hisdata[tagName].Time; } else { varListObj[tagName.toLowerCase()] = hisdata[tagName].Value; VarSnapshotTime[tagName.toLowerCase()] = hisdata[tagName].Time; } } } } ptime = getDateString(new Date(beginTime + nowspeed * 1000)); beginTime = new Date(ptime).getTime(); } }) } }, 1000); interTimers.push(timeid); } else { clearInterval(interTimers[0]); interTimers.shift(interTimers[0]); $("#palyTime").val("播放"); } }); //加速 $("#addSpeed").click(function () { if (nowspeed >= 128) { nowspeed = 128; } else { nowspeed = nowspeed * 2; } $("#nowspeed").html(nowspeed); }); //减速 $("#slowSpeed").click(function () { if (nowspeed <= 1) { nowspeed = 1; } else { nowspeed = nowspeed / 2; } $("#nowspeed").html(nowspeed); }); $("#closeBtn").click(function () { clearInterval(interTimers[0]); interTimers.shift(interTimers[0]); intervalTimers.unshift(setInterval(callback, 1000)); dialog.hide(); }); } function savehtmlToJpg() { //直接选择要截图的dom,就能截图,但是因为canvas的原因,生成的图片模糊 html2canvas(document.getElementsByClassName("main")[0]).then(function (canvas) { document.body.appendChild(canvas); }) //创建一个新的canvas var canvas2 = document.createElement("canvas"); let _canvas = document.getElementsByClassName("main")[0]; var w = parseInt(window.getComputedStyle(_canvas).width); var h = parseInt(window.getComputedStyle(_canvas).height); //将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了 canvas2.width = w * 2; canvas2.height = h * 2; canvas2.style.width = w + "px"; canvas2.style.height = h + "px"; // canvas2.width = w ; // canvas2.height = h ; // canvas2.style.width = w + "px"; // canvas2.style.height = h + "px"; //可以按照自己的需求,对context的参数修改,translate指的是偏移量 var context = canvas2.getContext("2d"); context.scale(2, 2); html2canvas(document.getElementsByClassName("main")[0], { canvas: canvas2 }).then(function (canvas) { document.body.appendChild(canvas); var aLink = document.createElement('a'); //canvas转换成url,然后利用a标签的download属性,直接下载,绕过上传服务器再下载 var blob = base64Img2Blob(canvas.toDataURL("image/png")); //new Blob([content]); var evt = document.createEvent("HTMLEvents"); evt.initEvent("click", false, false);//initEvent 不加后两个参数在FF下会报错 aLink.download = "下载图片.png"; aLink.href = URL.createObjectURL(blob); aLink.dispatchEvent(evt); aLink.click(); }); } function base64Img2Blob(code) { var parts = code.split(';base64,'); var contentType = parts[0].split(':')[1]; var raw = window.atob(parts[1]); var rawLength = raw.length; var uInt8Array = new Uint8Array(rawLength); for (var i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], { type: contentType }); }