jinpengyong
2020-12-04 e294ea312fe1994c3ddfe26595ee414e6612eb0c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
package com.moral.controller;
 
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
 
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import com.moral.common.bean.Constants;
import com.moral.common.bean.JsonData;
import com.moral.common.bean.PageResult;
import com.moral.common.bean.ResultBean;
import com.moral.common.util.BeanUtils;
import com.moral.common.util.ParameterUtils;
import com.moral.common.util.ValidateUtil;
import com.moral.common.util.WebUtils;
import com.moral.common.xml.Version;
import com.moral.entity.*;
import com.moral.entity.alarm.AlarmConfig;
import com.moral.entity.alarm.AlarmConfigValue;
import com.moral.entity.alarm.AlarmSensorLevel;
import com.moral.entity.charts.DataSortCondition;
import com.moral.entity.layout.RealTimeDeviceLayout;
import com.moral.mapper.HistoryMapper;
import com.moral.service.*;
import com.moral.util.*;
 
import com.rabbitmq.client.*;
import com.rabbitmq.client.Channel;
 
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import jdk.nashorn.internal.runtime.regexp.joni.Regex;
import net.sf.json.JSONString;
 
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.xml.sax.InputSource;
 
import static com.moral.common.util.ResourceUtil.getValue;
import static com.moral.common.util.WebUtils.getParametersStartingWith;
import static java.util.Calendar.*;
 
/**
 * The Class ScreenController.大屏接口
 */
@RestController
@RequestMapping("/screen")
@CrossOrigin(origins = "*", maxAge = 3600)
@SuppressWarnings({"rawtypes", "unchecked", "unused"})
@Api(tags = "Screen", description = "大屏接口")
public class ScreenController {
    public static Logger log = Logger.getLogger(ScreenController.class);
 
    @Resource
    private HistoryMapper historyMapper;
    @Resource
    AlarmConfigService alarmConfigService;
    @Resource
    AreaService areaService;
 
    @Resource
    SensorService sensorService;
    @Resource
    SensorUnitService sensorUnitService;
    @Resource
    MonitorPointService monitorPointService;
    @Resource
    DeviceVersionService deviceVersionService;
 
  /*  @Resource
    HistorySpecialService historySpecialService;*/
 
    /**
     * The screen service.
     */
    @Resource
    private HistoryService historyService;
 
    /**
     * The account service.
     */
    @Resource
    private AccountService accountService;
 
    /**
     * The device service.
     */
    @Resource
    private DeviceService deviceService;
 
    @Resource
    private HistoryHourlyService historyHourlyService;
 
    @Resource
    private HistoryMinutelyService historyMinutelyService;
 
    @Resource
    private MachineActivateService machineActivateService;
 
    /** The resource. */
//    @Value(value = "classpath:system/alarmLevels.json")
//    private org.springframework.core.io.Resource resource;
 
    /**
     * The redis template.
     */
    @Resource
    private RedisTemplate<String, String> redisTemplate;
 
    /**
     * The level key.
     */
    private String levelKey = "alarm_";
 
    @Resource
    private AlarmDailyService alarmDailyService;
    @Resource
    private OrganizationLayoutService orgLayoutService;
    @Resource
    private DeviceVersionService dviceVersionService;
    @Resource
    private OrganizationService organizationService;
    @Resource
    private DictionaryDataService dictionaryDataService;
 
    @Resource
    private WeatherService weatherService;
 
    @Resource
    private QualityDailyService qualityDailyService;
 
    @Resource
    private DeviceRoadService deviceRoadService;
 
    @Resource
    private ScreenVersionService screenVersionService;
 
    @Resource
    private DeviceAdjustValueTimingService deviceAdjustValueTimingService;
 
    /**
     * Screen login. 大屏登录
     *
     * @param request the request
     * @return the map
     */
    @GetMapping("login")
    public Map<String, Object> screenLogin(HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        if (!(parameters.containsKey("account") && parameters.containsKey("password"))) {
            resultMap.put("msg", "用户名及密码不允许为空!");
            resultMap.put("accountId", -1);
        } else {
            resultMap = accountService.screenLogin(parameters);
            // 添加返回行政区信息字符串操作
            Object orgId = resultMap.get("orgId");
            if (resultMap.get("orgId") != null && resultMap.get("orgId") instanceof Integer) {
                StringBuilder areaNamesBuilder = new StringBuilder("中国");
                if (!((Integer) orgId).equals(dictionaryDataService.querySupperOrgId())) {
                    Organization organization = organizationService.getOrganizationById((Integer) orgId);
                    if (organization.getAreaNames() != null) {
                        Map<String, String> areaNameMap = BeanUtils.beanToMap(organization.getAreaNames());
                        List<String> names = areaNameMap.entrySet().stream().filter(item -> {
                            return item.getValue() != null;
                        }).map(item -> {
                            return item.getValue();
                        }).collect(Collectors.toList());
                        AreaNames areaNames = organization.getAreaNames();
                        areaNamesBuilder.append("/");
                        areaNamesBuilder.append(String.join("/", names));
                    }
                    // 企业用户
                    if (organization.getRank() != null && organization.getRank() == 0) {
                        resultMap.put("type", "enterprise");
                    } else {
                        resultMap.put("type", "government");
                    }
                    Number mapAreaCode = null;
                    if (organization.getVillageCode() != null) {
                        mapAreaCode = organization.getVillageCode();
                    } else if (organization.getTownCode() != null) {
                        mapAreaCode = organization.getTownCode();
                    } else if (organization.getAreaCode() != null) {
                        mapAreaCode = organization.getAreaCode();
                    } else if (organization.getCityCode() != null) {
                        mapAreaCode = organization.getCityCode();
                    } else if (organization.getProvinceCode() != null) {
                        mapAreaCode = organization.getProvinceCode();
                    }
                    resultMap.put("mapAreaCode", mapAreaCode.toString());
                }
                resultMap.put("mapPath", areaNamesBuilder.toString());
            }
        }
        return resultMap;
    }
 
    @GetMapping("loginNew")
    public Map<String, Object> screenLoginNew(HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        if (!(parameters.containsKey("account") && parameters.containsKey("password"))) {
            resultMap.put("msg", "用户名及密码不允许为空!");
            resultMap.put("accountId", -1);
        } else {
            resultMap = accountService.screenLoginNew(parameters);
            // 添加返回行政区信息字符串操作
            Object orgId = resultMap.get("orgId");
            if (resultMap.get("orgId") != null && resultMap.get("orgId") instanceof Integer) {
                StringBuilder areaNamesBuilder = new StringBuilder("中国");
                if (!((Integer) orgId).equals(dictionaryDataService.querySupperOrgId())) {
                    Organization organization = organizationService.getOrganizationById((Integer) orgId);
                    if (organization.getAreaNames() != null) {
                        Map<String, String> areaNameMap = BeanUtils.beanToMap(organization.getAreaNames());
                        List<String> names = areaNameMap.entrySet().stream().filter(item -> {
                            return item.getValue() != null;
                        }).map(item -> {
                            return item.getValue();
                        }).collect(Collectors.toList());
                        AreaNames areaNames = organization.getAreaNames();
                        areaNamesBuilder.append("/");
                        areaNamesBuilder.append(String.join("/", names));
                    }
                    // 企业用户
                    if (organization.getRank() != null && organization.getRank() == 0) {
                        resultMap.put("type", "enterprise");
                    } else {
                        resultMap.put("type", "government");
                    }
                    Number mapAreaCode = null;
                    if (organization.getVillageCode() != null) {
                        mapAreaCode = organization.getVillageCode();
                    } else if (organization.getTownCode() != null) {
                        mapAreaCode = organization.getTownCode();
                    } else if (organization.getAreaCode() != null) {
                        mapAreaCode = organization.getAreaCode();
                    } else if (organization.getCityCode() != null) {
                        mapAreaCode = organization.getCityCode();
                    } else if (organization.getProvinceCode() != null) {
                        mapAreaCode = organization.getProvinceCode();
                    }
                    resultMap.put("mapAreaCode", mapAreaCode.toString());
                }
                resultMap.put("mapPath", areaNamesBuilder.toString());
            }
        }
        return resultMap;
    }
 
    /**
     * Gets the equipment states. 获取该账号下所有设备的状态
     *
     * @param request the request
     * @return the equipment states
     */
    @GetMapping("/equipment-state")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public Map<String, Object> getDeviceStatesByAccount(HttpServletRequest request) {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        return deviceService.getDeviceStatesByAccount(parameters);
    }
 
    /**
     * Gets the alarm levels. 获取报警配置
     *
     * @param request the request
     * @return the alarm levels
     */
    @GetMapping("alarm-levels")
    public Object getAlarmLevels(HttpServletRequest request, Optional<Integer> orgId, Optional<Integer> mpId,
                                 Optional<String> mac) {
        List<Map<String, Object>> sensorAlarmList = null;
        try {
            AlarmConfig alarmConfig = null;
            if (orgId.isPresent()) {
                alarmConfig = alarmConfigService.queryValueByOrganizationId(orgId.get()).get();
            } else if (mpId.isPresent()) {
                alarmConfig = alarmConfigService.queryByMonitorPointId(mpId.get()).get();
            } else if (mac.isPresent()) {
                alarmConfig = alarmConfigService.queryByDeviceMac(mac.get()).get();
            }
            // 返回值处理
            if (alarmConfig.getValue() != null && alarmConfig.getValue().getAlarmLevels() != null) {
                Map<String, AlarmSensorLevel> alarmLevelMap = alarmConfig.getValue().getAlarmLevels();
                // 当前非取默认值,未设值将用默认值覆盖
                Map<String, AlarmSensorLevel> defaultSensorLevelMap = null;
                if (alarmConfig.getId() != null) {
                    AlarmConfigValue defaultAlarmValue = alarmConfigService.getDefaultAlarmConfigValue();
                    defaultSensorLevelMap = defaultAlarmValue.getAlarmLevels();
                }
                Map<String, AlarmSensorLevel> finalDefaultSensorLevelMap = defaultSensorLevelMap;
                alarmLevelMap.entrySet().stream().forEach(entry -> {
                    // 当 increment都为0时,替换为默认值
                    AlarmSensorLevel alarmSensorLevel = entry.getValue();
                    if (alarmSensorLevel.getIncrement() != null) {
                        boolean isAllZero = alarmSensorLevel.getIncrement().stream().allMatch(item -> item == 0);
                        if (isAllZero) {
                            AlarmSensorLevel defaultAlarmSensorLevel = finalDefaultSensorLevelMap == null ? null
                                    : finalDefaultSensorLevelMap.get(entry.getKey());
                            if (defaultAlarmSensorLevel != null) {
                                alarmSensorLevel.setIncrement(defaultAlarmSensorLevel.getIncrement());
                            } else {
                                List<Float> tempList = Arrays.asList(0.0f, 200.0f, 500.0f);
                                alarmSensorLevel.setIncrement(tempList);
                            }
                        }
                    }
                });
                // map to list
                Map<String, AlarmSensorLevel> finalAlarmLevelMap = alarmLevelMap;
                sensorAlarmList = alarmLevelMap.keySet().stream().map(key -> {
                    AlarmSensorLevel alarmSensorLevel = finalAlarmLevelMap.get(key);
                    Map<String, Object> alarmSensorLevelMap = new HashMap<>(BeanMap.create(alarmSensorLevel));
                    alarmSensorLevelMap.put("key", key);
                    return alarmSensorLevelMap;
                }).collect(Collectors.toList());
            } else {
                return new ResultBean<>("提供参数有误,未查询到任何数据", ResultBean.FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> err = new LinkedHashMap<String, Object>();
            err.put("msg", "系统错误,请联系管理员!原因如下:" + e.getMessage());
            return err;
        }
        return sensorAlarmList;
    }
 
    /**
     * Gets the standard by sensor.获取某传感器标准值
     *
     * @param macKey the request
     * @return the standard by sensor
     */
    @GetMapping("sensor-standard")
    public Map<String, Object> getStandardBySensor(@RequestParam("macKey") String macKey) {
        ValidateUtil.notEmpty(macKey, "param.is.null");
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("standard", getValue(macKey + "-standard"));
        return result;
    }
 
    /**
     * @param dataSortCondition 数据排名查询条件
     * @return
     */
    public ResultBean<Map<String, Object>> getOrderData(DataSortCondition dataSortCondition) {
        ResultBean resultBean = new ResultBean();
        if (dataSortCondition.getCode() == null) {
            resultBean.setCode(ResultBean.FAIL);
            resultBean.setMessage("code can't be null");
        } else if (dataSortCondition.getStyle() == null) {
            resultBean.setCode(ResultBean.FAIL);
            resultBean.setMessage("style can't be null");
        }
        String code = dataSortCondition.getCode().toString();
        Region region = Region.create(code);
        if (region == null) {
            resultBean.setCode(ResultBean.FAIL);
            resultBean.setMessage("code is not in the correct format");
        }
        // todo
        return null;
    }
 
    /**
     * Gets the day AQI by sensor.设备昨日的AQI指标
     *
     * @param request the request
     * @return the day AQI by sensor
     */
    @GetMapping("day-aqi")
    public Map<String, Object> getDayAQIByDevice(HttpServletRequest request) {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        return historyMinutelyService.getDayAQIByDevice(parameters);
    }
 
    @GetMapping("hour-aqi")
    @ApiOperation(value = "获取一小时AQI", notes = "获取一小时AQI")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "mac", value = "设备mac地址", required = true, paramType = "query", dataType = "String")
    })
    public Map<String, Object> getHourAQIByDevice(HttpServletRequest request) {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        return historyService.gitHourlyAQIByMacAndTimeslot(parameters);
    }
 
    /**
     * Gets the average by all. 获取某账号某区域10分钟前到5分钟前所有传感器平均数值排名
     *
     * @param request the request
     * @return the average by all
     * @throws Exception
     */
    @GetMapping("all-average")
    public Map<String, Object> getAllSensorAverageByDevice(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        return historyService.getAllSensorAverageByDevice(parameters);
    }
 
    /**
     * Gets the average by sensor.某个传感器一小时内所有设备排名
     *
     * @param request the request
     * @return the average by sensor
     */
    @GetMapping("sensor-average")
    public Map<String, Object> getDeviceRankingBySensorAverage(HttpServletRequest request) {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        return historyService.getDeviceRankingBySensorAverage(parameters);
    }
 
    /**
     * Gets the month average by sensor.设备传感器本月平均值
     *
     * @param request the request
     * @return the month average by sensor
     */
    @GetMapping("month-sensor-average")
    public Map<String, Object> getMonthAverageBySensor(HttpServletRequest request) {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        return historyMinutelyService.getAverageBySensor(parameters);
    }
 
    @GetMapping("check-activate")
    public ResultBean<Integer> checkActivate(String macCpuCode) {
        Integer result = machineActivateService.checkActivate(macCpuCode);
        return new ResultBean<Integer>(result);
    }
 
    @PostMapping("activate-machine")
    public ResultBean<Integer> activateMachine(HttpServletRequest request) {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        Integer result = machineActivateService.activateMachine(parameters);
        return new ResultBean<Integer>(result);
    }
 
    /*********************************************
     * 大屏程序在线升级配置读取
     *********************************************/
    private String fileName = "Version.xml";
    private String ip = "47.96.19.115";
    private String userName = "ftp_user";
    private String userPwd = "qwer1234";
    private int port = 21;
    private String path = "/";
 
    @RequestMapping(value = "/upgrade", method = RequestMethod.GET)
    public Version index() {
        Version version = new Version();
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip, port);
            ftpClient.login(userName, userPwd);
            ftpClient.changeWorkingDirectory(path);
            ftpClient.enterLocalPassiveMode();
            // ftpClient.enterLocalActiveMode();
 
            InputStream ins = ftpClient.retrieveFileStream(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(ins, "utf-8"));
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            reader.close();
            if (ins != null) {
                ins.close();
            }
            ftpClient.getReply();
            String content = builder.toString();
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
 
