util_ng.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. angular.module('app.util', [])
  2. .service('FlotServ', FlotServ)
  3. .directive('myFlot', myFlot)
  4. .directive('ngEnter', ngEnter)
  5. .filter('formatSize', formatSize);
  6. function formatSize() {
  7. return function(input, standard) {
  8. input = input;
  9. var size = parseFloat(input);
  10. if (standard) {
  11. standard = standard.toLowerCase();
  12. }
  13. if(size <= 1){
  14. return size.toFixed(3);
  15. }
  16. var n = 0,
  17. base = standard == 'si' ? 1000 : 1024,
  18. prefixes = ' KMGTPEZY';
  19. if (size >= base) {
  20. n = Math.floor( Math.log(size) / Math.log(base) );
  21. if (n >= prefixes.length) {
  22. return 'N/A';
  23. }
  24. size = ( size / Math.pow(base, n) ).toFixed(3) * 1 + '';
  25. }else{
  26. size = size.toFixed(3)
  27. }
  28. return size + prefixes[n] + ( n && standard == 'iec' ? 'i' : '' ) + '';
  29. };
  30. }
  31. function myFlot(FlotServ) {
  32. var link = function($scope, $element, $attrs) {
  33. // 这里的值是异步的, 刚开始是空的, 需要watch一下
  34. var flot;
  35. var loadingIcon = $('#loading-container');
  36. loadingIcon.show();
  37. var type = $attrs.type; // s: 小图模式, b: 大图模式
  38. var el;
  39. if (type === 's') {
  40. el = $element.find('.chart-container-multi');
  41. } else if (type === 'b') {
  42. el = $element.find('.chart-container-big');
  43. }
  44. el.html('<span class="loading">载入中</span>');
  45. var legendContainer = $element.find('.legend');
  46. var data;
  47. var dataBak;
  48. $scope.$watch('config', function(val) {
  49. if (val && val.length) {
  50. // 这里的 数据需要排序, 貌似angular把这里的顺序弄乱了
  51. data = FlotServ.sortData(val);
  52. dataBak = angular.copy(data);
  53. // console.log('1', JSON.stringify(data));
  54. // 如果这里面有sum的话, 设置 stack 为true
  55. // laiwei:暂时不用stack
  56. // var stack = _.some(data, function(d) {
  57. // return d.label === 'sum';
  58. // });
  59. var stack = false;
  60. flot = $.plot(el, data, FlotServ.getConfig({legend: legendContainer, stack: stack}));
  61. }
  62. loadingIcon.hide();
  63. el.find('.loading').remove();
  64. });
  65. $element.parents().find('.reset-zoom').on('click', function(e) {
  66. flot.shutdown();
  67. loadingIcon.show();
  68. var data = angular.copy(dataBak); // copy一份, 重新渲染
  69. // console.log('2', JSON.stringify(data));
  70. // 如果这里面有sum的话, 设置 stack 为true
  71. // laiwei:暂时不用stack
  72. // var stack = _.some(data, function(d) {
  73. // return d.label === 'sum';
  74. // });
  75. var stack = false;
  76. flot = $.plot(el, data, FlotServ.getConfig({legend: legendContainer, stack: stack}));
  77. loadingIcon.hide();
  78. });
  79. // watch新添加的数据
  80. $scope.$watch('newdata', function(val) {
  81. if (val && val.length) {
  82. val = FlotServ.sortData(val);
  83. // console.log('2', JSON.stringify(val));
  84. // 在这里把新的数据拼到旧数据里
  85. // 例: 旧的数据 [1,2,3], 新数据 [2,3,4] [1,2,3]等
  86. // console.log('2', data);
  87. for (var si in data) {
  88. // 这里顺序又乱了... 为什么...
  89. var series = data[si];
  90. series = FlotServ.sortData([data[si]])[0];
  91. // console.log('2.5', JSON.stringify(series));
  92. var last = series.data[series.data.length-1][0];
  93. // console.log('3', last);
  94. for (var di in val) {
  95. var label = val[di].label;
  96. var d = val[di].data;
  97. if (series.label === label) {
  98. for (var idx in d) {
  99. if (d[idx][0] > last) {
  100. data[si].data.push(d[idx]);
  101. }
  102. }
  103. }
  104. }
  105. }
  106. // console.log('3', data);
  107. flot.setData(data);
  108. flot.draw();
  109. }
  110. });
  111. el.on('plothover', function (event, pos, item) {
  112. // console.log('1111');
  113. if (item) {
  114. // console.log('2222');
  115. // var x = item.datapoint[0].toFixed(2),
  116. var x = moment(item.datapoint[0]).format('YYYY-MM-DD HH:mm:ss'),
  117. y = item.datapoint[1].toFixed(3);
  118. $('#tooltip').html(item.series.label + '<br>' + x + '<br>' + y)
  119. .css({top: item.pageY+5, left: item.pageX+5})
  120. .fadeIn(200);
  121. // console.log('3333');
  122. } else {
  123. $('#tooltip').hide();
  124. }
  125. });
  126. el.bind("plotselected", function (event, ranges) {
  127. // $("#selection").text(ranges.xaxis.from.toFixed(1) + " to " + ranges.xaxis.to.toFixed(1));
  128. $.each(flot.getXAxes(), function(_, axis) {
  129. var opts = axis.options;
  130. opts.min = ranges.xaxis.from;
  131. opts.max = ranges.xaxis.to;
  132. });
  133. flot.setupGrid();
  134. flot.draw();
  135. flot.clearSelection();
  136. });
  137. };
  138. return {
  139. link: link,
  140. restrict: 'A',
  141. scope: {
  142. config: '=',
  143. newdata: '='
  144. }
  145. };
  146. }
  147. function ngEnter() {
  148. return function (scope, element, attrs) {
  149. element.bind("keydown keypress", function (event) {
  150. if(event.which === 13) {
  151. scope.$apply(function (){
  152. scope.$eval(attrs.ngEnter);
  153. });
  154. event.preventDefault();
  155. }
  156. });
  157. };
  158. }
  159. function FlotServ($http, $window, $q) {
  160. var self = this;
  161. // flot config
  162. self.getConfig = function(options) {
  163. return {
  164. stack: options.stack || false,
  165. // 使用深色色彩可选值, 避免因为绘图线条颜色太浅看不清楚
  166. colors: [
  167. "#FF6A6A", "#00BFFF", "#A52A2A",
  168. "#CDCD00", "#008878", "#FF0000",
  169. "#00FF00", "#7B68EE", "#FF00FF",
  170. "#EEAEEE", "#00AEEE", "#AEEEEE",
  171. "#FFB90F", "#00B90F", "#00FFFF",
  172. "#DC143C", "#BFEFFF", "#AA7500",
  173. "#F0E68C", "#00E68C", "#AAE68C",
  174. "#EE9A49", "#009A49", "#AA9A49",
  175. "#FFA54F", "#00A54F", "#AAA54F",
  176. "#8B4789", "#004789", "#AA4789",
  177. "#00CDCD", "#00CDCD", "#AACDCD",
  178. "#EE8262", "#008262", "#AA8262",
  179. "#FF8C00", "#008C00", "#AA8C00",
  180. "#8B3626", "#003626", "#AA3626",
  181. "#00BFFF", "#00E8AA", "#AAE8AA",
  182. "#EE7621", "#007621", "#AA7621",
  183. ],
  184. lines: {
  185. show: true
  186. },
  187. points: {
  188. show: true,
  189. show: true,
  190. radius: 0.2,
  191. lineWidth: 1,
  192. fill:true,
  193. fillColor: "rgba(215, 234, 252, 0.8)"
  194. },
  195. xaxis: {
  196. mode: 'time',
  197. timezone: 'browser',
  198. color: "#EAEAEA",
  199. font: {
  200. size: 10,
  201. weight: "bold",
  202. color: "#ACABAB",
  203. family: "sans-serif",
  204. variant: "small-caps"
  205. }
  206. // tickDecimals: 0,
  207. // tickSize: 1
  208. },
  209. series: {
  210. shadowSize: 0 // Drawing is faster without shadows
  211. },
  212. yaxis: {
  213. // min: 0
  214. // max: 100
  215. color: "#EAEAEA",
  216. font: {
  217. size: 10,
  218. weight: "bold",
  219. color: "#ACABAB",
  220. family: "sans-serif",
  221. variant: "small-caps"
  222. }
  223. },
  224. grid: {
  225. hoverable: true,
  226. clickable: true,
  227. borderWidth: 0.5,
  228. borderColor: "#EAEAEA"
  229. },
  230. selection: {
  231. mode: "x"
  232. },
  233. legend: {
  234. show: true,
  235. // position: 'nw',
  236. container: options.legend,
  237. labelFormatter: function(label, series) {
  238. return label;
  239. // return label + '<input type='checkbox' value='' + label + ''>';
  240. // return null;
  241. }
  242. }
  243. }
  244. };
  245. // send ajax
  246. self.getData = function(url, params) {
  247. return $http({method: 'GET', url: url, params: params});
  248. };
  249. // 首次请求的参数
  250. self.getParam = function() {
  251. return $window.obj;
  252. };
  253. // 后续请求的参数, 定时的那个
  254. self.getParam2 = function() {
  255. return $window.obj2;
  256. };
  257. // 数据url
  258. self.getUrls = function() {
  259. return $window.urls;
  260. };
  261. // 多图时, 每个图的id
  262. self.getIds = function() {
  263. return $window.ids;
  264. };
  265. self.getMultiDataById = function(param) {
  266. var ids = self.getIds();
  267. var reqs = _.map(ids, function(id) {
  268. var p = angular.copy(param);
  269. if (angular.isDate(p.start_s)) {
  270. p.start_s = +p.start_s/1000;
  271. }
  272. if (angular.isDate(p.end_s)) {
  273. p.end_s = +p.end_s/1000;
  274. }
  275. p.id = id;
  276. return $http({method: 'GET', url: '/chart/' + p.graph_type, params: p});
  277. });
  278. return $q.all(reqs);
  279. };
  280. // 数据请求
  281. self.getMultiData = function() {
  282. var urls = self.getUrls();
  283. var reqs = _.map(urls, function(u) {
  284. return $http({method: 'GET', url: u});
  285. });
  286. return $q.all(reqs);
  287. };
  288. // parse response data
  289. self.parseData = function(ret) {
  290. var data = [];
  291. var len = ret.series.length;
  292. for (var i = 0, l = len; i < l; i ++) {
  293. var v = ret.series[i];
  294. data.push({label: v.name, data: v.data, check: true});
  295. // if (v.name === 'sum') {
  296. // data.push({label: v.name, data: v.data, check: true, lines: {fill: true}});
  297. // } else {
  298. // data.push({label: v.name, data: v.data, check: true});
  299. // }
  300. }
  301. return data;
  302. };
  303. // get max, min, avg, sum
  304. self.summary = function(series) {
  305. var d = series.data;
  306. // 去掉值中的null
  307. d = _.filter(d, function(i) {
  308. return i[1] !== null;
  309. });
  310. // 这里的数据结构是 [timestamp, value]
  311. var last = d[d.length-1][1];
  312. var max = _.max(d, function(i) {return i[1]})[1];
  313. var min = _.min(d, function(i) {return i[1]})[1]
  314. var sum = sum = _.reduce(d, function(memo, i) {return memo + i[1]}, 0);
  315. var avg = (sum/d.length);
  316. var sorted = d.sort(function(a,b) {return a[1]-b[1]});
  317. var th95 = sorted[parseInt(d.length*0.95, 10)][1];
  318. var th99 = sorted[parseInt(d.length*0.99, 10)][1];
  319. return {
  320. last: last,
  321. max: max,
  322. min: min,
  323. sum: sum,
  324. avg: avg,
  325. th95: th95,
  326. th99: th99
  327. };
  328. };
  329. // sort data by timestamp
  330. self.sortData = function(data) {
  331. _.each(data, function(d) {
  332. d.data = d.data.sort(function(a, b) {
  333. return a[0] - b[0];
  334. });
  335. });
  336. return data;
  337. };
  338. }