//            String urlStr = "http://www.7drlb.com/apps/Version.xml";
//            URL realUrl = new URL(urlStr);
//            URLConnection connection = realUrl.openConnection();
//            connection.connect();
//            StringBuffer result = new StringBuffer();
//            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
//            String line;
//            while ((line = in.readLine()) != null) {
//                result.append(line);
//            }
//            String content = result.toString();
 
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(new InputSource(new ByteArrayInputStream(content.getBytes("utf-8"))));
            Element root = document.getRootElement();
            version.setVer(root.element("Ver").getText());
            version.setFileName(root.element("FileName").getText());
            version.setFileMD5Hash(root.element("FileMD5Hash").getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }
 
    public static void main(String[] args) {
        ScreenController sc = new ScreenController();
        Version a = sc.index();
        System.out.println(a.getVer());
    }
 
    /**
     * 地图接口 开始
     */
    /**
     * 地图主页
     *
     * @param model
     * @param code
     * @param accountId
     * @return
     */
    @RequestMapping(value = "/map-page", method = RequestMethod.GET)
    public ModelAndView map(ModelAndView model, @RequestParam("areaCode") long code,
                            @RequestParam("accountId") int accountId) {
        Account account = accountService.getAccountById(accountId);
        String regionName = areaService.queryFullNameByCode(code);
        if (account != null && regionName != null) {
            Object sensors = sensorService.queryAll();
            JSONObject params = new JSONObject();
            params.put("regionCode", code);
            params.put("regionName", regionName);
            params.put("accountId", accountId);
            params.put("orgId", account.getOrganizationId());
            params.put("sensors", sensors);
            String paramsJson = params.toJSONString();
            model.addObject("mapParams", paramsJson);
            model.setViewName("map");
            return model;
        } else {
            StringBuilder msg = new StringBuilder();
            msg.append(" param[0] areaCode:");
            msg.append(code);
            msg.append(" param[0] accountId:");
            msg.append(accountId);
            log.warn(msg);
            model.setViewName("403");
            return model;
        }
    }
 
    @GetMapping("/getSensorsMap")
    public List<Map<String, String>> getSensorsMapOnly(String mac) {
        List<Map<String, String>> sensorsMapList = sensorService.getSensorsMaps(mac);
        return sensorsMapList;
    }
 
    @GetMapping("/getSensorsAllMap")
    public List<Map<String, String>> getSensorsAllMap(String mac) {
        List<Map<String, String>> sensorsMapList = sensorService.getSensorsAllMap();
        return sensorsMapList;
    }
 
    @RequestMapping(value = "/get-monitorpoints", method = RequestMethod.GET)
    @ResponseBody
    public ResultBean getMonitorpointList(@RequestParam("orgId") String orgId, MapBounds mapBounds,
                                          @RequestParam("regionCode") String regionCode) {
        ResultBean<List<MonitorPoint>> resultBean = new ResultBean();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("orgId", orgId);
        paramMap.put("mapBounds", mapBounds);
        paramMap.put("regionCode", regionCode);
        ParameterUtils.getRegionType4RegionCode(paramMap);
        List<MonitorPoint> list = monitorPointService.queryWithStateByMap(paramMap);
        resultBean.setData(list);
        resultBean.setCode(ResultBean.SUCCESS);
        return resultBean;
    }
 
    @RequestMapping(value = "/get-devices", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "设备信息", notes = "设备信息")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "orgId", defaultValue = "5", value = "组织Id", required = true, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "regionCode", defaultValue = "320583", value = "地区编码", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "Fe", defaultValue = "31.485018", value = "东北角纬度", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "Ge", defaultValue = "121.378395", value = "东北角经度", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "Ke", defaultValue = "31.296614", value = "西南角纬度", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "Le", defaultValue = "120.59651", value = "西南角经度", required = true, paramType = "query", dataType = "String")
    })
    public ResultBean getDevices(@RequestParam("orgId") Integer orgId, MapBounds mapBounds,
                                 @RequestParam("regionCode") String regionCode) {
        ResultBean<List<Device>> resultBean = new ResultBean();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("orgId", orgId);
        paramMap.put("mapBounds", mapBounds);
        paramMap.put("regionCode", regionCode);
        ParameterUtils.getRegionType4RegionCode(paramMap);
        List<Device> list = deviceService.query(paramMap);
        resultBean.setData(list);
        resultBean.setCode(ResultBean.SUCCESS);
        return resultBean;
    }
 
    @RequestMapping(value = "get-devices-for-popup", method = RequestMethod.GET)
    @ResponseBody
    public PageResult getDevicesForPopup(@RequestParam("orgId") Integer orgId, String name, Integer pageSize,
                                         Integer pageNo) {
        return deviceService.query(orgId, name, pageSize, pageNo);
    }
 
    @RequestMapping(value = "get-devices-by-mid-oid", method = RequestMethod.GET)
    @ResponseBody
    public PageResult getDevicesByMidOid(@RequestParam("orgId") Integer orgId, @RequestParam("mpId") Integer mpId,
                                         Integer pageSize, Integer pageNo) {
        return deviceService.query(orgId, mpId, pageSize, pageNo);
    }
 
    @RequestMapping(value = "/get-real-state-data", method = RequestMethod.POST)
    @ResponseBody
    public JsonData getRealStateAndData(@RequestBody JSONObject paramMap) {
        JsonData jsonData = new JsonData();
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("layer", paramMap.getString("layer"));
        // 覆盖控件的数据刷新
        if (!CollectionUtils.isEmpty(paramMap.getJSONArray("markerKeys"))) {
            JSONArray markerKeys = paramMap.getJSONArray("markerKeys");
            List<Map<String, String>> markers = null;
            if ("equipments".equals(paramMap.getString("layer"))) {
                markers = deviceService.queryDevicesState(markerKeys.toJavaList(String.class), true);
            } else {// 返回监控点id和state
                String orgId = paramMap.getString("orgId");
                String areaCode = paramMap.getString("areaCode");
                for (Object mPointId : markerKeys) {
                    markers = monitorPointService.queryMonitroPointsState(markerKeys.toJavaList(Integer.class));
                }
            }
            returnMap.put("markers", markers);
        }
        if (paramMap.getJSONArray("popupEquMacs") != null && paramMap.getJSONArray("popupEquMacs").size() > 0) {
            JSONArray popupEquMacs = paramMap.getJSONArray("popupEquMacs");
            List<Map<String, String>> popupEquWithStates = null;
            for (Object mac : popupEquMacs) {
                popupEquWithStates = deviceService.queryDevicesState(popupEquMacs.toJavaList(String.class), false);
            }
            // 返回搜索结果的状态
            returnMap.put("popupEquStates", popupEquWithStates);
        }
        jsonData.setExtData(returnMap);
        return jsonData;
    }
 
    @GetMapping("monitor_points")
    public ResultBean<List<MonitorPoint>> getMonitorPointsByOrganizationId(Integer orgId) {
        // Map<String, Object> parameters = getParametersStartingWith(request, null);
        List<MonitorPoint> monitorPoints = monitorPointService.getMonitorPointsByOrganizationId(orgId);
        return new ResultBean<List<MonitorPoint>>(monitorPoints);
    }
 
 
    /*
     * 参数:monitorPoint=368&mac=p5dnd7a0392018&sensorKey=e92&time=2020-08-11
     * 获取传感器均值接口
     * */
    @GetMapping("report_avg_datas")
    public ResultBean<List<Map<String, Object>>> getMonitorPointOrDeviceAvgData(HttpServletRequest request)
            throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        //该方法用于判断时间是具体到年月日
        ParameterUtils.getTimeType4Time(parameters);
        String time1 = (String) parameters.get("time");
        time1 = time1.replaceAll(" ", "");
        parameters.put("time",time1);
 
        String mac1 = (String) parameters.get("mac");
        List<Map<String, Object>> list = null;
        if (mac1 != null && mac1.equals("p5dnd7a0392018") && time1.substring(0, 4).equals("2019")) {
            list = null;
        } else {
            parameters.put("monitorPointId", parameters.remove("monitorPoint"));
            Object sensorKey = parameters.remove("sensorKey");
            parameters.put("sensors", Arrays.asList(sensorKey));
            // monitorPointService.isCompensateCalculation(parameters);
            list = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters);
 
 
            /* 0点的数据是昨天11点到今天0点的,界面显示1-24点的,所以不需要0点的数据,但需要单独查询24点的数据
                因为改动以前24点的数据是23-24,现在24点的数据是第二天0点的数据,
             */
            /*改动范围start-------------------------------------------------------------------------*/
            list.remove(0);
            //if (list.size() == 23) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                //获取全格式时间yyyy-MM-dd HH:mm:ss
                time1 = time1 + " 00:00:00";
                Date date = sdf.parse(time1);
                date = DateUtil.rollDay(date, 1);
                //将全格式时间截取
                String time2 = sdf2.format(date);
                parameters.put("time", time2);
                /*查询第二天0点的数据,以24点的形式存进集合中*/
                List<Map<String, Object>> nextDayList = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters);
                if(!ObjectUtils.isEmpty(nextDayList)){
                    time1=time1.replaceAll(" 00:00:00"," 24");
                    Map<String, Object> datas = nextDayList.get(0);
                    datas.put("time",time1);
                    list.add(datas);
                }
            //}
            /*改动范围end-------------------------------------------------------------------------*/
 
 
            for (Map<String, Object> map : list) {
                String time = map.get("time").toString();
                time = time.substring(time.length() - 2);
                map.put("time", Integer.valueOf(time));
             /*   if (parameters.get("type").equals("day")) {
                    map.put("time", Integer.valueOf(time) + 1);
                }*/
                map.put("value", map.remove(sensorKey));
            }
        }
        return new ResultBean<List<Map<String, Object>>>(list);
    }
 
 
    @GetMapping("report_alarm_datas")
    public ResultBean<List<Map<String, Object>>> getAlarmData(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        ParameterUtils.getTimeType4Time(parameters);
        // parameters.put("type", "month");
        String sensorKey = "list";
        if (ObjectUtils.isEmpty(parameters.get("sensorKey"))) {
            parameters.put("description", "description");
        } else {
            sensorKey = parameters.remove("sensorKey").toString();
            List<String> sensorKeys = new ArrayList<String>();
            sensorKeys.add(sensorKey);
            parameters.put("sensors", sensorKeys);
        }
        if (!ObjectUtils.isEmpty(parameters.get("organizationId"))) {
            if (!Constants.isNotSpecialOrgId(Integer.valueOf(parameters.get("organizationId").toString()))) {
                parameters.remove("organizationId");
            }
        }
        Map pieData = alarmDailyService.getPieData(parameters);
        List<Map<String, Object>> list = (List<Map<String, Object>>) pieData.get(sensorKey);
        return new ResultBean<List<Map<String, Object>>>(list);
    }
 
    /**
     * 根据监控点id获取所属设备version数据集
     *
     * @param mptid
     * @return
     */
    @GetMapping("getvers")
    public ResultBean<List<Integer>> getVersions(Integer mptid) {
        return new ResultBean<>(monitorPointService.queryVersionsById(mptid));
    }
 
    @GetMapping("region_ranking_data")
    @ApiOperation(value = "获取排名数据", notes = "获取排名数据")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "regionCode", value = "区域码", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "dimension", value = "维度(profession、region、monitorPoint选一)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "accountId", value = "账户id", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "timeType", value = "时间类型(month、day、hour选一)", required = true, paramType = "query", dataType = "int"),})
    public ResultBean<List<Map<String, Object>>> getRegionRankingData(HttpServletRequest request) {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        List<Map<String, Object>> list = historyService.getRegionRankingData(parameters);
        return new ResultBean<List<Map<String, Object>>>(list);
    }
 
    // todo
    @Value(value = "classpath:system/realTimeMonitorLayout.json")
    private org.springframework.core.io.Resource resource;
 
    @ApiOperation(value = "获取实时监控页面布局", notes = "")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "primaryKey", defaultValue = "898607b0101730391967", value = "值为:设备mac或监控站id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "type", defaultValue = "device", value = "值为:'monitorPoint'或'device'", required = true, paramType = "query", dataType = "String"),})
    @GetMapping("rtm-layout")
    public ResultBean realTimeMonitorLayout(String primaryKey, String type) {
        RealTimeDeviceLayout rtdLayout = null;
        if (type != null && type.equals("device")) {
            Device device = deviceService.getDeviceByMac(primaryKey, false);
            if (device != null && device.getOrganizationIds() != null && device.getOrganizationIds().size() > 0
                    && device.getDeviceVersionId() != null) {
                Integer orgId = device.getOrganizationIds().get(0);
                DeviceVersion deviceVersion = deviceVersionService.queryVersionById(device.getDeviceVersionId());
                rtdLayout = orgLayoutService.queryRtdLayoutWithUnit(orgId, deviceVersion.getVersion());
            } else {
                String errMsg = "device 数据异常:" + JSON.toJSONString(device);
                log.warn(errMsg);
                return ResultBean.fail(errMsg);
            }
 
        } else {
            MonitorPoint monitorPoint = monitorPointService.queryMonitorPointById(Integer.parseInt(primaryKey));
            List<DeviceVersion> versionList = deviceVersionService.queryByMpointId(monitorPoint.getId());
            if (versionList.size() > 0) {
                List<Integer> versionNolist = versionList.stream().map(item -> {
                    return item.getVersion();
                }).collect(Collectors.toList());
                rtdLayout = orgLayoutService.queryRtdLayoutWithUnit(monitorPoint.getOrganizationId(), versionNolist);
                if (rtdLayout == null) {
                    return ResultBean.fail();
                }
            }
        }
        if (rtdLayout != null && rtdLayout.getDefaultMonitorItems().size() == 0) {
            rtdLayout.getDefaultMonitorItems().addAll(rtdLayout.getCoreMonitorItems());
        }
        return new ResultBean(rtdLayout == null ? new RealTimeDeviceLayout() : rtdLayout);
    }
 
    @GetMapping("report_avg_data")
    @ApiOperation(value = "获取监测因子月平均值", notes = "获取监测因子月平均值")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitorPoint", value = "监控站id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "mac", value = "设备mac", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "传感器key,如有多个用逗号分隔", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间,月份(格式:2018-03)", required = true, paramType = "query", dataType = "String"),})
    public ResultBean<List<Map<String, Object>>> getMonitorPointOrDeviceAvgDataBySensorKey(HttpServletRequest request)
            throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        ParameterUtils.getTimeType4Time(parameters);
        parameters.put("monitorPointId", parameters.remove("monitorPoint"));
        String[] sensorKeys = parameters.remove("sensorKey").toString().split(",");
        parameters.put("sensors", Arrays.asList(sensorKeys));
        // monitorPointService.isCompensateCalculation(parameters);
        List<Map<String, Object>> list = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters);
 
        for (Map<String, Object> map : list) {
            String time = map.get("time").toString();
            time = time.substring(time.length() - 2);
            map.put("time", Integer.valueOf(time));
            List<Number> values = new ArrayList<Number>();
            for (String string : sensorKeys) {
                values.add((Number) map.remove(string));
            }
            map.put("values", values);
        }
        return new ResultBean<List<Map<String, Object>>>(list);
    }
 
    @GetMapping("report_avg_AreaData")
    @ApiOperation(value = "获取国控因子与监测因子平均值", notes = "获取国控因子与监测因子平均值")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitorPoint", value = "监控站id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "mac", value = "设备mac", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "areaCode", value = "地区代码", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间,月份(格式:2018-03)", required = true, paramType = "query", dataType = "String"),})
    public ResultBean<List<Map<String, Object>>> getAreaAvgDataByAreaCode(HttpServletRequest request)
            throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        ParameterUtils.getTimeType4Time(parameters);
        parameters.put("monitorPointId", parameters.remove("monitorPoint"));
        parameters.put("areaCode", parameters.remove("areaCode"));
        String[] sensorKeys = parameters.remove("sensorKey").toString().split(",");
        String type = parameters.get("type").toString();
        String s = sensorKeys[0];
        parameters.put("sensors", Arrays.asList(sensorKeys));
        parameters.put("sensors2", s);
 
        ArrayList<Map<String, Object>> resultList = new ArrayList<>();
 
        List<Map<String, Object>> monitorList = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters);
        List<Map<String, Object>> areaList = hangzhouAqiService.getAreaAvgDataByAreaCode(parameters);
        if (areaList.isEmpty() && monitorList.isEmpty()) {
            return new ResultBean<List<Map<String, Object>>>(resultList);
        } else if (areaList.isEmpty()) {
            resultList.addAll(monitorList);
            for (Map<String, Object> resultMap : resultList) {
                String time = resultMap.get("time").toString();
                time = time.substring(time.length() - 2);
                resultMap.put("time", Integer.valueOf(time));
                List<String> values = new ArrayList<>();
                values.add("");
                values.add(resultMap.remove(s).toString());
                resultMap.put("values", values);
            }
            return new ResultBean<List<Map<String, Object>>>(resultList);
        } else if (monitorList.isEmpty()) {
            resultList.addAll(areaList);
            for (Map<String, Object> resultMap : resultList) {
                String time = resultMap.get("time").toString();
                time = time.substring(time.length() - 2);
                resultMap.put("time", Integer.valueOf(time));
                List<String> values = new ArrayList<>();
                values.add(resultMap.remove(s).toString());
                values.add("");
                resultMap.put("values", values);
            }
            return new ResultBean<List<Map<String, Object>>>(resultList);
        }
 
        for (Map<String, Object> map : areaList) {
            String time = map.get("time").toString();
            time = time.substring(time.length() - 2);
            map.put("time", Integer.valueOf(time));
        }
 
        for (Map<String, Object> m : monitorList) {
            String time = m.get("time").toString();
            time = time.substring(time.length() - 2);
            m.put("time", Integer.valueOf(time));
        }
 
        Integer maxTime;
        Map<String, Object> areaMap = areaList.get(areaList.size() - 1);
        Integer areaMax = Integer.valueOf(areaMap.get("time").toString());
        Map<String, Object> monitorMap = monitorList.get(monitorList.size() - 1);
        Integer monitorMax = Integer.valueOf(monitorMap.get("time").toString());
 
        if (type.equals("day")) {
            if (areaMax >= monitorMax) {
                maxTime = areaMax + 1;
            } else {
                maxTime = monitorMax + 1;
            }
        } else {
            if (areaMax >= monitorMax) {
                maxTime = areaMax;
            } else {
                maxTime = monitorMax;
            }
        }
 
        for (int i = 0; i < maxTime; i++) {
            resultList.add(null);
        }
 
        for (Map<String, Object> map : areaList) {
            Integer time = Integer.valueOf(map.get("time").toString());
            if (type.equals("day")) {
                resultList.set(time, map);
            } else {
                resultList.set(time - 1, map);
            }
        }
 
        for (int i = 0; i < resultList.size(); i++) {
            if (resultList.get(i) == null) {
                Map<String, Object> hashMap = new HashMap<>();
                if (type.equals("day")) {
                    hashMap.put("time", i);
                } else {
                    hashMap.put("time", i + 1);
                }
                hashMap.put(s, "");
                resultList.set(i, hashMap);
            }
        }
 
        for (Map<String, Object> map1 : monitorList) {
            ArrayList<String> values = new ArrayList<>();
            Integer time = Integer.valueOf(map1.get("time").toString());
            Map<String, Object> map;
            if (type.equals("day")) {
                map = resultList.get(time);
            } else {
                map = resultList.get(time - 1);
            }
            values.add(map.remove(s).toString());
            values.add(map1.get(s).toString());
            map.put("values", values);
        }
 
        for (Map<String, Object> map : resultList) {
            if (map.containsKey(s)) {
                ArrayList<String> values = new ArrayList<>();
                values.add(map.remove(s).toString());
                values.add("");
                map.put("values", values);
            }
        }
 
        Iterator<Map<String, Object>> it = resultList.iterator();
        while (it.hasNext()) {
            Map<String, Object> next = it.next();
            ArrayList<String> values = (ArrayList<String>) next.get("values");
            if (values.get(0).equals("") && values.get(1).equals("")) {
                it.remove();
            }
        }
        return new ResultBean<List<Map<String, Object>>>(resultList);
    }
 
    @GetMapping("getmpoint-byid")
    @ApiOperation(value = "获取监测站数据", notes = "获取监测站数据,包含名称、地址、坐标等详细信息")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitorPointId", defaultValue = "1", value = "监控站id", required = true, paramType = "query", dataType = "Integer"),})
    public ResultBean<MonitorPoint> getMonitorPointById(Integer monitorPointId) {
        MonitorPoint monitorPoint = monitorPointService.queryMonitorPointById(monitorPointId);
        return new ResultBean<>(monitorPoint);
    }
 
    @Resource
    HangzhouAqiService hangzhouAqiService;
 
    @GetMapping("aqi24hours")
    @ApiOperation(value = "最近24小时aqi数值", notes = "最近24小时国控aqi数值")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "orgid", defaultValue = "5", value = "组织id", required = true, paramType = "query", dataType = "Integer"),})
    public ResultBean<List<Map<String, Object>>> getAqi24HoursNC(@RequestParam("orgid") Integer organizationId) {
        return new ResultBean<>(hangzhouAqiService.queryAqi24Hours(organizationId));
    }
 
    @GetMapping("mpt-dev-summary")
    @ApiOperation(value = "监控总数和设备状态信息", notes = "监控总数和设备状态信息")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "orgid", defaultValue = "5", value = "组织id", required = true, paramType = "query", dataType = "Integer"),})
    public ResultBean<Map> getMptAndDevSummary(@RequestParam("orgid") Integer organizationId) {
        Map<String, Map> result = new HashMap<>(2);
        Integer mptCount = monitorPointService.countOfSubOrgs(organizationId);
        Map monitorPointSummary = new HashMap();
        monitorPointSummary.put("all", mptCount);
        Map deviceSummary = deviceService.queryDeviceStateSummary(organizationId);
        result.put("monitorPoint", monitorPointSummary);
        result.put("device", deviceSummary);
        return new ResultBean<>(result);
    }
 
    @GetMapping("weather")
    @ApiOperation(value = "获取区域天气情况", notes = "获取区域天气情况")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "organizationId", defaultValue = "5", value = "登录账号的组织id", required = true, paramType = "query", dataType = "String")})
    public ResultBean<Map<String, Object>> getWeatherDataByRegion(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        Map<String, Object> map = weatherService.getWeatherDataByRegion(parameters);
        return new ResultBean<Map<String, Object>>(map);
    }
 
    @GetMapping("actual")
    @ApiOperation(value = "获取监测因子实时最大值", notes = "获取监测因子实时最大值")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "accountId", defaultValue = "1", value = "登录账号的id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", defaultValue = "e1,e2,e3", value = "传感器key,如有多个用逗号分隔", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", defaultValue = "", value = "时间(long类型时间)", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "interval", defaultValue = "30", value = "时间间隔(秒)", required = true, paramType = "query", dataType = "Integer"),})
    public ResultBean<Map<String, Object>> getActualDataByRegion(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        Map<String, Object> map = historyService.getActualDataByRegion(parameters);
        return new ResultBean<Map<String, Object>>(map);
    }
 
    @GetMapping("quality")
    @ApiOperation(value = "获取优良天数", notes = "获取优良天数")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "organizationId", defaultValue = "5", value = "登录账号的组织id", required = true, paramType = "query", dataType = "String")})
    public ResultBean<Map<String, Object>> getQualityCountDayByRegion(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        Map<String, Object> map = qualityDailyService.getQualityCountDayByRegion(parameters);
        return new ResultBean<Map<String, Object>>(map);
    }
 
    @GetMapping("monitorpoints-devices")
    @ApiOperation(value = "获取监控点以及设备", notes = "获取监控点以及设备")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "organizationId", defaultValue = "8", value = "登录账号的组织id", required = true, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "regionCode", defaultValue = "320583", value = "区域码", required = true, paramType = "query", dataType = "String")})
    public ResultBean<List<MonitorPoint>> getMonitorPointsAndDevicesByRegion(HttpServletRequest request)
            throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String regionCode = parameters.get("regionCode").toString();
        List<MonitorPoint> monitorPoints = monitorPointService.getMonitorPointsAndDevicesByRegion(parameters);
 
        //剔除沧州非本公司设备
        if (regionCode.startsWith("1309")) {
            List<Integer> orgIds = new ArrayList<>();
            Collections.addAll(orgIds, 60, 65, 159, 165, 166);
            Iterator<MonitorPoint> iter = monitorPoints.iterator();
            while (iter.hasNext()) {
                MonitorPoint next = iter.next();
                Integer mpId = next.getId();
                Integer orgId = next.getOrganizationId();
                if (!orgIds.contains(orgId)) {
                    iter.remove();
                } else {
                    if (orgId == 60) {
                        if (mpId != 56) {
                            iter.remove();
                        }
                    } else if (orgId == 65) {
                        if (mpId != 83 && mpId != 84) {
                            iter.remove();
                        }
                    }
                }
            }
        }
 
        //给每一个monitorPoint下的设备通过device.getName()进行排序
        for (MonitorPoint monitorPoint : monitorPoints) {
            List<Device> deviceList = monitorPoint.getDevices();
            deviceList.sort((Device o1, Device o2) -> {
                return o1.getName().compareTo(o2.getName());
            });
        }
        return new ResultBean<List<MonitorPoint>>(monitorPoints);
    }
 
    @GetMapping("devices-state")
    @ApiOperation(value = "刷新设备状态", notes = "刷新设备状态")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "organizationId", defaultValue = "8", value = "登录账号的组织id", required = true, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "regionCode", defaultValue = "320583", value = "区域码", required = true, paramType = "query", dataType = "String")})
    public ResultBean<Collection<Object>> getDevicesStateByRegion(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        Collection<Object> monitorPoints = monitorPointService.getDevicesStateByRegion(parameters);
        return new ResultBean<Collection<Object>>(monitorPoints);
    }
 
    @Resource
    private HistoryDailyService historyDailyService;
 
    @GetMapping("emissions")
    @ApiOperation(value = "排放量", notes = "排放量")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "organizationId", defaultValue = "5", value = "登录账号的组织id", required = true, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "time", defaultValue = "2019", value = "查询的时间", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", defaultValue = "e27", value = "查询的监测因子的key", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "regionCode", defaultValue = "130000", value = "区域码", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "monitorPointId", value = "监测点id(格式:376)", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "mac", value = "设备mac(格式:vocscxwnm00001)", required = false, paramType = "query", dataType = "String")})
    public ResultBean<List<Map<String, Object>>> getemissionsData(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        List<Map<String, Object>> result = historyDailyService.getEmissionsData(parameters);
        return new ResultBean<List<Map<String, Object>>>(result);
    }
 
    @GetMapping("overproof")
    @ApiOperation(value = "浓度超标", notes = "浓度超标")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "organizationId", defaultValue = "5", value = "登录账号的组织id", required = true, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "time", defaultValue = "2019", value = "查询的时间", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", defaultValue = "e27", value = "查询的监测因子的key", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "overproofRatio", defaultValue = "0", value = "超标比例(0,1,2,3)(超标,超标100%,超标200%,超标300%)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "regionCode", defaultValue = "130000", value = "区域码", required = true, paramType = "query", dataType = "String")})
    public ResultBean<Map> getOverproofData(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        Map result = historyDailyService.getOverproofData(parameters);
        return new ResultBean<Map>(result);
    }
 
    @GetMapping("limit-device")
    @ApiOperation(value = "获取设备的警报限值", notes = "获取设备的警报限值")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "mac", defaultValue = "p5dnd7a0391956", value = "设备mac码", required = true, paramType = "query", dataType = "String")})
    public ResultBean<List<Map<String, Object>>> getLimitDataByDevice(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String density = deviceService.getLimitDataByDevice(parameters);
        JSONObject parseObject = JSONObject.parseObject(density);
        List<Map<String, Object>> resuList = new ArrayList<Map<String, Object>>();
        for (Map.Entry entry : parseObject.entrySet()) {
            resuList.add(new HashMap<String, Object>() {
                {
                    put("key", entry.getKey());
                    put("limit", entry.getValue());
                }
            });
        }
        return new ResultBean<List<Map<String, Object>>>(resuList);
    }
 
    /**
     * @param model
     * @param request
     * @return
     * @throws Exception
     * @description 根据设备mac,监测因子,时间查询返回界面
     * @author ZhuDongming
     * @date 2019-06-05 10:02:10
     */
    @GetMapping("/map-traceability")
    @ApiOperation(value = "获取污染溯源", notes = "获取污染溯源")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitorPointId", value = "监测点id(格式:319)", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "mac", value = "设备mac地址(格式:p5dnd7a0391993)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "查询的监测因子的key(格式:e1)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "查询时间(格式:2019-09-08)", required = true, paramType = "query", dataType = "String")})
    public ModelAndView traceability(ModelAndView model, HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        Integer monitorPointId = Integer.parseInt(parameters.get("monitorPointId").toString());
        MonitorPoint monitorPoint = monitorPointService.queryWithRelationById(monitorPointId);
        String mac = parameters.get("mac").toString();
        String sensorKey = parameters.get("sensorKey").toString();
        String time = parameters.get("time").toString();
        if (monitorPoint != null && mac != null && sensorKey != null && time != null) {
            Map<String, Double> resultMap = historyDailyService.getTraceabilityData(parameters);
            JSONObject params = new JSONObject();
            Long code = monitorPoint.getAreaCode().longValue();
            String regionName = areaService.queryFullNameByCode(code);
            Device device = deviceService.getDeviceByMac(mac, false);
            Device deviceSecond = deviceService.getDeviceByLongitudeAsc(mac);
            params.put("sensorInfo", resultMap);
            params.put("regionCode", code);
            params.put("regionName", regionName);
            params.put("monitorPoint", monitorPoint);
            params.put("device", device);
            params.put("deviceSecond", deviceSecond);
            String paramsJson = params.toJSONString();
            model.addObject("traceabilityParams", paramsJson);
            model.setViewName("traceability");
            return model;
        } else {
            StringBuilder msg = new StringBuilder();
            msg.append(" param[0] monitorPointId:");
            msg.append(monitorPointId);
            msg.append(" param[0] mac:");
            msg.append(mac);
            msg.append(" param[0] sensorKey:");
            msg.append(sensorKey);
            msg.append(" param[0] time:");
            msg.append(time);
            log.warn(msg);
            model.setViewName("403");
            return model;
        }
    }
 
    /*@GetMapping("getSensor")
    @ApiOperation(value = "返回单位", notes = "返回单位")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "mac", value = "设备MN号", required = true, paramType = "query", dataType = "String")
    })
    public ResultBean<Map<String, Object>> getSensor(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String mac = (String) parameters.get("mac");
        Map<String, Object> map = sensorUnitService.getSensorByMac(mac);
        return new ResultBean<Map<String, Object>>(map);
    }*/
 
    @GetMapping("getSensorByMonitorPointId")
    @ApiOperation(value = "返回单位", notes = "返回单位")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitor_point_id", value = "监测站点id", required = true, paramType = "query", dataType = "String")
    })
    public ResultBean<List<Map<String, Object>>> getSensorByMonitorPointId(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String monitor_point_id = (String) parameters.get("monitor_point_id");
        List<Map<String, Object>> map = sensorUnitService.getSensorsByMonitPointId2(monitor_point_id);
        return new ResultBean<List<Map<String, Object>>>(map);
    }
 
    @GetMapping("getSensorByDeviceId")
    @ApiOperation(value = "通过设备获取因子", notes = "通过设备获取因子")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "设备id", required = true, paramType = "query", dataType = "String")
    })
    public ResultBean<List<Map<String, Object>>> getSensorByDeviceId(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String id = (String) parameters.get("id");
        List<Map<String, Object>> list = sensorService.getSensorByDeviceId(id);
        Map<String, Object> map = list.get(0);
        String monitor_point_id = map.get("monitor_point_id").toString();
        List<Map<String, Object>> sensorUnitList = sensorUnitService.getSensorsByMonitPointId2(monitor_point_id);
        for (Map<String, Object> sensorMap : list) {
            for (Map<String, Object> sensorUnitMap : sensorUnitList) {
                if (sensorUnitMap.get("sensor_key").equals(sensorMap.get("sensor_key"))) {
                    sensorMap.put("unit", sensorUnitMap.get("name"));
                }
            }
        }
        return new ResultBean<List<Map<String, Object>>>(list);
    }
 
    @GetMapping("getSensorWithUnitByMonitorPointId")
    @ApiOperation(value = "通过站点获取因子", notes = "通过站点获取因子")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitor_point_id", value = "站点id", required = true, paramType = "query", dataType = "String")
    })
    public ResultBean<List<Map<String, Object>>> getSensorWithUnitByMonitorPointId(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String monitor_point_id = (String) parameters.get("monitor_point_id");
        List<Map<String, Object>> list = sensorService.getSensorByMonitorPointId(monitor_point_id);
        List<Map<String, Object>> sensorUnitList = sensorUnitService.getSensorsByMonitPointId2(monitor_point_id);
        for (Map<String, Object> sensorMap : list) {
            for (Map<String, Object> sensorUnitMap : sensorUnitList) {
                if (sensorUnitMap.get("sensor_key").equals(sensorMap.get("sensorKey"))) {
                    sensorMap.put("unit", sensorUnitMap.get("name"));
                }
            }
        }
        return new ResultBean<List<Map<String, Object>>>(list);
    }
 
    @GetMapping("AIForecast")
    @ApiOperation(value = "AI预测", notes = "AI预测")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitorPoint", value = "监控站id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "mac", value = "设备mac", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "传感器key,如有多个用逗号分隔", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间,天(格式:2018-03-06)", required = true, paramType = "query", dataType = "String"),
    })
    public ResultBean<List<Map<String, Object>>> AIForecast(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        String monitorPoint = (String) parameters.get("monitorPoint");
        String intoTime = parameters.get("time").toString();
        Date date = new SimpleDateFormat("yy-MM-dd").parse(intoTime);
        DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        String alterTime = df1.format(date.getTime() - 15 * 24 * 60 * 60 * 1000);
        parameters.put("time", alterTime);
        ParameterUtils.getTimeType4Time(parameters);
        String monitor_point_id = (String) parameters.get("monitorPoint");
        parameters.put("monitorPointId", parameters.remove("monitorPoint"));
        String[] sensorKeys = parameters.remove("sensorKey").toString().split(",");
        parameters.put("sensors", Arrays.asList(sensorKeys));
        List<Map<String, Object>> list = historyMinutelyService.getMonitorPointOrDeviceAvgData(parameters);
 
        Map<String, Object> mpMap = new HashMap<>();
        mpMap = monitorPointService.selectAllById(monitorPoint);
        //生命一个map,用来存放查询天气信息是需要的参数
        Map<String, Object> weatherParameters = new HashMap<>();
        weatherParameters.put("organizationId", mpMap.get("organization_id"));
        weatherParameters.put("time", intoTime);
        //获取天气信息
        Map<String, Object> weatherMap = new HashMap<>();
        Map<String, Object> tempMap = new HashMap<>();
        Boolean tf = false;
        for (int i = 0; i < sensorKeys.length; i++) {
            if (sensorKeys[i].equals("e7")) {
                tf = true;
            }
        }
        if (tf) {
            weatherMap = weatherService.get15DayWeatherDataByRegion(weatherParameters);
            tempMap = TempAllocationUtils.tempAllocation(weatherMap);
        }
        //获取单位信息
        Map<String, Map<String, Object>> sensorUnitMap = sensorUnitService.getSensorsByMonitPointId(monitor_point_id);
 
        for (Map<String, Object> map : list) {
            String time = map.get("time").toString();
            time = time.substring(time.length() - 2);
            map.put("time", Integer.valueOf(time));
            if (tempMap != null) {
                map.put("temp", tempMap.get(map.get("time").toString()));
            }
            List<Number> values = new ArrayList<Number>();
            List<String> units = new ArrayList<String>();
            for (String string : sensorKeys) {
                if (sensorUnitMap != null && !sensorUnitMap.isEmpty()) {
                    if (sensorUnitMap.get(string) != null) {
                        units.add(sensorUnitMap.get(string).get("name").toString());
                        String rules = sensorUnitMap.get(string).get("rules").toString();
                        rules = rules.replace("{0}", "a");
                        rules = rules.replace("d", "");
                        Expression expression = AviatorEvaluator.compile(rules);
                        Double value;
                        Map<String, Object> ev = new HashMap<>();
                        ev.put("a", map.get(string));
                        value = (Double) expression.execute(ev);
                        //保留两位小数
                        DecimalFormat df = new DecimalFormat("#.00");
                        value = Double.parseDouble(df.format(value));
                        values.add(value);
                    } else {
                        Map<String, Object> sensorMap = sensorService.getSensorBySensorKey(string);
                        units.add(sensorMap.get("unit").toString());
                        values.add((Number) map.remove(string));
                    }
                } else {
                    Map<String, Object> sensorMap = sensorService.getSensorBySensorKey(string);
                    units.add(sensorMap.get("unit").toString());
                    values.add((Number) map.remove(string));
                }
                //values.add((Number) map.remove(string));
            }
            map.put("values", values);
            map.put("units", units);
        }
        return new ResultBean<List<Map<String, Object>>>(list);
    }
 
    @GetMapping("getWeather")
    @ApiOperation(value = "获取天气信息", notes = "获取天气信息")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "organizationId", defaultValue = "5", value = "登录账号的组织id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间,天(格式:2018-03-06)", required = true, paramType = "query", dataType = "String"),
    })
    public ResultBean<Map<String, Object>> getWeather(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        Map<String, Object> map = weatherService.get15DayWeatherDataByRegion(parameters);
        Map<String, Object> tempMap = TempAllocationUtils.tempAllocation(map);
        return new ResultBean<Map<String, Object>>(tempMap);
    }
 
    @GetMapping("/uavTrajectory")
    @ApiOperation(value = "显示无人机飞行轨迹", notes = "显示无人机飞行轨迹")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "mac", value = "设备mac(格式:p5dnd7a0392068)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间(格式:2019-07-17-17)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2019-07-17-18)", required = true, paramType = "query", dataType = "String")
    })
    public ModelAndView uavTrajectory(ModelAndView model, HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String st = parameters.get("startTime").toString();
        String startYearAndDay = st.substring(0, st.lastIndexOf("-"));
        String startHour = st.substring(st.lastIndexOf("-") + 1);
        String startTime = startYearAndDay + " " + startHour + ":00:00";
        String et = parameters.get("endTime").toString();
        String endYearAndDay = et.substring(0, et.lastIndexOf("-"));
        String endHour = et.substring(et.lastIndexOf("-") + 1);
        int endHourValue = Integer.valueOf(endHour);
        int startHourValue = Integer.valueOf(startHour);
        if (endHourValue <= startHourValue) {
            endHourValue = startHourValue + 1;
        }
        String endTime = startYearAndDay + " " + endHourValue + ":00:00";
        parameters.put("startTime", startTime);
        parameters.put("endTime", endTime);
        String mac = parameters.get("mac").toString();
        if (mac != null && mac.length() != 0) {
            List<List<Map<String, Object>>> sensorData = historyMinutelyService.getSensorData(parameters);
            Map<String, String> sensorsMap = sensorService.getSensorsMap(parameters);
            List<Map<String, Object>> sensorList = new ArrayList<>();
            List<Map<String, Object>> sensorListMin = new ArrayList<>();
            List<Map<String, Object>> sensorListMax = new ArrayList<>();
            if (sensorData.size() == 3) {
                sensorList = sensorData.get(0);
                sensorListMin = sensorData.get(1);
                sensorListMax = sensorData.get(2);
            }
            JSONObject params = new JSONObject();
            params.put("sensorInfo", sensorList);
            params.put("sensorInfoMin", sensorListMin);
            params.put("sensorInfoMax", sensorListMax);
            params.put("sensorsMap", sensorsMap);
            String paramsJson = params.toJSONString();
            model.addObject("uavTrajectoryParams", paramsJson);
            model.setViewName("uavtrajectory");
            return model;
        } else {
            StringBuilder msg = new StringBuilder();
            msg.append(" param[0] mac:");
            msg.append(mac);
            log.warn(msg);
            model.setViewName("403");
            return model;
        }
    }
 
    @GetMapping("/pollutionSource")
    @ApiOperation(value = "污染传播来源", notes = "污染传播来源")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "mac", value = "设备mac地址(如:898607b0101730392251)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "查询的监测因子的key(格式:e1)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "查询时间(格式:2019-09-01-10)", required = true, paramType = "query", dataType = "String")})
    public ModelAndView pollutionSource(ModelAndView model, HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String timeStr = parameters.get("time").toString();
        String yearAndDay = timeStr.substring(0, timeStr.lastIndexOf("-"));
        String Hour = timeStr.substring(timeStr.lastIndexOf("-") + 1);
        String time = yearAndDay + " " + Hour + ":00:00";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime timeLocalDateTime = LocalDateTime.parse(time, dateTimeFormatter);
        int month = timeLocalDateTime.getMonth().getValue();
        parameters.put("yearAndDay",yearAndDay);
        Point dirPoint = historyHourlyService.getDirPoint(parameters);
        Map<String, Object> getPollutionSourceData = historyHourlyService.getPollutionSourceDataByHour(parameters);
        if (MapUtils.isEmpty(getPollutionSourceData)) {
            getPollutionSourceData = historyHourlyService.getPollutionSourceDataAll(parameters);
        }
        if (MapUtils.isEmpty(getPollutionSourceData)) {
            getPollutionSourceData = new HashMap<>();
        }
        String mac = parameters.get("mac").toString();
        Device device = deviceService.getDeviceByMac(mac, false);
        JSONObject params = new JSONObject();
        params.put("device", device);
        params.put("month", month);
        params.put("dirPoint", dirPoint);
        params.put("getPollutionSourceData", getPollutionSourceData);
        String paramsJson = params.toJSONString();
        model.addObject("pollutionSourceParams", paramsJson);
        model.setViewName("pollutionsource");
        return model;
    }
 
    @GetMapping("getAirQualityComparison")
    @ApiOperation(value = "空气质量对比", notes = "空气质量对比")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "organizationId", defaultValue = "5", value = "登录账号的组织id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "monitor_point_id", defaultValue = "5", value = "监控站点id", required = true, paramType = "query", dataType = "String")})
    public ResultBean<Map<String, Object>> getAirQualityComparison(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        Map<String, Object> map = weatherService.getWeatherDataByRegion(parameters);
        Map<String, Double> sensorMap = new HashMap<>();
        sensorMap.put("e1", Double.parseDouble(map.get("pm25").toString()));
        sensorMap.put("e2", Double.parseDouble(map.get("pm10").toString()));
        sensorMap.put("e11", Double.parseDouble(map.get("so2").toString()));
        sensorMap.put("e16", Double.parseDouble(map.get("no2").toString()));
        sensorMap.put("e10", Double.parseDouble(map.get("co").toString()));
        sensorMap.put("e15", Double.parseDouble(map.get("o3").toString()));
        Map<String, Object> StateControl = AQICalculation.hourlyAQI(sensorMap);
        Map<String, Object> hourAqi = historyService.gitHourlyAQIByMonitorPointIdAndTimeslot(parameters);
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("MonitorPointAQI", hourAqi.get("AQI"));
        returnMap.put("StateControlAQI", StateControl.get("AQI"));
        return new ResultBean<Map<String, Object>>(returnMap);
    }
 
 
    @GetMapping("mointorPointRank")
    @ApiOperation(value = "获取站点排名", notes = "获取站点排名")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "accountId", value = "账号id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensor", value = "因子", required = true, paramType = "query", dataType = "String")
    })
    public ResultBean<List<Map<String, Object>>> getMointorPointRank(HttpServletRequest request) {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String id = parameters.get("accountId").toString();
        String sensor = parameters.get("sensor").toString();
        Map<String, Object> account = accountService.getOrganizationIdByAccountId(id);
        //通过组织id来获取站点和设备信息
        account.put("sensor", sensor);
        List<Map<String, Object>> rankList = historyService.getMointorPointRankByOrganizationId(account);
        List<Map<String, Object>> returnList = new ArrayList<>();
        for (Map<String, Object> map : rankList) {
            boolean contains = map.containsKey("sensor");
            if (contains) {
                returnList.add(map);
            }
        }
        return new ResultBean<List<Map<String, Object>>>(returnList);
    }
 
    @GetMapping("/carTrajectory")
    @ApiOperation(value = "显示走航车轨迹", notes = "显示走航车轨迹")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "mac", value = "设备mac(格式:p5dnd7a0392081)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间(格式:2020-03-19-14)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2020-03-19-17)", required = true, paramType = "query", dataType = "String")
    })
    public ModelAndView carTrajectory(ModelAndView model, HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String st = parameters.get("startTime").toString();
        String startYearAndDay = st.substring(0, st.lastIndexOf("-"));
        String startHour = st.substring(st.lastIndexOf("-") + 1);
        String startTime = startYearAndDay + " " + startHour + ":00:00";
        String et = parameters.get("endTime").toString();
        String endYearAndDay = et.substring(0, st.lastIndexOf("-"));
        String endHour = et.substring(et.lastIndexOf("-") + 1);
        String endTime = endYearAndDay + " " + endHour + ":00:00";
       /* int endHourValue = Integer.valueOf(endHour);
        int startHourValue = Integer.valueOf(startHour);
        if (endHourValue <= startHourValue) {
            endHourValue = startHourValue + 1;
        }
        String endTime = startYearAndDay + " " + endHourValue + ":00:00";*/
        parameters.put("startTime", startTime);
        parameters.put("endTime", endTime);
        String mac = parameters.get("mac").toString();
        if (mac != null && mac.length() != 0) {
            List<List<Map<String, Object>>> sensorData = historyService.getCarSensorData(parameters);
            Map<String, String> sensorsMap = sensorService.getSensorsMap(parameters);
            List<Map<String, Object>> sensorList = new ArrayList<>();
            if (sensorData.size() == 3) {
                sensorList = sensorData.get(0);
            }
            JSONObject params = new JSONObject();
            params.put("sensorInfo", sensorList);
            params.put("sensorsMap", sensorsMap);
            String paramsJson = params.toJSONString();
            //System.out.println(paramsJson);
            model.addObject("carTrajectoryParams", paramsJson);
            model.setViewName("cartrajectory");
            return model;
        } else {
            StringBuilder msg = new StringBuilder();
            msg.append(" param[0] mac:");
            msg.append(mac);
            log.warn(msg);
            model.setViewName("403");
            return model;
        }
    }
 
    @GetMapping("/trajectoryDataShow")
    @ApiOperation(value = "轨迹及数据", notes = "轨迹及数据")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "mac", value = "设备mac(格式:p5dnd7a0392081)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间(格式:2020-03-19-14)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2020-03-19-17)", required = true, paramType = "query", dataType = "String")
    })
    public ModelAndView trajectoryDataShow(ModelAndView model, HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String st = parameters.get("startTime").toString();
        String startYearAndDay = st.substring(0, st.lastIndexOf("-"));
        String startHour = st.substring(st.lastIndexOf("-") + 1);
        String startTime = startYearAndDay + " " + startHour + ":00:00";
        String et = parameters.get("endTime").toString();
        String endHour = et.substring(et.lastIndexOf("-") + 1);
        int endHourValue = Integer.valueOf(endHour);
        int startHourValue = Integer.valueOf(startHour);
        if (endHourValue <= startHourValue) {
            endHourValue = startHourValue + 1;
        }
        String endTime = startYearAndDay + " " + endHourValue + ":00:00";
        parameters.put("startTime", startTime);
        parameters.put("endTime", endTime);
        String mac = parameters.get("mac").toString();
        if (mac != null && mac.length() != 0) {
            List<List<Map<String, Object>>> sensorData = historyService.getCarSensorData(parameters);
            Map<String, String> sensorsMap = sensorService.getSensorsMap(parameters);
            List<Map<String, Object>> sensorList = new ArrayList<>();
            if (sensorData.size() == 3) {
                sensorList = sensorData.get(0);
            }
            JSONObject params = new JSONObject();
            params.put("sensorInfo", sensorList);
            params.put("sensorsMap", sensorsMap);
            String paramsJson = params.toJSONString();
            model.addObject("trajectoryParams", paramsJson);
            model.setViewName("trajectorydatashow");
            return model;
        } else {
            StringBuilder msg = new StringBuilder();
            msg.append(" param[0] mac:");
            msg.append(mac);
            log.warn(msg);
            model.setViewName("403");
            return model;
        }
    }
 
    @GetMapping("device-excel")
    @ApiOperation(value = "获取设备数据报表", notes = "获取设备数据报表")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "organizationId", defaultValue = "8", value = "登录账号的组织id", required = true, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "regionCode", defaultValue = "320583", value = "区域码", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间(格式:2020-04-09或2019-04)", required = true, paramType = "query", dataType = "String")})
    public ResultBean<List<Map<String, Object>>> getDevicesDataToExcel(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        ParameterUtils.getTimeType4Time(parameters);
        Object sensorKey = parameters.get("sensorKey");
        parameters.put("sensorKeys", Arrays.asList(sensorKey));
        List<String> macList = new ArrayList<>();
        List<MonitorPoint> monitorPoints = monitorPointService.getMonitorPointsAndDevicesByRegion(parameters);
        for (MonitorPoint m : monitorPoints) {
            for (Device d : m.getDevices()) {
                macList.add(d.getMac());
            }
        }
        parameters.put("macs", macList);
        List<Map<String, Object>> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(macList)) {
            list = historyMinutelyService.getDevicesAvgDataToExcel(parameters);
        }
        return new ResultBean<List<Map<String, Object>>>(list);
    }
 
    @RequestMapping(value = "/newMap-page", method = RequestMethod.GET)
    public ModelAndView newMap(ModelAndView model, @RequestParam("areaCode") long code,
                               @RequestParam("accountId") int accountId) {
 
        Account account = accountService.getAccountById(accountId);
        List<MonitorPoint> monitorPointList = monitorPointService.getMonitorPointListByAccountId(accountId);
        String regionName = areaService.queryFullNameByCode(code);
 
        if (account != null && regionName != null) {
            Object sensors = sensorService.queryAll();
            JSONObject params = new JSONObject();
            params.put("regionCode", code);
            params.put("regionName", regionName);
            params.put("accountId", accountId);
            params.put("orgId", account.getOrganizationId());
            params.put("sensors", sensors);
            String paramsJson = params.toJSONString();
            model.addObject("mapParams", paramsJson);
            model.setViewName("newmap");
            return model;
        } else {
            StringBuilder msg = new StringBuilder();
            msg.append(" param[0] areaCode:");
            msg.append(code);
            msg.append(" param[0] accountId:");
            msg.append(accountId);
            log.warn(msg);
            model.setViewName("403");
            return model;
        }
    }
 
    @GetMapping("/uavDroppoint")
    @ApiOperation(value = "无人机落点应用", notes = "无人机落点应用")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "mac", value = "设备mac(格式:p5dnd7a0392068)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间(格式:2019-07-17-17)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2019-07-17-18)", required = true, paramType = "query", dataType = "String")
    })
    public ModelAndView uavDroppoint(ModelAndView model, HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String st = parameters.get("startTime").toString();
        String startYearAndDay = st.substring(0, st.lastIndexOf("-"));
        String startHour = st.substring(st.lastIndexOf("-") + 1);
        String startTime = startYearAndDay + " " + startHour + ":00:00";
        String et = parameters.get("endTime").toString();
        String endHour = et.substring(et.lastIndexOf("-") + 1);
        int endHourValue = Integer.valueOf(endHour);
        int startHourValue = Integer.valueOf(startHour);
        if (endHourValue <= startHourValue) {
            endHourValue = startHourValue + 1;
        }
        String endTime = startYearAndDay + " " + endHourValue + ":00:00";
        parameters.put("startTime", startTime);
        parameters.put("endTime", endTime);
        String mac = parameters.get("mac").toString();
        if (mac != null && mac.length() != 0) {
            List<Map<String, Object>> sensorData = historyService.getUavSensorData(parameters);
            Map<String, String> sensorsMap = sensorService.getSensorsMap(parameters);
            JSONObject params = new JSONObject();
            params.put("sensorInfo", sensorData);
            params.put("sensorsMap", sensorsMap);
            params.put("sensorKey", parameters.get("sensorKey"));
            params.put("unit", parameters.get("unit"));
            params.put("description", parameters.get("description"));
            String paramsJson = params.toJSONString();
            model.addObject("uavDroppointParams", paramsJson);
            model.setViewName("uavdroppoint");
            return model;
        } else {
            StringBuilder msg = new StringBuilder();
            msg.append(" param[0] mac:");
            msg.append(mac);
            log.warn(msg);
            model.setViewName("403");
            return model;
        }
    }
 
    @GetMapping("/uavChannel")
    @ApiOperation(value = "无人机污染源通道应用", notes = "无人机污染源通道应用")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "mac", value = "设备mac(格式:p5dnd7a0392068)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间(格式:2019-07-17-17)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2019-07-17-18)", required = true, paramType = "query", dataType = "String")
    })
    public ModelAndView uavChannel(ModelAndView model, HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String st = parameters.get("startTime").toString();
        String startYearAndDay = st.substring(0, st.lastIndexOf("-"));
        String startHour = st.substring(st.lastIndexOf("-") + 1);
        String startTime = startYearAndDay + " " + startHour + ":00:00";
        String et = parameters.get("endTime").toString();
        String endHour = et.substring(et.lastIndexOf("-") + 1);
        int endHourValue = Integer.valueOf(endHour);
        int startHourValue = Integer.valueOf(startHour);
        if (endHourValue <= startHourValue) {
            endHourValue = startHourValue + 1;
        }
        String endTime = startYearAndDay + " " + endHourValue + ":00:00";
        parameters.put("startTime", startTime);
        parameters.put("endTime", endTime);
        String mac = parameters.get("mac").toString();
        if (mac != null && mac.length() != 0) {
            List<Map<String, Object>> sensorData = historyService.getUavSensorData(parameters);
            Map<String, String> sensorsMap = sensorService.getSensorsMap(parameters);
            JSONObject params = new JSONObject();
            params.put("sensorInfo", sensorData);
            params.put("sensorsMap", sensorsMap);
            params.put("sensorKey", parameters.get("sensorKey"));
            params.put("unit", parameters.get("unit"));
            params.put("description", parameters.get("description"));
            String paramsJson = params.toJSONString();
            model.addObject("uavChannelParams", paramsJson);
            model.setViewName("uavchannelnew");
            return model;
        } else {
            StringBuilder msg = new StringBuilder();
            msg.append(" param[0] mac:");
            msg.append(mac);
            log.warn(msg);
            model.setViewName("403");
            return model;
        }
    }
 
    @GetMapping("/uavTracing")
    @ApiOperation(value = "无人机溯源应用", notes = "无人机溯源应用")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "mac", value = "设备mac(格式:p5dnd7a0392068)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间(格式:2019-07-17-17)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2019-07-17-18)", required = true, paramType = "query", dataType = "String")
    })
    public ModelAndView uavTracing(ModelAndView model, HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String st = parameters.get("startTime").toString();
        String startYearAndDay = st.substring(0, st.lastIndexOf("-"));
        String startHour = st.substring(st.lastIndexOf("-") + 1);
        String startTime = startYearAndDay + " " + startHour + ":00:00";
        String et = parameters.get("endTime").toString();
        String endHour = et.substring(et.lastIndexOf("-") + 1);
        int endHourValue = Integer.parseInt(endHour);
        int startHourValue = Integer.parseInt(startHour);
        if (endHourValue <= startHourValue) {
            endHourValue = startHourValue + 1;
        }
        String endTime = startYearAndDay + " " + endHourValue + ":00:00";
        parameters.put("startTime", startTime);
        parameters.put("endTime", endTime);
        String mac = parameters.get("mac").toString();
        if (mac != null && mac.length() != 0) {
            List<Map<String, Object>> sensorData = historyService.getUavSensorData(parameters);
            Map<String, String> sensorsMap = sensorService.getSensorsMap(parameters);
            JSONObject params = new JSONObject();
            params.put("sensorInfo", sensorData);
            params.put("sensorsMap", sensorsMap);
            params.put("sensorKey", parameters.get("sensorKey"));
            params.put("unit", parameters.get("unit"));
            params.put("description", parameters.get("description"));
            String paramsJson = params.toJSONString();
            model.addObject("uavTracingParams", paramsJson);
            model.setViewName("uavtracing");
            return model;
        } else {
            StringBuilder msg = new StringBuilder();
            msg.append(" param[0] mac:");
            msg.append(mac);
            log.warn(msg);
            model.setViewName("403");
            return model;
        }
    }
 
    @GetMapping("/purify")
    @ApiOperation(value = "获取厂区净化率", notes = "获取厂区净化率")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitorPointId", value = "公司Id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "因子", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19-14)", required = true, paramType = "query", dataType = "String")})
    public ModelAndView PurificationRate(HttpServletRequest request, ModelAndView model) {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String monitPointIdS = (String) parameters.get("monitorPointId");
        String sensor = (String) parameters.get("sensorKey");
        String time = (String) parameters.get("time");
        String YearAndDay = time.substring(0, time.lastIndexOf("-"));
        String Hour = time.substring(time.lastIndexOf("-") + 1);
        String Time = YearAndDay + " " + Hour + ":00:00";
        int monitPointId = Integer.parseInt(monitPointIdS);
        JSONObject params = monitorPointService.getMonitorPointById(monitPointId, Time, 1, sensor);
        String paramsJson = params.toJSONString();
        model.addObject("mapParams", paramsJson);
        model.setViewName("purityMap");
        return model;
    }
 
 
    @GetMapping("/collection")
    @ApiOperation(value = "获取厂区收集率", notes = "获取厂区收集率")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitorPointId", value = "公司Id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19-14)", required = true, paramType = "query", dataType = "String")})
    public ModelAndView collectionRate(HttpServletRequest request, ModelAndView model) {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String monitPointIdS = (String) parameters.get("monitorPointId");
        String sensor = "";
        String time = (String) parameters.get("time");
        String YearAndDay = time.substring(0, time.lastIndexOf("-"));
        String Hour = time.substring(time.lastIndexOf("-") + 1);
        String Time = YearAndDay + " " + Hour + ":00:00";
        int monitPointId = Integer.parseInt(monitPointIdS);
        //获取公司信息
        JSONObject params = monitorPointService.getMonitorPointById(monitPointId, Time, 2, sensor);
        model.addObject("params", params);
        model.setViewName("pressureMap");
        return model;
    }
 
 
    @GetMapping("/unorganizedEmissions")
    @ApiOperation(value = "无组织排放", notes = "无组织排放")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitorPointId", value = "公司Id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "因子", required = true, paramType = "query", dataType = "String"),
            // @ApiImplicitParam(name = "sensorKey", value = "传感器key,如有多个用逗号分隔", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19-14)", required = true, paramType = "query", dataType = "String")})
    public ModelAndView unorganizedEmissions(HttpServletRequest request, ModelAndView model) {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String monitPointIdS = (String) parameters.get("monitorPointId");
        String sensor = (String) parameters.get("sensorKey");
        String time = (String) parameters.get("time");
        String YearAndDay = time.substring(0, time.lastIndexOf("-"));
        String Hour = time.substring(time.lastIndexOf("-") + 1);
        String Time = YearAndDay + " " + Hour + ":00:00";
        int monitPointId = Integer.parseInt(monitPointIdS);
        //获取公司信息
        JSONObject params = monitorPointService.getMonitorPointById(monitPointId, Time, 3, sensor);
        model.addObject("params", params);
        model.setViewName("unorganizedMap");
        return model;
    }
 
 
    @GetMapping("/unorganizedEmissionsRealTime")
    @ApiOperation(value = "无组织排放实时", notes = "无组织排放实时")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitorPointId", value = "公司Id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "因子", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "accountId", value = "用户id", required = false, paramType = "query", dataType = "String")})
    public ModelAndView unorganizedEmissionsBackups(HttpServletRequest request, ModelAndView model) {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        String monitPointIdS = (String) parameters.get("monitorPointId");
        String sensor = (String) parameters.get("sensorKey");
        String accountId = (String) parameters.get("accountId");
        Account account = accountService.getAccountById(Integer.parseInt(accountId));
        int monitPointId = Integer.parseInt(monitPointIdS);
        JSONObject params = monitorPointService.getMacList(monitPointId);
        params.put("accountId", accountId);
        params.put("orgId", account.getOrganizationId());
        params.put("sensor", sensor);
        //获取公司信息
        //JSONObject params=monitorPointService.getMonitorPointById(monitPointId,Time,3,sensor);
        // model.addObject("params",params);
        model.addObject("params", params);
        model.setViewName("newUnorganizedMap");
        return model;
    }
 
    @GetMapping("/chooseDevice")
    @ResponseBody
    public Object unorganizedEmissionsBackups(String wind, String monitPointId) {
        JSONObject params = new JSONObject();
        Double windDir = Double.parseDouble(wind);
        List<Device> deviceList = deviceService.getDeviceById2(Integer.parseInt(monitPointId));
        Map<String, Object> longAndLatiMap;
        List<Map> longAndLatiList = new ArrayList<>();//经纬度夹角集合,存放的是windList中两台设备的下标和两台设备夹角与风向角的差值
        List<Device> preAngleDeviceList = new ArrayList<Device>(); //角度减去风向最小的两台设备
        for (int f = 0; f < deviceList.size(); f++) {
            for (int h = 0; h < deviceList.size(); h++) {
                if (f != h) {
                    longAndLatiMap = new HashMap<String, Object>();
                    longAndLatiMap.put("h", h);
                    longAndLatiMap.put("f", f);
                    Double angle = mapUtils.getAngle(
                            new MyLatLng((Double) deviceList.get(h).getLongitude(),
                                    (Double) deviceList.get(h).getLatitude()),
                            new MyLatLng((Double) deviceList.get(f).getLongitude(),
                                    (Double) deviceList.get(f).getLatitude()));
                    Double angleDiff = Math.abs(angle - windDir);
                    longAndLatiMap.put("angle", angleDiff);
                    longAndLatiList.add(longAndLatiMap);
                }
            }
        }
        Double minAngle = (Double) longAndLatiList.get(0).get("angle");
        int indexAngle = 0;
        for (int j = 1; j < longAndLatiList.size(); j++) {
            if (minAngle > (Double) longAndLatiList.get(j).get("angle")) {
                minAngle = (Double) longAndLatiList.get(j).get("angle");
                indexAngle = j;
            } else {
                indexAngle = indexAngle;
            }
        }
        preAngleDeviceList.add(deviceList.get((Integer) longAndLatiList.get(indexAngle).get("h")));
        preAngleDeviceList.add(deviceList.get((Integer) longAndLatiList.get(indexAngle).get("f")));
        Double length = mapUtils.getDistance((Double) preAngleDeviceList.get(0).getLongitude(), (Double) preAngleDeviceList.get(0).getLatitude(),
                (Double) preAngleDeviceList.get(1).getLongitude(), (Double) preAngleDeviceList.get(1).getLatitude());
        Double subLength = length / 5;
        Double subLength1 = length / 6.1;
        Double angle = mapUtils.getAngle(
                new MyLatLng((Double) preAngleDeviceList.get(0).getLongitude(),
                        (Double) preAngleDeviceList.get(0).getLatitude()),
                new MyLatLng((Double) preAngleDeviceList.get(1).getLongitude(),
                        (Double) preAngleDeviceList.get(1).getLatitude()));
        List locationList = new ArrayList();
        String[] firstLocation = mapUtils.calLocationByDistanceAndLocationAndDirection(angle, (Double) preAngleDeviceList.get(0).getLongitude(),
                (Double) preAngleDeviceList.get(0).getLatitude(), subLength);
        String[] secondLoction = mapUtils.calLocationByDistanceAndLocationAndDirection(angle, Double.parseDouble(firstLocation[0]),
                Double.parseDouble(firstLocation[1]), subLength);
        String[] thirdLocation = mapUtils.calLocationByDistanceAndLocationAndDirection(angle, Double.parseDouble(secondLoction[0]),
                Double.parseDouble(secondLoction[1]), subLength);
        String[] fourthLoction = mapUtils.calLocationByDistanceAndLocationAndDirection(angle, Double.parseDouble(thirdLocation[0]),
                Double.parseDouble(thirdLocation[1]), subLength);
        String[] fivethLoction = mapUtils.calLocationByDistanceAndLocationAndDirection(angle, Double.parseDouble(fourthLoction[0]),
                Double.parseDouble(fourthLoction[1]), subLength1);
        locationList.add(firstLocation);
        locationList.add(secondLoction);
        locationList.add(thirdLocation);
        locationList.add(fourthLoction);
        locationList.add(fivethLoction);
        String preAngleDeviceString = JSON.toJSON(preAngleDeviceList).toString();
        params.put("preAngleDeviceString", preAngleDeviceString);//两台添加箭头的设备
        params.put("locationList", locationList);
        return params;
    }
 
    @GetMapping("/allDevice")
    @ResponseBody
    public Map<String, List> getAllDevice() {
        List<String> macList = deviceService.getAllMac();
        Map<String, List> latlngMap = new HashMap<String, List>();
        Map devMap = null;
        List list = new ArrayList();
        for (String mac : macList) {
            devMap = new HashMap();
            if (mac != null) {
                Device device = deviceService.byMacGetDevice(mac);
                List list1 = LatLngTransformation.Convert_BD09_To_GCJ02(device.getLatitude(), device.getLongitude());
                if (device.getState() != 4 + "") {
                    devMap.put("state", device.getState());
                }
                devMap.put("lat", list1.get(1));
                devMap.put("lng", list1.get(0));
                devMap.put("monitorPointId", device.getMonitorPointId());
                //System.out.println(device);
                list.add(devMap);
            } else {
                continue;
            }
        }
        latlngMap.put("latlng", list);
        return latlngMap;
    }
 
 
    @GetMapping("/windAndDeviceData")
    @ResponseBody
    public List windAndDeviceData(String monitorPointId) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, (calendar.get(Calendar.MINUTE) - 2));
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        //String time = df.format(calendar.getTime()) + ":00";
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        String mon;
        if (month < 10) {
            mon = "0" + month;
        } else {
            mon = "" + month;
        }
        String table = "history_five_minutely_" + year + mon;
        List list = deviceService.byMonitorIdGetDeviceAndWind(monitorPointId, table);
        return list;
    }
 
    //局部风场
    @GetMapping("/windAndDeviceDataByArea")
    @ResponseBody
    public List windAndDeviceDataByArea(String monitorPointId) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, (calendar.get(Calendar.MINUTE) - 2));
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String time = df.format(calendar.getTime()) + ":00";
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        String mon;
        if (month < 10) {
            mon = "0" + month;
        } else {
            mon = "" + month;
        }
        String table = "history_five_minutely_" + year + mon;
        List list = deviceService.byMonitorIdGetDeviceAndWindSpecial(monitorPointId, table);
        return list;
    }
 
    @GetMapping("forecastO3")
    @ApiOperation(value = "预测和实际臭氧对比", notes = "预测和实际臭氧对比")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitorPointId", defaultValue = "1", value = "监控站id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19)", required = true, paramType = "query", dataType = "String")})
    public ResultBean<List<Map<String, Object>>> getWeatherNextDayDataByRegion(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        List<String> sensorKeys=new ArrayList<>();
        sensorKeys.add("e15");
        parameters.put("sensorKeys",sensorKeys);
        List<Map<String, Object>> resultList = weatherService.getForecastAndReal(parameters);
        return new ResultBean<List<Map<String, Object>>>(resultList);
    }
 
 
    @GetMapping("forecastPM")
    @ApiOperation(value = "预测和实测颗粒物对比", notes = "预测和实测颗粒物对比")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitorPointId", defaultValue = "1", value = "监控站id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19)", required = true, paramType = "query", dataType = "String")})
    public ResultBean<List<Map<String, Object>>> getForecastAndRealPM(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        List<String> sensorKeys=new ArrayList<>();
        sensorKeys.add("e1");
        sensorKeys.add("e2");
        parameters.put("sensorKeys",sensorKeys);
        List<Map<String, Object>> resultList = weatherService.getForecastAndReal(parameters);
        return new ResultBean<List<Map<String, Object>>>(resultList);
    }
 
    @GetMapping("weatherData")
    @ApiOperation(value = "根据city查询小时预测和实测数据", notes = "根据city查询小时预测和实测数据")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "city", value = "城市名", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19)", required = true, paramType = "query", dataType = "String")})
    public ResultBean<List<Map<String, Object>>> getWeatherData(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        List<Map<String, Object>> weatherList = weatherService.getWeatherData(parameters);
        return new ResultBean<List<Map<String, Object>>>(weatherList);
    }
 
    @GetMapping("weatherDataDay")
    @ApiOperation(value = "根据city查询日实测数据", notes = "根据city查询日实测数据")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "city", value = "城市名", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19)", required = true, paramType = "query", dataType = "String")})
    public ResultBean<List<Map<String, Object>>> getWeatherDataByDay(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        List<Map<String, Object>> weatherList = weatherService.getWeatherDataByDay(parameters);
        return new ResultBean<List<Map<String, Object>>>(weatherList);
    }
 
    @GetMapping("monitorDeviceData")
    @ApiOperation(value = "获取微型站5分钟和半小时数据", notes = "获取微型站5分钟和半小时数据")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "city", value = "城市名", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-15)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "type", value = "类型(5分钟:m,半小时:h)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "range", value = "要查看的设备范围(国控站周边:m,全城:a)", required = true, paramType = "query", dataType = "String")})
    public ResultBean<List<Map<String, Object>>> get5MinutesOrHalfHour(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        List<Map<String, Object>> deviceData = historyMinutelyService.get5MinutesOrHalfHour(parameters);
        return new ResultBean<List<Map<String, Object>>>(deviceData);
    }
 
    @PostMapping("updateForecastWeather")
    public void updateForecastWeather(HttpServletRequest request) {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        weatherService.updateForecastWeather(parameters);
    }
 
    @GetMapping("dataByTimeSlot")
    @ApiOperation(value = "根据时间类型获取因子的值", notes = "根据时间类型获取因子的值")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "mac", value = "mac地址", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "起始时间(格式:2020-08-03/2020-08-03-13)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2020-08-04/2020-08-04-14)", required = true, paramType = "query", dataType = "String")})
    public ResultBean<List<Map<String, Object>>> getDataByTimeSlot(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        String mac = parameters.get("mac").toString();
        String startTime = parameters.get("startTime").toString();
        String endTime = parameters.get("endTime").toString();
        //对时间进行操作的接口
        Calendar calendar = getInstance();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        List<Map<String, Object>> list = new ArrayList();
        Map device = deviceService.getAllFieldByMac(parameters);
        Map monitorPointMap = monitorPointService.selectAllById(device.get("monitor_point_id").toString());
        List<Map<String, Object>> device_sensorList = sensorService.getSensorByDeviceId(device.get("id").toString());
        Map<String, Object> device_sensorUnit_map = new HashMap<>();
        for (Map<String, Object> device_sensorMap : device_sensorList) {
            device_sensorUnit_map.put(device_sensorMap.get("sensor_key").toString(), device_sensorMap.get("unit"));
        }
        Map<String, String> sensorMap = sensorService.getSensorsMap(parameters);
        if (startTime.length() == 10 && endTime.length() == 10) {
            //获取当日时间
            Date dd = new Date();
            //格式化
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
            //获取系统当前时间
            String nowTime = sim.format(dd);
            int days = endTime.compareTo(nowTime);
            //System.out.println(days);
            List<String> dayList = DatesUtil.findDaysStr(startTime, endTime);
            //System.out.println("dayList:"+dayList);
            /*if (days<0){
                Date date=null;
                try {
                    date = new SimpleDateFormat("yy-MM-dd").parse(endTime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                calendar.setTime(date);
                int day=calendar.get(Calendar.DATE);
                calendar.set(Calendar.DATE,day+1);
 
                endTime=new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
            }*/
            List<Map<String, Object>> sameDayHourlyList = null;
            if (days >= 0) {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //获取系统当前时间
                String currentTime = df.format(dd);
                sameDayHourlyList = historyHourlyService.getDataByTimeSlot(mac, nowTime, currentTime);
            }
            List<Map<String, Object>> dataList = historyDailyService.getDataByTimeSlot(mac, startTime, endTime);
            if (dataList.isEmpty()) {
                return null;
            }
            Set<String> keys = sensorMap.keySet();
            for (String key : keys) {
                Map<String, Object> oneSensorMap = new LinkedHashMap<>();
                oneSensorMap.put("monitorPointName", monitorPointMap.get("name"));
                oneSensorMap.put("deviceName", device.get("name"));
                oneSensorMap.put("sersorKey", sensorMap.get(key) + "(" + device_sensorUnit_map.get(key) + ")");
                for (String day : dayList) {
                    for (Map<String, Object> dataMap : dataList) {
                        JSONObject dataJson = JSONObject.parseObject(dataMap.get("json").toString());
                        if (dataMap.get("time").toString().equals(day + " 00:00:00.0")) {
                            oneSensorMap.put(dataMap.get("time").toString().substring(0, 10), dataJson.getJSONArray(key).get(0));
                            break;
                        } else {
                            continue;
                        }
                    }
                    if (!oneSensorMap.containsKey(day)) {
                        oneSensorMap.put(day, "");
                    }
                }
 
                Double avg = 0.0;
                if (sameDayHourlyList != null) {
                    for (Map sameDayHourlyMap : sameDayHourlyList) {
                        List<Double> arr = new ArrayList<>();
                        JSONObject hourlyJson = JSONObject.parseObject(sameDayHourlyMap.get("json").toString());
                        arr.add(Double.parseDouble(hourlyJson.getJSONArray(key).get(0).toString()));
                        Double sum = 0.0;
                        for (int i = 0; i < arr.size(); i++) {
                            sum += arr.get(i);
                        }
                        avg = sum / arr.size();
                    }
                    oneSensorMap.put(nowTime, avg);
                }
                list.add(oneSensorMap);
            }
        } else if (startTime.length() == 13 && endTime.length() == 13) {
            StringBuilder startTime_sb = new StringBuilder(startTime);
            startTime_sb.replace(10, 11, " ");
            startTime = startTime_sb.toString() + ":00:00";
            StringBuilder endTime_sb = new StringBuilder(endTime);
            endTime_sb.replace(10, 11, " ");
            endTime = endTime_sb.toString() + ":00:00";
 
            List<String> hoursList = DatesUtil.findHoursStr(startTime, endTime);
            //System.out.println("hoursList:"+hoursList);
 
            List<Map<String, Object>> hourlyList = historyHourlyService.getDataByTimeSlot(mac, startTime, endTime);
            if (hourlyList.isEmpty()) {
                return null;
            }
            Set<String> keys = sensorMap.keySet();
            for (String key : keys) {
                Map<String, Object> oneSensorMap = new LinkedHashMap<>();
                oneSensorMap.put("monitorPointName", monitorPointMap.get("name"));
                oneSensorMap.put("deviceName", device.get("name"));
                oneSensorMap.put("sersorKey", sensorMap.get(key) + "(" + device_sensorUnit_map.get(key) + ")");
                for (String hour : hoursList) {
                    for (Map<String, Object> hourlyMap : hourlyList) {
                        JSONObject dataJson = JSONObject.parseObject(hourlyMap.get("json").toString());
                        if (hourlyMap.get("time").toString().equals(hour + ".0")) {
                            if (dataJson.getJSONArray(key) != null) {
                                oneSensorMap.put(hourlyMap.get("time").toString().substring(0, 19), dataJson.getJSONArray(key).get(0));
                                break;
                            }
                        } else {
                            continue;
                        }
                    }
                    if (!oneSensorMap.containsKey(hour)) {
                        oneSensorMap.put(hour, "");
                    }
                }
                /*for (Map<String, Object> hourlyMap: hourlyList) {
                    JSONObject hourlyJson = JSONObject.parseObject(hourlyMap.get("json").toString());
                    oneSensorMap.put(hourlyMap.get("time").toString().substring(0,19),hourlyJson.getJSONArray(key).get(2));
 
                }*/
                list.add(oneSensorMap);
            }
        } else {
            return null;
        }
        return new ResultBean<List<Map<String, Object>>>(list);
    }
 
 
    @GetMapping("/contrastFactor")
    @ApiOperation(value = "因子对比", notes = "因子对比")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "mac", value = "设备mac", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensor", value = "因子", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19、20、21)", required = true, paramType = "query", dataType = "String")})
    public ResultBean<List<Map<String, Object>>> contrastFactor(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        List list = historyHourlyService.getDataByMacAndTime(parameters);
        //System.out.println(list);
        return new ResultBean<List<Map<String, Object>>>(list);
    }
 
    @GetMapping("/getAlarm")
    @ResponseBody
    public List<DeviceRoad> getAlarm(@Param("windData") String windData, @Param("code") String code, @Param("mac") String mac, @Param("speedLevel") String speedLevel) {
        List<DeviceRoad> alarmData = deviceRoadService.getAlarmData(windData, code, mac, speedLevel);
        return alarmData;
    }
 
    @GetMapping("multiDeviceContrast")
    @ApiOperation(value = "多设备因子对比", notes = "多设备因子对比")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "macs", value = "设备mac,如有多个用逗号分隔", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间,日期(格式:2018-03-12)", required = true, paramType = "query", dataType = "String"),})
    public ResultBean<List<Map<String, Object>>> multiDeviceSensor(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        ParameterUtils.getTimeType4Time(parameters);
        List<Map<String, Object>> list = historyMinutelyService.getMultiDeviceSensorData(parameters);
        return new ResultBean<List<Map<String, Object>>>(list);
    }
 
 
    @PostMapping("/tellAlarm")
    @ResponseBody
    public List<List> tellAlarm(String states, String orgId, String accountId, String states1, String regionCode) {
        JSONArray stateList = JSONArray.parseArray(states);//最新的设备数据
        JSONArray stateList1 = JSONArray.parseArray(states1);//前10秒的设备数据
        List<List> lookList = new ArrayList<>();
        Map params = new HashMap();
        String lookString = "";
        //判断前十秒数据和现在数据是否相等,如果不相等进入方法
        //第一次进入接口前十秒数据为null
        if (stateList1 != null && !states.equals(states1)) {
            List<Map> listDevice = JSONObject.parseArray(stateList.toJSONString(), Map.class);
            List<Map> listDevice1 = JSONObject.parseArray(stateList1.toJSONString(), Map.class);
            //将所有设备放到同一个集合下
            List<Map> deviceList = new ArrayList<Map>();
            List<Map> deviceList1 = new ArrayList<Map>();
            //存放所有组织的id
            List orgList = new ArrayList();
            for (Map devices : listDevice) {
                int monitorId = Integer.parseInt((String) devices.get("id"));
                MonitorPoint monitorPoint = monitorPointService.byIdGetMonitorPoint(monitorId);
                int org_id = monitorPoint.getOrganizationId();
                orgList.add(org_id);
                List<Map> devicesList = (List<Map>) devices.get("devices");
                if (!devicesList.isEmpty()) {
                    if (devicesList.size() > 1) {
                        for (Map map : devicesList) {
                            deviceList.add(map);
                        }
                    } else {
                        deviceList.add((Map) ((List) devices.get("devices")).get(0));
                    }
                }
            }
            for (Map devices1 : listDevice1) {
                int monitorId = Integer.parseInt((String) devices1.get("id"));
                MonitorPoint monitorPoint = monitorPointService.byIdGetMonitorPoint(monitorId);
                int org_id = monitorPoint.getOrganizationId();
                List<Map> devicesList = (List<Map>) devices1.get("devices");
                if (!devicesList.isEmpty()) {
                    if (devicesList.size() > 1) {
                        for (Map map : devicesList) {
                            deviceList1.add(map);
                        }
                    } else {
                        deviceList1.add((Map) ((List) devices1.get("devices")).get(0));
                    }
                }
            }
            List<String> macList = new ArrayList<String>();
            //获得两个时间的设备状态改变的mac号
            for (Map map : deviceList) {
                String state = (String) map.get("state");
                String mac = (String) map.get("mac");
                for (Map map1 : deviceList1) {
                    String state1 = (String) map1.get("state");
                    String mac1 = (String) map1.get("mac");
                    if (mac.equals(mac1)) {
                        if (Integer.parseInt(state) > Integer.parseInt(state1) && Integer.parseInt(state) != 4 /*&& Integer.parseInt(state1) == 0*/) {
                            macList.add(mac + "-" + state + "-" + state1);
                        }
                    }
                }
            }
            //存放不重合的数组
            LinkedHashSet<Integer> orgS = new LinkedHashSet<Integer>(orgList);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date(System.currentTimeMillis());
            Date date1 = new Date(System.currentTimeMillis() - 1000);
            //系统当前时间
            String time = formatter.format(date);
            //系统当前时间的前一秒
            String time1 = formatter.format(date1);
            List<Map> alarmList = new ArrayList<Map>();
            for (Integer org : orgS) {
                int orgNum = alarmConfigService.containOrgId(org);
                Map<String, Object> eMap = new HashMap<String, Object>();
                if (orgNum == 1) {
                    String alarmConfig = alarmConfigService.getValueByOrganizationId(Integer.parseInt(String.valueOf(org)));
                    Map hashMap = JSON.parseObject(alarmConfig, HashMap.class);
                    Map alarmLevels = (Map) hashMap.get("alarmLevels");
                    //数据库因子表只有106个因子
                    for (int i = 1; i < 106; i++) {
                        if (alarmLevels.containsKey("e" + i)) {
                            Map map = (Map) alarmLevels.get("e" + i);
                            if (!map.isEmpty()) {
                                Integer enable = (Integer) map.get("enable");
                                List increment = (List) map.get("increment");
                                if (enable == 1) {
                                    if (!(increment.get(0).toString().equals("0") && increment.get(1).toString().equals("0"))) {
                                        eMap.put("e" + i, increment);
                                    } else {
                                        continue;
                                    }
                                } else {
                                    continue;
                                }
                            }
                        }
                    }
                } else {
                    String defultAlarm = dictionaryDataService.getDefultAlarm();
                    Map hashMap = JSON.parseObject(defultAlarm, HashMap.class);
                    Map alarmLevels = (Map) hashMap.get("alarmLevels");
                    //数据库因子表只有106个因子
                    for (int i = 1; i < 106; i++) {
                        if (alarmLevels.containsKey("e" + i)) {
                            Map map = (Map) alarmLevels.get("e" + i);
                            if (!map.isEmpty()) {
                                Integer enable = (Integer) map.get("enable");
                                List increment = (List) map.get("increment");
                                if (enable == 1) {
                                    if (!(increment.get(0).toString().equals("0") && increment.get(1).toString().equals("0"))) {
                                        eMap.put("e" + i, increment);
                                    } else {
                                        continue;
                                    }
                                } else {
                                    continue;
                                }
                            }
                        }
                    }
                }
                Map map = new HashMap();
                map.put("eMap", eMap);
                map.put("org", org);
                alarmList.add(map);
            }
            for (Map aEMap : alarmList) {
                List<Map> values = new ArrayList<Map>();
                if (macList.size() > 0) {
                    for (String sMac : macList) {
                        String[] aMac = sMac.split("-");
                        String mac = aMac[0];
                        //因为数据库数据是两秒钟插入一条,所以通过两个时间区间获取一条数据,防止一个时间获取数据为空的情况
                        String value = historyService.getValueByMacAndTime(mac, time, time1);
                        Map<String, String> map = new HashMap<String, String>();
                        if (value == null) {
                            Date date2 = new Date(System.currentTimeMillis() - 2000);
                            //系统当前时间的前两秒
                            String time2 = formatter.format(date1);
                            value = historyService.getValueByMacAndTime(mac, time, time2);
                            if (value == null) {
                                Date date3 = new Date(System.currentTimeMillis() - 3000);
                                //系统当前时间的前三秒
                                String time3 = formatter.format(date1);
                                value = historyService.getValueByMacAndTime(mac, time, time3);
                            }
                        }
                        if (value != null) {
                            map.put("mac", mac);
                            map.put("value", value);
                            map.put("state", aMac[1]);
                            map.put("state1", aMac[2]);
                            values.add(map);
                        } else {
                            continue;
                        }
                    }
                }
 
                if (values.size() > 0 && values.size() == macList.size()) {
                    for (Map dataMap : values) {
                        String oId = deviceService.byMacGetOrgId((String) dataMap.get("mac"));
                        if (!(aEMap.get("org").toString()).equals(oId)) {
                            continue;
                        }
                        List<String> list = new ArrayList<String>();
                        Map sensorMap = JSONObject.parseObject((String) dataMap.get("value"));
                        Iterator<String> iter = sensorMap.keySet().iterator();
                        while (iter.hasNext()) {
                            String key = iter.next();
                            list.add(key);
                        }
                        String state = (String) dataMap.get("state");
                        String state1 = (String) dataMap.get("state1");
                        List<Map> mapList = new ArrayList();
                        for (String key : list) {
                            if (((Map) aEMap.get("eMap")).containsKey(key)) {
                                Double val = Double.valueOf(sensorMap.get(key).toString());
                                List valueList = (List) ((Map) aEMap.get("eMap")).get(key);
                                Device device = deviceService.byMacGetDevice((String) dataMap.get("mac"));
                                Map<String, Object> sensors = sensorService.getSensorBySensorKey(key);
                                if (key.equals("e1") || key.equals("e2") || key.equals("e10") || key.equals("e11") || key.equals("e15") || key.equals("e16")) {
                                    //判断六参因子超标
                                    if ((state1.equals("0") || state1.equals("1")) && Integer.parseInt(state) > 1) {
                                        if (val > Double.valueOf(String.valueOf(valueList.get(1)))) {
                                            Map lookMap = new HashMap();
                                            lookMap.put("time", time);
                                            lookMap.put("name", device.getName());
                                            lookMap.put("sensor", sensors.get("description"));
                                            lookMap.put("value", val + "" + sensors.get("unit"));
                                            mapList.add(lookMap);
                                            //lookString = time+" "+device.getName()+sensors.get("description")+"="+val + sensors.get("unit")+"超标";
                                            //System.out.println(time + "====" + device.getName() + "=====" + sensors.get("description") + "======" + val + sensors.get("unit"));
                                        }
                                    }
                                } else {//判断非六参因子超标
                                    if (state1.equals("0")) {
                                        if (val > Double.valueOf(String.valueOf(valueList.get(0)))) {
                                            Map lookMap = new HashMap();
                                            lookMap.put("time", time);
                                            lookMap.put("name", device.getName());
                                            lookMap.put("sensor", sensors.get("description"));
                                            lookMap.put("value", val + "" + sensors.get("unit"));
                                            mapList.add(lookMap);
                                        }
                                    }
                                }
 
                            }
                        }
                        if (mapList.size() > 0) {
                            lookList.add(mapList);
                        } else {
                            continue;
                        }
                    }
                }
            }
        }
        return lookList;
    }
 
    /*  @GetMapping("/lianxian")
      @ApiOperation(value = "连线", notes = "连线" )
      @GetMapping("multiDeviceContrast")
      @ApiOperation(value = "多设备因子对比", notes = "多设备因子对比")
      @ApiImplicitParams(value = {
              @ApiImplicitParam(name = "macs", value = "设备mac,如有多个用逗号分隔", required = true, paramType = "query", dataType = "String"),
              @ApiImplicitParam(name = "sensorKey", value = "传感器key", required = true, paramType = "query", dataType = "String"),
              @ApiImplicitParam(name = "time", value = "时间,日期(格式:2018-03-12)", required = true, paramType = "query", dataType = "String"),})
      public ResultBean<List<Map<String, Object>>> multiDeviceSensor(HttpServletRequest request) throws Exception {
          Map<String, Object> parameters = getParametersStartingWith(request, null);
          ParameterUtils.getTimeType4Time(parameters);
          List<Map<String, Object>> list = historyMinutelyService.getMultiDeviceSensorData(parameters);
          return new ResultBean<List<Map<String, Object>>>(list);
      }
 
      /*
      * 根据大屏版本号获取版本更新信息
      */
    @GetMapping("screenVersion")
    public Map<String, Object> getScreenVersion(HttpServletRequest request) {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        String version = parameters.get("version").toString();
        return screenVersionService.getScreenVersion(version);
    }
 
    @GetMapping("allDeviceExcel")
    @ApiOperation(value = "所有设备多因子数据报表", notes = "所有设备多因子数据报表")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitorPoint", value = "监控站点id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sensorKey", value = "传感器key,多个逗号隔开", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "起始时间(格式:2020-08-03)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间(格式:2020-08-04)", required = false, paramType = "query", dataType = "String")})
    public ResultBean<List<Map<String, Object>>> getAllDeviceDataToExcel(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        List<Map<String, Object>> list = historyMinutelyService.getAllDeviceDataToExcel(parameters);
        return new ResultBean<List<Map<String, Object>>>(list);
    }
 
    /*@PostMapping("insertAdjustValue")
    @ApiOperation(value = "所有设备多因子数据报表", notes = "所有设备多因子数据报表")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "设备id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间(格式08:30:00)", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "dataArray", value = "公式", required = false, paramType = "query", dataType = "String")})
    public void insertAdjustValue(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request, null);
        int device_id = Integer.parseInt(parameters.get("id").toString());
        String hour_minute_second = parameters.get("time").toString();
        String[] arr = hour_minute_second.split(":");
        int seconds = Integer.parseInt(arr[0])*3600+Integer.parseInt(arr[1])*60+Integer.parseInt(arr[2]);
        String value = parameters.get("dataArray").toString();
        deviceAdjustValueTimingService.insertData(device_id,seconds,value);;
    }*/
 
    @PostMapping("insertAdjustValue")
    public  int insertAdjustValue(@RequestBody HashMap map){
        try{
            int device_id = Integer.parseInt(map.get("id").toString());
            String time = map.get("time").toString();
            String[] arr = time.split(":");
            int seconds = Integer.parseInt(arr[0])*3600+Integer.parseInt(arr[1])*60+Integer.parseInt(arr[2]);
            //String t = URLEncoder.encode(参数,"UTF-8")
            List list = (List) map.get("dataArray");
            String val="";
            for (int i = 0; i <list.size() ; i++) {
                if (i==0){
                    val=val+list.get(i);
                }else {
                    val=val+","+list.get(i);
                }
            }
            String value = "{"+val+"}";
            deviceAdjustValueTimingService.insertData(device_id,seconds,value);
            return 1;
        }catch (Exception e){
            log.warn(e);
        }
        return 0;
    }
 
    @RequestMapping("/biaozhun")
    @ResponseBody
    public List<Device> queryDevice(String macOrName){
        List<Device> deviceList = new ArrayList<>();
        if (!macOrName.equals("")){
             deviceList= deviceService.getDevice(macOrName);
        }
        return deviceList;
    }
 
    @RequestMapping("/getBiaoZhun")
    @ResponseBody
    public List<DeviceAdjustValueTiming> getBiaoZhun(String id){
        List<DeviceAdjustValueTiming> dataByDeviceid = deviceAdjustValueTimingService.getDataByDeviceid(Integer.parseInt(id));
        for (DeviceAdjustValueTiming deviceAdjustValueTiming : dataByDeviceid) {
            int seconds = Integer.parseInt(deviceAdjustValueTiming.getSeconds());
            String hour = String.valueOf(seconds/3600);
            int millAndSeconds = seconds%3600;
            String mill = String.valueOf(millAndSeconds/60);
            String second = String.valueOf(millAndSeconds%60);
            if (hour.length()<2){
                hour="0"+hour;
            }
            if (mill.length()<2){
                mill="0"+mill;
            }
            if (second.length()<2){
                second="0"+second;
            }
            String time = hour+":"+mill+":"+second;
            Map<String, String> value = deviceAdjustValueTiming.getValue();
            Collection<String> values = value.values();
            deviceAdjustValueTiming.setSeconds(time);
        }
        return dataByDeviceid;
    }
 
 
    @RequestMapping("/getSensor")
    @ResponseBody
    public  List<Map<String, Object>> getSensor(String id){
        List<Map<String, Object>> allSensors = sensorService.getSensorByDeviceId(id);
        return allSensors;
    }
 
    @RequestMapping("/deleteBiaoZhun")
    @ResponseBody
    public int deleteBiaoZhun(String id){
        int i= deviceAdjustValueTimingService.delete(id);
        return i;
    }
 
 
    @GetMapping("/monitorAVGData")
    @ApiOperation(value = "monitor平均数据导出", notes = "monitor平均数据导出")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "monitorPointIds", value = "多个monitorid", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "time", value = "时间(格式:2020-03-19)", required = true, paramType = "query", dataType = "String")})
    public ResultBean<List<Map<String,Object>>> monitorAVGData(HttpServletRequest request) throws Exception {
        Map<String, Object> parameters = getParametersStartingWith(request, null);
        String monitorPointIds = (String) parameters.get("monitorPointIds");
        String time = (String) parameters.get("time");
        time = time+" 00:00:00";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd mm:HH:ss");//注意月份是MM
        Date date = simpleDateFormat.parse(time);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE,+1);
        String date1= simpleDateFormat.format(date);
        String date2= simpleDateFormat.format(calendar.getTime());
        String[] mIds = monitorPointIds.split(",");
        List<List<Map<String,Object>>> lists = new ArrayList<>();
        if (mIds.length==1 && mIds.length!=0){
            String mId = mIds[0];
            List<Map<String,Object>> dataAvbByMIdAndTime = historyHourlyService.getDataAvbByMIdAndTime(mId, date1, date2);
            Double maxO3 = Double.parseDouble(dataAvbByMIdAndTime.get(dataAvbByMIdAndTime.size() - 1).get("maxO3").toString());
            Map<String,Object> dailyAvgData =new HashMap<>();
            if (dataAvbByMIdAndTime.get(dataAvbByMIdAndTime.size() - 2).get("data")!=""){
                dailyAvgData = (Map<String, Object>) dataAvbByMIdAndTime.get(dataAvbByMIdAndTime.size() - 2).get("data");
                dailyAvgData.put("maxO3_8h",new BigDecimal(maxO3).setScale(0,BigDecimal.ROUND_HALF_UP).doubleValue());
            }else {
                dailyAvgData= historyHourlyService.getAvgDataByMId(mId, date1, date2);
                if (dailyAvgData!=null){
                    dailyAvgData.put("maxO3_8h",new BigDecimal(maxO3).setScale(0,BigDecimal.ROUND_HALF_UP).doubleValue());
                }else {
                    dailyAvgData = new HashMap<>();
                    dailyAvgData.put("PM2_5","");
                    dailyAvgData.put("NO2","");
                    dailyAvgData.put("SO2","");
                    dailyAvgData.put("PM10","");
                    dailyAvgData.put("O3_day","");
                    dailyAvgData.put("CO","");
                }
            }
            dataAvbByMIdAndTime.remove(dataAvbByMIdAndTime.size() - 1);
            dataAvbByMIdAndTime.remove(dataAvbByMIdAndTime.size() - 1);
            Map<String,Object> dayMap = new HashMap<>();
            dayMap.put("data",dailyAvgData);
            dayMap.put("time",date1.substring(0,11));
            dataAvbByMIdAndTime.add(dayMap);
            for (int i = 0; i <dataAvbByMIdAndTime.size() ; i++) {
                if (i!=dataAvbByMIdAndTime.size()-1){
                    Map<String, Object> map1 = AQICalculation2.hourlyAQI((Map<String, Object>) dataAvbByMIdAndTime.get(i).get("data"));
                    if (Double.parseDouble(map1.get("AQI").toString())>50.0){
                        ((Map<String, Object>) dataAvbByMIdAndTime.get(i).get("data")).put("primary_pollutants",map1.get("maxSensor"));
                        ((Map<String, Object>) dataAvbByMIdAndTime.get(i).get("data")).put("AQI",map1.get("AQI"));
                    }else {
                        ((Map<String, Object>) dataAvbByMIdAndTime.get(i).get("data")).put("primary_pollutants","-");
                        ((Map<String, Object>) dataAvbByMIdAndTime.get(i).get("data")).put("AQI",map1.get("AQI"));
                    }
                }else {
                    Map<String, Object> map1 = AQICalculation2.dayAQI((Map<String, Object>) dataAvbByMIdAndTime.get(i).get("data"));
                    if (map1.get("AQI").toString().equals("")){
                        break;
                    }
                        if (Double.parseDouble(map1.get("AQI").toString())>50.0){
                            ((Map<String, Object>) dataAvbByMIdAndTime.get(i).get("data")).put("primary_pollutants",map1.get("maxSensor"));
                            ((Map<String, Object>) dataAvbByMIdAndTime.get(i).get("data")).put("AQI",map1.get("AQI"));
                        }else {
                            ((Map<String, Object>) dataAvbByMIdAndTime.get(i).get("data")).put("primary_pollutants","-");
                            ((Map<String, Object>) dataAvbByMIdAndTime.get(i).get("data")).put("AQI",map1.get("AQI"));
                        }
                }
            }
            List timeList = new ArrayList();
            for (int q = 0; q < dataAvbByMIdAndTime.size(); q++) {
                timeList.add(dataAvbByMIdAndTime.get(q).get("time"));
            }
            if (dataAvbByMIdAndTime.size()<25){
                for (int j = 1; j < 25; j++) {
                    Map<String,Object> map = null;
                    for (int q = 0; q < dataAvbByMIdAndTime.size(); q++) {
                        if (dataAvbByMIdAndTime.get(q).get("time").toString().length() > 2){
                            continue;
                        }else {
                            // System.out.println(Integer.parseInt(dataAvbByMIdAndTime.get(q).get("time").toString())+"==="+j);
                            String sj="";
                            if (j<10){
                                sj="0"+j;
                            }else {
                                if (j==24){
                                    sj="00";
                                }else {
                                    sj=""+j;
                                }
                            }
                            if (!timeList.contains(sj)){
                                map = new HashMap<>();
                                map.put("time",sj);
                                Map map1 = new HashMap();
                                map1.put("PM2_5","");
                                map1.put("NO2","");
                                map1.put("primary_pollutants","-");
                                map1.put("SO2","");
                                map1.put("O3","");
                                map1.put("PM10","");
                                map1.put("O3_8h","");
                                map1.put("CO","");
                                map1.put("AQI","");
                                map.put("data",map1);
                                dataAvbByMIdAndTime.add(map);
                                break;
                            }else {
                                break;
                            }
                        }
                    }
                }
            }
             /* for (int i1 = 0; i1 < dataAvbByMIdAndTime.size(); i1++) {
                    System.out.println(dataAvbByMIdAndTime.get(i1));
                }*/
            Collections.sort(dataAvbByMIdAndTime, new Comparator<Map<String, Object>>(){
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    String name1 =(String)o1.get("time");//name1是从你list里面拿出来的一个
                    String name2= (String)o2.get("time"); //name1是从你list里面拿出来的第二个name
                    return name1.compareTo(name2);
                }
            });
            Map map1 = dataAvbByMIdAndTime.get(0);
            dataAvbByMIdAndTime.remove(0);
            dataAvbByMIdAndTime.add(map1);
            for (int j = 0; j <dataAvbByMIdAndTime.size() ; j++) {
                if (dataAvbByMIdAndTime.get(j).get("time").toString().length()>2){
                    Map map2 = dataAvbByMIdAndTime.get(j);
                    dataAvbByMIdAndTime.remove(j);
                    dataAvbByMIdAndTime.add(map2);
                }
            }
            if (dataAvbByMIdAndTime.size()==1){
                dataAvbByMIdAndTime=null;
            }
            lists.add(dataAvbByMIdAndTime);
            //List<Device> devicesByMonitorPointId = deviceService.getDevicesByMonitorPointId(Integer.valueOf(mId));
        }else {
            for (int i = 0; i <mIds.length ; i++) {
                List<Map<String,Object>> dataAvbByMIdAndTime = historyHourlyService.getDataAvbByMIdAndTime(mIds[i], date1, date2);
                Double maxO3 = Double.parseDouble(dataAvbByMIdAndTime.get(dataAvbByMIdAndTime.size() - 1).get("maxO3").toString());
                Map<String,Object> dailyAvgData =new HashMap<>();
                if (dataAvbByMIdAndTime.get(dataAvbByMIdAndTime.size() - 2).get("data")!=""){
                    dailyAvgData = (Map<String, Object>) dataAvbByMIdAndTime.get(dataAvbByMIdAndTime.size() - 2).get("data");
                    dailyAvgData.put("maxO3_8h",new BigDecimal(maxO3).setScale(0,BigDecimal.ROUND_HALF_UP).doubleValue());
                }else {
                    dailyAvgData= historyHourlyService.getAvgDataByMId(mIds[i], date1, date2);
                    if (dailyAvgData!=null){
                        dailyAvgData.put("maxO3_8h",new BigDecimal(maxO3).setScale(0,BigDecimal.ROUND_HALF_UP).doubleValue());
                    }else {
                        dailyAvgData = new HashMap<>();
                        dailyAvgData.put("PM2_5","");
                        dailyAvgData.put("NO2","");
                        dailyAvgData.put("SO2","");
                        dailyAvgData.put("PM10","");
                        dailyAvgData.put("O3_day","");
                        dailyAvgData.put("CO","");
                    }
                }
                dataAvbByMIdAndTime.remove(dataAvbByMIdAndTime.size() - 1);
                dataAvbByMIdAndTime.remove(dataAvbByMIdAndTime.size() - 1);
                Map<String,Object> dayMap = new HashMap<>();
                dayMap.put("data",dailyAvgData);
                dayMap.put("time",date1.substring(0,11));
                dataAvbByMIdAndTime.add(dayMap);
                List timeList = new ArrayList();
                for (int q = 0; q < dataAvbByMIdAndTime.size(); q++) {
                    timeList.add(dataAvbByMIdAndTime.get(q).get("time"));
                }
                  if (dataAvbByMIdAndTime.size()<25){
                    for (int j = 1; j < 25; j++) {
                        Map<String,Object> map = null;
                        for (int q = 0; q < dataAvbByMIdAndTime.size(); q++) {
                            if (dataAvbByMIdAndTime.get(q).get("time").toString().length() > 2){
                                continue;
                            }else {
                               // System.out.println(Integer.parseInt(dataAvbByMIdAndTime.get(q).get("time").toString())+"==="+j);
                                String sj="";
                                if (j<10){
                                    sj="0"+j;
                                }else {
                                    if (j==24){
                                        sj="00";
                                    }else {
                                        sj=""+j;
                                    }
                                }
                                if (!timeList.contains(sj)){
                                    map = new HashMap<>();
                                    map.put("time",sj);
                                    Map map1 = new HashMap();
                                    map1.put("PM2_5","");
                                    map1.put("NO2","");
                                    map1.put("SO2","");
                                    map1.put("O3","");
                                    map1.put("PM10","");
                                    map1.put("O3_8h","");
                                    map1.put("CO","");
                                    map.put("data",map1);
                                    dataAvbByMIdAndTime.add(map);
                                    break;
                                }else {
                                    break;
                                }
                            }
                        }
 
                    }
                }
                Collections.sort(dataAvbByMIdAndTime, new Comparator<Map<String, Object>>(){
                    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                        String name1 =(String)o1.get("time");//name1是从你list里面拿出来的一个
                        String name2= (String)o2.get("time"); //name1是从你list里面拿出来的第二个name
                        return name1.compareTo(name2);
                    }
                });
                Map map1 = dataAvbByMIdAndTime.get(0);
                dataAvbByMIdAndTime.remove(0);
                dataAvbByMIdAndTime.add(map1);
                for (int j = 0; j <dataAvbByMIdAndTime.size() ; j++) {
                    if (dataAvbByMIdAndTime.get(j).get("time").toString().length()>2){
                        Map map2 = dataAvbByMIdAndTime.get(j);
                        dataAvbByMIdAndTime.remove(j);
                        dataAvbByMIdAndTime.add(map2);
                    }
                }
                lists.add(dataAvbByMIdAndTime);
            }
            List<Map<String, Object>> dataByMonitorPoints = historyHourlyService.getDataByMonitorPoints(mIds, date1, date2);
            lists.add(dataByMonitorPoints);
        }
        List<Map<String, Object>> rList =new ArrayList<>();
        if (lists.size()==1 && lists.get(0)!=null){
            for (int i = 0; i < lists.get(0).size(); i++) {
                List list = new ArrayList();
                list.add(lists.get(0).get(i).get("data"));
                Map map = new HashMap();
                map.put("data",list);
                map.put("time",lists.get(0).get(i).get("time"));
                rList.add(map);
            }
 
        } else if (lists.size()==1 && lists.get(0)==null){
            rList.add(null);
        }else {
            for (int j = 0; j < lists.get(0).size(); j++) {
                Map<String, Object> listMap = new HashMap();
                List<Map> mapList = new ArrayList<>();
                if (lists.get(0).size() == 1) {
                    mapList.add(null);
                } else {
                    mapList.add((Map) lists.get(0).get(j).get("data"));
                }
                for (int i = 1; i < lists.size(); i++) {
                    if (lists.get(i).size() == 1) {
                        mapList.add(null);
                        listMap.put("data", mapList);
                    } else {
                        if (lists.get(0).get(j).get("time").equals(lists.get(i).get(j).get("time"))) {
                            mapList.add((Map) lists.get(i).get(j).get("data"));
                        }
                        listMap.put("time", lists.get(0).get(j).get("time"));
                        listMap.put("data", mapList);
                    }
                }
                rList.add(listMap);
            }
        }
        return new ResultBean<List<Map<String,Object>>>(rList);
    }
}