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
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
//using CloudWaterNetwork.Magnifier;
using DevExpress.Diagram.Core.Layout;
using DevExpress.XtraPrinting;
using Hydro.CommonBase;
using Hydro.Inp;
//using ConfigApp;
//using DevExpress.Diagram.Core.Layout;
//using DevExpress.DirectX.NativeInterop.Direct2D;
//using DevExpress.Utils.Extensions;
//using dict_py_Inner;
using Hydro.MapView;
using Hydro.MapView.Common;
using Newtonsoft.Json;
//using ReflectionManager_NameSpace;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.Remoting.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
//using static Hydro.Core.ObjectEnum;
using static Hydro.MapView.MapViewEnum;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.AxHost;
using static System.Windows.Forms.LinkLabel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
using Cursor = System.Windows.Forms.Cursor;
 
namespace Hydro.MapUI
{
    public partial class MapViewer : UserControl
    {
 
        #region 一、全局
 
 
        #region 初始化
        //public MapViewer()
        //{
        //    InitializeComponent();
        //    //_Template = new Template();
        //    //toolStrip1.Visible = false;
        //    MapCenter = PointF.Empty;
        //    zoom = 1.0f;
        //    DoubleBuffered = true;
        //    SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        //    BackColor = Color.Transparent;
 
        //}
        private bool _showToolBar = true;
        [DisplayName("显示工具栏")]
 
        public bool showToolBar
        {
            get
            {
                return _showToolBar;// this.panel1==null?true:Visible; 
            }
            set
            {
                _showToolBar = value;
                if (this.panel1 != null) this.panel1.Visible = value;
            }
        }
 
 
        private bool _showStatusBar = true;
        [DisplayName("显示状态栏")]
        public bool ShowStatusBar
        {
            get
            {
                return _showStatusBar;// this.panel1==null?true:Visible; 
            }
            set
            {
                _showStatusBar = value;
                if (this.statusStrip1 != null) this.statusStrip1.Visible = value;
            }
        }
        //public MapViewer()
        //{
        //    this.showToolBar = false;
        //    //this.showToolBar = false;
        //    InitializeComponent();
 
        //    MapCenter = PointF.Empty;
        //    zoom = 1.0f;
        //    DoubleBuffered = true;
        //    SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        //    BackColor = Color.Transparent;
 
 
        //}
        
        public MapViewer(bool showToolBar = false)
        {
 
            this.showToolBar = showToolBar;
            InitializeComponent();
 
            MapCenter = PointF.Empty;
            zoom = 1.0f;
            DoubleBuffered = true;
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            BackColor = Color.Transparent;
 
            //if (!showToolBar) this.panel1.Visible = false;
        }
        public MapViewer() 
        {
 
            this.showToolBar = false;
            InitializeComponent();
 
            MapCenter = PointF.Empty;
            zoom = 1.0f;
            DoubleBuffered = true;
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            BackColor = Color.Transparent;
 
        }
        private void MapViewer_Load(object sender, EventArgs e)
        {
            this.panel1.Visible = _showToolBar;
            this.statusStrip1.Visible = _showStatusBar;
 
 
            cb_Node_Colour.Items.Clear();
            cb_Link_Colour.Items.Clear();
            //repositoryItemComboBox1.Items.Add(ColourType.无);
            cb_Link_Colour.Items.Add(ColourType.无);
            int i = 0;
            //遍历ColourType
 
            // 遍历枚举类型
            foreach (ColourType colour in Enum.GetValues(typeof(ColourType)))
            {
                if (i <= Colour.NodeTypeCount)
                    cb_Node_Colour.Items.Add(colour);
                else
                    cb_Link_Colour.Items.Add(colour);
 
                i++;
            }
 
 
            cb_Node_Colour.SelectedIndex = 0;
 
            cb_Link_Colour.SelectedIndex = 0;
 
            
        }
 
        #endregion
 
 
        #region 对外开放,全局控制方法
 
        public bool LoadData(bool isDelCache = false)
        {
 
            if (_Template == null) return false;
            if (isDelCache || _Template.network == null)
            {
                if (!_Template.loadInpFile())
                {
                    //MessageBox.Show("读取地图失败");
                    _Template.network = new MapViewNetWork();
                    //return false;
                }
            }
 
 
            if (_ViewModel == null)
            {
                if (!_IsEditMode)
                {
                    if (param == null)
                        param = new dict<string, dynamic>();
                    _Template.network.LoadRepeaters(_Template.MaxLevel, param, _ViewModel, !_IsEditMode);
 
                }
                else
                {
                    if (param == null)
                        param = new dict<string, dynamic>();
                    _Template.network.LoadRepeaters(_Template.MaxLevel, param, null, !_IsEditMode);
                }
            }
            else
            {
                if (_IsEditMode)
                {
                    if (param == null)
                        param = new dict<string, dynamic>();
                    _Template.network.LoadRepeaters(_Template.MaxLevel, param, _ViewModel, !_IsEditMode);
 
                }
                else
                {
                    if (param == null)
                        param = new dict<string, dynamic>();
                    _Template.network.LoadRepeaters(_Template.MaxLevel, param, null, !_IsEditMode);
                }
 
            }
            if (GlobalObject.PropertyForm != null)
            {
                GlobalObject.PropertyForm.SetEnabled(_IsEditMode);
                GlobalObject.PropertyForm.SetNet(_Template.network);
                //_Template.network.MapObjects.AddUndoRedoSupport(GlobalObject.PropertyForm.propertyGrid);
            }
 
 
            SetStartEndPoint(_Template.Node1, _Template.Node2);
 
 
            return true;
        }
 
 
        Dictionary<TemplateType, bool> _ViewModel = null;
        public void Clear()
        {
            _Template = null;
            MapCenter = PointF.Empty;
            zoom = 1.0f;
            Rotation = 0;
            RotationF = 90;
            Invalidate();
        }
        public void SetData(Template template, dict<string, dynamic> param = null, Dictionary<TemplateType, bool> viewMode = null)
        {
            this.param = param;
            bool reLoad = _Template == template;
            this._Template = template;
            this._ViewModel = viewMode;
 
 
            //if ( _Template?.Floors!=null)
            //{
 
            //    _Template.Floors.ForEach(f=> 
            //    {
            //        var btn = new ToolStripButton("  "+f.Name+"  ");
            //        btn.Click += (s, e) =>
            //        {
            //            this.mapOption.ShowFloor = f.FloorIndex;
            //            if (f.MapView != null ) 
            //            { 
            //                this.mapOption= f.MapView.Copy();
            //            }
            //            this.Invalidate();
            //        };
            //        ToolStripMenuItem_Floor.DropDownItems.Add(btn);
 
            //    });
            //}
 
            //_Template.network = null;
            if (!LoadData()) return;
            //LoadData();
            //    temp.network.LoadRepeaters();
 
            //    map.SetStartEndPoint(temp.Node1, temp.Node2);
 
            if (!reLoad)
            {
                if (_Template.view == null)
                    InitCenter();
                else
                {
                    //MapCenter = _Template.view.Center;
                    //zoom = _Template.view.zoom;
                    //Rotation = _Template.view.rotation;
                    //RotationF = _Template.view.rotationF;
                    this.mapOption = _Template.view.Copy();
                    SetInvalidated();
                }
            }
            刷新楼层ToolStripMenuItem_Click(1, new EventArgs());
            //Invalidate();
        }
 
        private void InitCenter()
        {
            //MapCenter
            var p = PointF.Empty;
            float x0 = 99999999999f, y0 = 99999999999f, x1 = -99999999999f, y1 = -99999999999f;
 
            foreach (NodeViewModel junction in _Nodes)
            {
                p.X += (float)junction.X;
                p.Y += (float)junction.Y;
                if (x0 > junction.X) x0 = junction.X;
                if (y0 > junction.Y) y0 = junction.Y;
                if (x1 < junction.X) x1 = junction.X;
                if (y1 < junction.Y) y1 = junction.Y;
            }
 
            float x_span = x1 - x0, y_span = y1 - y0;
 
            zoom = Math.Min(Width / x_span, Height / y_span);
            zoom = Math.Max(zoom, MinZoom);
            zoom = Math.Min(zoom, MaxZoom);
 
            Rotation = 0;
            RotationF = 90;
 
 
            if (_Nodes.Count > 0)
            {
                p.X /= _Nodes.Count;
                p.Y /= _Nodes.Count;
            }
            MapCenter = p;
        }
 
        public void SetInvalidated()
        {
 
            Invalidate();
 
 
        }
 
        public void SetStartEndPoint(String node1, string node2)
        {
            _StartPoint = node1;
            _EndPoint = node2;
            Invalidate();
        }
        public void Set3DView(bool is3Dview, double 俯视角度)
 
        {
            this.RotationF = 俯视角度;
            this.is3Dview = is3Dview;
            Invalidate();
        }
 
 
 
        public void SetRotation(double d)
        {
            this.Rotation = d;
            Invalidate();
        }
 
        #endregion
 
 
        #region 基础坐标转换方法
        /// <summary>
        /// 将屏幕坐标转换为世界坐标。输入屏幕坐标 (x,y),返回世界坐标 (wx, wy)。
        /// </summary>
        /// <param name="screenPos"></param>
        /// <returns></returns>
        private PointF ScreenToVMap(PointF screenPos, float z = 0)
        {
 
            var centerX = Width / 2;
            var centerY = Height / 2;
            var worldX = (screenPos.X - centerX - Z(z).X) / Zoom.X + MapCenter.X;
            var worldY = (screenPos.Y - centerY) / Zoom.Y + 0;
            //if (is3Dview) worldY = -(screenPos.Y - centerY + 2 * z) / (0.5f* zoom) + center.Y;
            return new PointF(worldX, worldY);
        }
 
 
        /// <summary>
        /// 将屏幕坐标转换为世界坐标。输入屏幕坐标 (x,y),返回世界坐标 (wx, wy)。
        /// </summary>
        /// <param name="screenPos"></param>
        /// <returns></returns>
        private PointF ScreenToMap(PointF screenPos, float z = 0)
        {
 
            var centerX = Width / 2;
            var centerY = Height / 2;
            var worldX = (screenPos.X - centerX - Z(z).X) / Zoom.X + MapCenter.X;
            var worldY = (screenPos.Y - centerY - Z(z).Y) / Zoom.Y + MapCenter.Y;
            //if (is3Dview) worldY = -(screenPos.Y - centerY + 2 * z) / (0.5f* zoom) + center.Y;
            return new PointF(worldX, worldY);
        }
 
        private PointF MapToScreen(PointF mapPos, float z = 0)
        {
 
            var centerX = Width / 2;
            var centerY = Height / 2;
            var screenX = (mapPos.X - MapCenter.X) * Zoom.X + centerX + Z(z).X;
            var screenY = (mapPos.Y - MapCenter.Y) * Zoom.Y + centerY + Z(z).Y;
            //if (is3Dview) screenY = -(mapPos.Y - center.Y) * (0.5f * zoom) + centerY - 2 * z;
            return new PointF(screenX, screenY);
        }
 
 
        // 根据旋转角度计算旋转后的坐标
 
 
        // 根据旋转角度计算旋转后的坐标
        private PointF Get平面旋转Point(PointF p)
        {
            PointF center = MapCenter;
            double radian = Rotation * Math.PI / 180;  // 角度转弧度
            float x = (float)(Math.Cos(radian) * (p.X - center.X) - Math.Sin(radian) * (p.Y - center.Y) + center.X);
            float y = (float)(Math.Sin(radian) * (p.X - center.X) + Math.Cos(radian) * (p.Y - center.Y) + center.Y);
            return new PointF(x, y);
        }
        private PointF Get平面还原Point(PointF p)
        {
            PointF center = MapCenter;
            double radian = -Rotation * Math.PI / 180;  // 角度转弧度
            float x = (float)(Math.Cos(radian) * (p.X - center.X) - Math.Sin(radian) * (p.Y - center.Y) + center.X);
            float y = (float)(Math.Sin(radian) * (p.X - center.X) + Math.Cos(radian) * (p.Y - center.Y) + center.Y);
            return new PointF(x, y);
        }
 
 
 
        private PointF Get俯视角旋转Point(PointF p, float z)
        {
            PointF center = MapCenter;
            double radian_fushi = 俯视弧度;
            float sin = (float)Math.Sin(radian_fushi);
            float cos = (float)Math.Cos(radian_fushi);
            float x = (float)p.X;
            float y = (float)(sin * (p.Y - center.Y) + center.Y) + cos * z;
            return new PointF(x, y);
        }
        private PointF Get俯视角还原Point(PointF p, float z)
        {
            PointF center = MapCenter;
            double radian_fushi = 俯视弧度;
            float sin = (float)Math.Sin(radian_fushi);
            float cos = (float)Math.Cos(radian_fushi);
            float x = (float)p.X;
            float y = (p.Y - center.Y - cos * z) / sin + center.Y;
            return new PointF(x, y);
        }
 
 
        private PointF GetRotateVector(PointF p, PointF p0)
        {
 
            double radian = Rotation * Math.PI / 180;  // 角度转弧度
            float x = (float)(Math.Cos(radian) * (p.X - p0.X) - Math.Sin(radian) * (p.Y - p0.Y));
            float y = (float)(Math.Sin(radian) * (p.X - p0.X) + Math.Cos(radian) * (p.Y - p0.Y));
            return new PointF(x, y);
        }
        /// <summary>
        /// 获取地图投影坐标
        /// </summary>
        /// <param name="point"></param>
        /// <param name="z"></param>
        /// <returns></returns>
        private PointF WorldPointToMapPoint(PointF point, float z, PointF3D offset = null)
        {
            if (offset == null) offset = new PointF3D(0, 0, 0);
            point = new PointF(point.X + offset.X, point.Y + offset.Y);
 
            var pointR = Get平面旋转Point(point);
 
            var pointT = Get俯视角旋转Point(pointR, z + offset.Z);
 
            //var n=new PointF((float)pointR.X - Z(z).X, (float)(pointR.Y - Z(z).Y));
            return pointT;
        }
        private PointF WorldPointToMapPoint(PointF3D point, PointF3D offset = null)
        {
            return WorldPointToMapPoint(new PointF(point.X, point.Y), point.Z, offset);
 
        }
        private PointF WorldPointToMapPoint(NodeViewModel junction, PointF3D offset = null)
        {
            PointF p;
            if (junction == null) return new PointF(0, 0);
            p = WorldPointToMapPoint(junction.Position, junction.Elev, offset);
            return p;
 
        }
        private List<PointF> WorldPointToMapPoint(LinkViewModel pipe, PointF3D offset = null)
        {
            List<PointF> list = new List<PointF>();
 
            PointF p;
            p = WorldPointToMapPoint(pipe.StartNode, offset);
            list.Add(p);
            p = WorldPointToMapPoint(pipe.EndNode, offset);
            list.Add(p);
            return list;
 
        }
        /// <summary>
        /// 获取正交投影坐标,返回的是世界坐标
        /// </summary>
        /// <param name="position3D">世界坐标</param>
        /// <param name="mousePosition">地图坐标</param>
        /// <param name="vector3">投影向量</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private PointF3D GetZZWorldPoint(PointF3D position3D, PointF mousePosition, Vector3 vector3)
        {
            //做一条通过position3D的平行于vector3的直线,
            if (vector3==new Vector3(0,0,1))
            {
                return GetLGWorldPoint(position3D, mousePosition);
            }
            else
            {
                return new PointF3D(0, 0, 0);
            }
        }
 
        /// <summary>
        /// 获取正交投影坐标,返回的是世界坐标
        /// </summary>
        /// <param name="position3D">世界坐标</param>
        /// <param name="mousePosition">地图坐标</param>
        /// <param name="vector3">投影向量</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private PointF3D GetLGWorldPoint(PointF3D position3D, PointF p2)
        {
            double radian_fushi = 俯视弧度;
            float sin = (float)Math.Sin(radian_fushi);
            float cos = (float)Math.Cos(radian_fushi);
            var p1 = WorldPointToMapPoint(position3D);
            var dy=p2.Y - p1.Y;
            float dz= dy/cos;
            return new PointF3D(position3D.X, position3D.Y, position3D.Z+ dz);
 
        }
        private PointF MapPointToWorldPoint(PointF3D point)
        { 
            return MapPointToWorldPoint(new PointF(point.X, point.Y), point.Z);
        }
        /// <summary>
        /// 获取地图投影坐标
        /// </summary>
        /// <param name="point"></param>
        /// <param name="z"></param>
        /// <returns></returns>
        private PointF MapPointToWorldPoint(PointF point, float z = 0)
        {
            var pointT = Get俯视角还原Point(point, z);
            pointT = Get平面还原Point(pointT);
 
            //var n=new PointF((float)pointR.X - Z(z).X, (float)(pointR.Y - Z(z).Y));
            return pointT;
        }
        private PointF GetMapPoint_还原(NodeViewModel junction)
        {
            PointF p;
 
            p = MapPointToWorldPoint(junction.Position, junction.Elev);
            return p;
 
        }
 
 
 
        #endregion
 
 
        #region 判断可见性
        private float Get_dist(PointF A, PointF B)
        {
            float dx = A.X - B.X;
            float dy = A.Y - B.Y;
            float dist = (float)Math.Sqrt(dx * dx + dy * dy);
            return dist;
        }
        //判断A距离线段B和C的距离,如果超出了线段的范围,则返回到最近的端点的距离;距离线段中心点越远,返回的距离越大;
        private float Get_dist(PointF A, PointF B, PointF C, float MaxOff)
        {
            //PointF A, PointF B,PointF C,求点A到B、C构成线段的中心点的距离
 
            float dist_off = GetDistanceFromPointAToMidpointOfLineSegmentBC(A, B, C);
            //使用dist_off 跟 线段A、B的长度比较,如果大于1/2,则返回MaxOff,否则按照比例返回
            float dist_len = Get_dist(B, C);
            if (dist_len < 5) dist_len = 5;
            float dist_add = (dist_off / dist_len > 0.5 ? MaxOff : dist_off / dist_len * 2 * MaxOff);
 
            float dx = C.X - B.X;
            float dy = C.Y - B.Y;
            float dist = (float)Math.Sqrt(dx * dx + dy * dy);
            if (dist == 0) return Get_dist(A, B) + dist_add;
            float t = ((A.X - B.X) * dx + (A.Y - B.Y) * dy) / (dist * dist);
            if (t < 0) return Get_dist(A, B) + dist_add;
            if (t > 1) return Get_dist(A, C) + dist_add;
            float x = B.X + t * dx;
            float y = B.Y + t * dy;
            return Get_dist(A, new PointF(x, y)) + dist_add;
 
        }
        private float GetDistanceFromPointAToMidpointOfLineSegmentBC(PointF A, PointF B, PointF C)
        {
            // Calculate the midpoint of the line segment BC
            PointF midpoint = new PointF((B.X + C.X) / 2, (B.Y + C.Y) / 2);
 
            // Calculate the distance from point A to the midpoint
            float dx = midpoint.X - A.X;
            float dy = midpoint.Y - A.Y;
            float distance = (float)Math.Sqrt(dx * dx + dy * dy);
 
            return distance;
        }
 
        PointF PMin_Show, PMax_Show;
 
        /// <summary>
        /// 判断是否在屏幕坐标内
        /// </summary>
        /// <param name="screenPos"></param>
        /// <returns></returns>
        public bool isVisible(PointF MapPos)
        {
            if (MapPos.X < PMin_Show.X || MapPos.X > PMax_Show.X || MapPos.Y < PMin_Show.Y || MapPos.Y > PMax_Show.Y)
                return false;
            else
                return true;
        }
 
        /// <summary>
        /// 判断是否在屏幕坐标内
        /// </summary>
        /// <param name="screenPos"></param>
        /// <returns></returns>
        public bool isVisible(List<PointF> list_MapPos)
        {
            bool visible = false;
            foreach (var MapPos in list_MapPos)
            {
                if (MapPos.X < PMin_Show.X || MapPos.X > PMax_Show.X || MapPos.Y < PMin_Show.Y || MapPos.Y > PMax_Show.Y)
                {
 
                }
                else
                {
                    visible = true;
                    return true;
                }
 
            }
 
            return visible;
        }
        #endregion
 
 
 
        #region 重绘函数
 
        bool _needPaintAll = false;
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
 
            if (float.IsInfinity(zoom)) return;
 
            label_center.Text = $"center:({MapCenter.X.ToString("0.00")} ,{MapCenter.Y.ToString("0.00")})";
            label_zoom.Text = $"Zoom:{zoom.ToString("0.000")}";
            toolStripStatusLabel_rotation.Text = $"Rotation:({Rotation.ToString("0")},{RotationF.ToString("0")})";
 
            //if (!_needPaintAll)
            //    return;
            int heightOfBar = showToolBar ? 24 : 0;
            if (!showToolBar) heightOfBar = 0;
 
 
 
            if (e.ClipRectangle != new Rectangle(this.Left, heightOfBar, this.Width, this.Height - heightOfBar - statusStrip1.Height)) return;
 
 
            _needPaintAll = false;
            if (buffer == null || buffer.Width != Width || buffer.Height != Height)
            {
                buffer?.Dispose();
                buffer = new Bitmap(Width, Height);
            }
            // 使用缓存绘制,避免在每次重绘时重新计算所有要绘制的元素
 
            //if (bufferG == null) bufferG = Graphics.FromImage(buffer);
            using (var bufferG = Graphics.FromImage(buffer))
            //using (var bufferG = e.Graphics)
            {
                // 先将控件的背景填充为白色
                bufferG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                bufferG.Clear(Color.Transparent);
                bufferG.TranslateTransform(Width / 2, Height / 2);
                bufferG.ScaleTransform(Zoom.X, Zoom.Y);
                bufferG.TranslateTransform(-MapCenter.X, -MapCenter.Y);
 
                //if (_NodeColour==null)
                //{
                //    cb_Node_Colour_SelectedIndexChanged(1, new EventArgs());
                //}
                //if (_LinkColour==null)
                //{
                //    cb_Link_Colour_SelectedIndexChanged(1, new EventArgs());
                //}
                //BookMark    :绘制地图事件
                Draw(bufferG, _Template);
 
 
 
                if (_newTemplate?.network != null) Draw(bufferG, _newTemplate);
 
                var r = 2f / zoom;
                if (_isDragging && DragStartPos != new PointF(0, 0) && mousePosition != new PointF(0, 0))
                {
                    label_center.Text = $"S:{DragStartPos.X}:{DragStartPos.Y} E:{mousePosition.X}:{mousePosition.Y}";
                    var _lastMousePosition = DragStartPos;
                    // 绘制矩形
                    var start = new PointF((float)Math.Min(mousePosition.X, _lastMousePosition.X), (float)Math.Min(mousePosition.Y, _lastMousePosition.Y));
                    var size = new SizeF((float)Math.Abs(_lastMousePosition.X - mousePosition.X), (float)Math.Abs(_lastMousePosition.Y - mousePosition.Y));
                    if (size.Width == 0) size.Width = 0.01f;
                    if (size.Height == 0) size.Height = 0.01f;
                    var rectangle0 = new RectangleF(start, size);
                    using (var pen = new Pen(Color.Black, 0.5f * r))
                    {
                        bufferG.DrawRectangles(pen, new RectangleF[] { rectangle0 });
                    }
                }
                if (_isPainting)
                {
                    if (_mouseState == MouseState.新增立管)
                    {
                        var wPos=GetZZWorldPoint(_select_junction1.Position3D, _MousePosition,new Vector3(0,0,1));
                        using (var pen = new Pen(Color.Black, 1 * r))
                        {
                            pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                            bufferG.DrawLine(pen, WorldPointToMapPoint(_select_junction1), WorldPointToMapPoint(wPos));
                        }
                    }
                    else
                    {
                        using (var pen = new Pen(Color.Black, 1 * r))
                        {
                            pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                            bufferG.DrawLine(pen, WorldPointToMapPoint(_select_junction1), _MousePosition);
                        }
                    }
                    
                }
                if (_isDrawingPolygon && polygonPoints.Count > 0)
                {
                    List<PointF> pf = polygonPoints.ToList();
                    pf.Add(new PointF(mousePosition.X, mousePosition.Y));
                    using (var pen = new Pen(Color.Black, 1 * r))
                    {
                        // 绘制多边形虚线边框
                        pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                        bufferG.DrawLines(pen, pf.ToArray());
                    }
                }
                if (_isSettingBackGroundPictur)
                {
 
                    var _lastMousePosition = DragStartPos;
                    // 绘制矩形
                    var start = new PointF((float)Math.Min(mousePosition.X, _lastMousePosition.X), (float)Math.Min(mousePosition.Y, _lastMousePosition.Y));
                    var size = new SizeF((float)Math.Abs(_lastMousePosition.X - mousePosition.X), (float)Math.Abs(_lastMousePosition.Y - mousePosition.Y));
                    var rectangle0 = new RectangleF(start, size);
                    using (var pen = new Pen(Color.Black, 1 * r))
                    {
                        bufferG.DrawRectangles(pen, new RectangleF[] { rectangle0 });
                    }
                }
 
                if (_isMovingObject)
                {
                    var newP = _MousePosition;
                    //var p = MapPointToWorldPoint(, _OperaNode.Elev);
                    var oldP3D = (PointF3D)_undoOldValue;
                    var oldP = WorldPointToMapPoint(new PointF(oldP3D.X, oldP3D.Y), oldP3D.Z);
                    List<PointF> pf = new List<PointF> { oldP, newP };
                    using (var pen = new Pen(Color.Black, 1 * r))
                    {
                        // 绘制多边形虚线边框
                        pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                        bufferG.DrawLines(pen, pf.ToArray());
                    }
                }
 
            }
            // 将生成的画布绘制到控件上
            e.Graphics.DrawImage(buffer, 0, 0);
 
        }
 
        
 
        PointF[] getCurclePoints(int num)
        {
            PointF[] points = new PointF[num + 1];
            float angle = 0;
            for (int i = 0; i < points.Length; i++)
            {
                float x = (float)Math.Cos(angle);
                float y = (float)Math.Sin(angle);
                points[i] = new PointF(x, y);
                angle += 2 * (float)Math.PI / num;
            }
            points[num] = points[0];
            return points;
        }
 
        void Draw(Graphics bufferG, Template template)
        {
            if (template == null) return;
            var _Nodes = template.network.Nodes.ViewNodes;
            var _Links = template.network.Links.ViewLinks;
 
            var Cpoints = getCurclePoints(64).ToList();
 
            var r = 1.73f / zoom;
            var rt = r;
 
            float minElve = float.MinValue;
            float maxElve = float.MaxValue;
            //if (this.mapOption!=null && this.mapOption.ShowFloor!=int.MinValue )
            //{
            //    var fl = template.Floors.Find(f => f.FloorIndex == this.mapOption.ShowFloor);
            //    var fl_1 = template.Floors.Find(f => f.FloorIndex == this.mapOption.ShowFloor+1);
            //    if (fl!=null)
            //    {st
            //        minElve = fl.Elev;
 
            //        maxElve = fl_1!=null ? fl_1.Elev : float.MaxValue;
            //    }
 
            //}
            r = r * Link_multiply;
            List<PointF> diametersZoom = new List<PointF>() { new PointF(0, 0.08f), new PointF(150, 0.03f), new PointF(300, 0.001f), new PointF(800, 0.0001f) };
 
            Pen penN = new Pen(Color.FromArgb(0, 0, 255), 1 * r);
 
            Pen penChoosed = new Pen(Color.Purple, 5 * r);
            Pen pen_valveChoosed = new Pen(Color.Red, 5 * r);
 
            Pen penClosed = new Pen(Color.OrangeRed, 2 * r);
            Pen penHovered =new Pen(Color.DeepSkyBlue, 5 * r);
            //背景图绘制
            if (this.mapOption.isShowPic && template != null && File.Exists(template.BackGroundImg_FullPath))
            {
                //var gs = bufferG.Save();
                // 应用矩阵变换以抵消之前的翻转效果
                //bufferG.ScaleTransform(1 / Zoom.X, 1 / Zoom.Y);
                // 恢复之前保存的绘图状态
 
                var Cps = new List<PointF>
                {
                    template.BackGroundPoint1,
                    new PointF(template.BackGroundPoint2.X,template.BackGroundPoint1.Y),
                    new PointF(template.BackGroundPoint1.X,template.BackGroundPoint2.Y),
                    //template.BackGroundPoint2,
                    
                 
                };
 
 
 
                List<PointF> p = new List<PointF>();
                Cps.ForEach(cp => p.Add(WorldPointToMapPoint(cp, template.BackGroundElev, template.OffSet)));
 
                //bufferG.DrawImage(System.Drawing.Image.FromFile(@"C:\Users\cloud\Pictures\GenshinImpactCloudGame\QQ截图20230919105637.png"), p[0]);
                try
                {
                    var img = System.Drawing.Image.FromFile(template.BackGroundImg_FullPath);
                    if (img != null)
                    {
                        bufferG.FillPolygon(penN.Brush, p.ToArray());
                        bufferG.DrawImage(img, p.ToArray());
                    }
                }
                catch
                {
 
                }
 
                //bufferG.Restore(gs);
            }
 
 
            // 绘制线
 
            HashSet<long> dict_flow_direction = new HashSet<long>();
            using (Pen pen0 = new Pen(Color.FromArgb(0, 0, 255), 2 * r))
            {
 
                foreach (var link in _Links)
                {
                    if (!link.Visible) continue;
                    if (link.Elev < minElve || link.Elev >= maxElve) continue;
                    //if (_isMovingObject && (link.StartNode == _OperaNode || link.EndNode == _OperaNode)) continue;
                    var p1 = WorldPointToMapPoint(link.StartNode, template.OffSet);
                    var p2 = WorldPointToMapPoint(link.EndNode, template.OffSet);
                    if (!isVisible(p1) && !isVisible(p2)) continue;
                    if (_LinkColour != null)
                    {
                        pen0.Color = penClosed.Color = getLinkColor(_LinkColour, link);
                    }
                   
                    Pen pen = pen0;
#if DEBUG
#else
                    if (_Template != null && _Template.mapOption._ShowStatus && link.Status == Hydro.Core.ObjectEnum.StatusType.CLOSED) pen = penClosed;
#endif
 
                    if (link.Hovered) pen = penHovered;
                    float zoomAtMin = 0;
                    for (int i = 0; i < diametersZoom.Count; i++)
                    {
                        PointF point = diametersZoom[i];
                        if (link.Diameter >= point.X) continue;
                        zoomAtMin = diametersZoom[i - 1].Y;
                        break;
                    }
                    if (zoomAtMin >= zoom) continue;
                    if (link is ValveViewModel)
                    {
                        if (link.Selected || _ShowValve)
                        {
                            var c = new PointF((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2);
                            bufferG.DrawLines(link.Selected ? penChoosed : pen, new PointF[] { p1, p2 });
                            var valveShapeHeight = link.Selected ? 10 : 5;
                            PointF[] points = new PointF[] {
                                getRotatePoint(c.X - valveShapeHeight * r, c.Y + valveShapeHeight * r,c,p1,p2),
                                getRotatePoint(c.X - valveShapeHeight * r, c.Y - valveShapeHeight * r,c,p1,p2),
                                getRotatePoint(c.X + valveShapeHeight * r, c.Y + valveShapeHeight * r,c,p1,p2),
                                getRotatePoint(c.X + valveShapeHeight * r, c.Y - valveShapeHeight * r,c,p1,p2),
                                getRotatePoint(c.X - valveShapeHeight * r, c.Y + valveShapeHeight * r,c,p1,p2),
                            };
                            bufferG.FillPolygon(link.Selected ? pen_valveChoosed.Brush : pen.Brush, points);
 
                        }
                    }
                    else if (link is PumpViewModel)
                    {
                        if (link.Selected || _ShowValve)
                        {
 
                            var c = new PointF((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2);
                            //bufferG.DrawLine(link.Selected ? pen_valveChoosed : pen, p1, p2);
 
                            bufferG.DrawLines(link.Selected ? penChoosed : pen, new PointF[] { p1, p2 });
                            // 绘制圆形部分(水泵的泵体)
                            float radius = 5 * r;
                            float diameter = radius * 2;
                            #region 圆形拆分
                            //var p = new PointF[] 
                            //{
                            //    getRotatePoint(c.X - radius - radius, c.Y - radius, c, p1, p2),
                            //    getRotatePoint(c.X + radius - radius, c.Y - radius, c, p1, p2),
                            //    getRotatePoint(c.X + radius - radius, c.Y + radius, c, p1, p2),
                            //    getRotatePoint(c.X - radius - radius, c.Y + radius, c, p1, p2),
                            //    getRotatePoint(c.X - radius - radius, c.Y - radius, c, p1, p2),
                            //};
                            List<PointF> p = new List<PointF>();
                            Cpoints.ForEach(cp => p.Add(getRotatePoint(c.X + cp.X * radius - radius, c.Y + cp.Y * radius, c, p1, p2)));
 
                            #endregion
 
                            //RectangleF circleRect = new RectangleF(p[0].X, p[0].Y,p[1].X-p[0].X>0? diameter:-diameter,p[1].Y-p[0].Y>0? diameter:-diameter);
                            //bufferG.FillEllipse(link.Selected ? pen_valveChoosed.Brush : pen.Brush, circleRect);
 
 
                            bufferG.FillPolygon(link.Selected ? pen_valveChoosed.Brush : pen.Brush, p.ToArray());
 
                            //// 绘制矩形部分(水泵的出口)
                            //float rectangleWidth = 6*r;
                            //float rectangleHeight = 2*r;
                            //PointF rectTopLeft = new PointF(c.X - rectangleWidth / 2, c.Y + radius);
                            //SizeF rectSize = new SizeF(rectangleWidth, rectangleHeight);
                            //RectangleF rectangleRect = new RectangleF(rectTopLeft, rectSize);
                            //bufferG.DrawRectangles(link.Selected ? pen_valveChoosed : pen,new RectangleF[] { rectangleRect });
 
                            // 绘制连接线
 
 
                            var valveShapeHeight = link.Selected ? radius * 2 : radius;
                            PointF[] points = new PointF[] {
                                getRotatePoint(c.X - valveShapeHeight , c.Y + valveShapeHeight ,c,p1,p2),
                                getRotatePoint(c.X - valveShapeHeight , c.Y ,c,p1,p2),
                                getRotatePoint(c.X + valveShapeHeight , c.Y ,c,p1,p2),
                                getRotatePoint(c.X + valveShapeHeight , c.Y + valveShapeHeight ,c,p1,p2),
                                getRotatePoint(c.X - valveShapeHeight , c.Y + valveShapeHeight ,c,p1,p2),
 
                            };
 
                            bufferG.FillPolygon(link.Selected ? pen_valveChoosed.Brush : pen.Brush, points);
                        }
 
 
                    }
                    else if (link is RepeaterViewModel re)
                    {
                        if (re.Status == RepeaterViewModel.RepeatStatus.收起 || _IsEditMode)
                        {
 
                            bufferG.DrawLines(link.Selected ? penChoosed : pen, new PointF[] { p1, p2 });
 
 
                            var listNode = Get等分Nodes(p1, p2, Math.Max(re.RepeatTimes, 1));
 
                            for (int i = 0; i < listNode.Count; i++)
                            {
                                //foreach (var c in listNode)
                                //{
                                var c = listNode[i];
                                RectangleF[] rects = new RectangleF[] {
                                    new RectangleF(c.X-10*r,c.Y-8*r,20*r,16*r),
                                };
                                bufferG.FillRectangles(new SolidBrush(Color.White), rects);
 
                                //bufferG.FillRectangles(link.Selected ? penChoosed.Brush : pen.Brush, new RectangleF[]
                                //{
                                //    new RectangleF(c.X-5*r,c.Y-5*r,3*r,3*r),
                                //    new RectangleF(c.X-5*r,c.Y+2*r,3*r,3*r),
                                //    new RectangleF(c.X+2*r,c.Y+2*r,3*r,3*r),
                                //    new RectangleF(c.X+2*r,c.Y-5*r,3*r,3*r),
                                //});
                                // 保存当前绘图状态
                                var gs = bufferG.Save();
                                // 应用矩阵变换以抵消之前的翻转效果
                                bufferG.ScaleTransform(1 / Zoom.X, 1 / Zoom.Y);
                                int index = re.GetIndex(i);
                                string indexString = index == 0 ? "" : index.ToString();
                                Font font = new Font(FontFamily.GenericSansSerif, 10);
                                string text = $"{indexString}{re.NetworkShowName}";
                                SizeF textSize = bufferG.MeasureString(text, font);
                                var center = new PointF(c.X * Zoom.X, c.Y * Zoom.Y);
                                float textLeft = center.X - textSize.Width / 2;
                                float textTop = center.Y - textSize.Height / 2;
                                PointF p = new PointF(textLeft, textTop);
 
                                bufferG.DrawString(text, font, link.Selected ? penChoosed.Brush : pen.Brush, p);
                                // 恢复之前保存的绘图状态
                                bufferG.Restore(gs);
 
                                if (textSize.Width / Zoom.X > rects[0].Width)
                                {
                                    rects[0] = new RectangleF(c.X - textSize.Width / 2 / Zoom.X - 1 * r, c.Y - 8 * r, textSize.Width / Zoom.X + 2 * r, 16 * r);
                                }
                                try
                                {
                                    bufferG.DrawRectangles(penN, rects);
 
                                }
                                catch { }
 
                            }
                            //var c = new PointF((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2);
                        }
                        //else
                        //{
                        //    DrawRepeater(bufferG,re);
                        //}
                    }
                    else
                    {
 
                        if (link.StartNode == null || link.EndNode == null) continue;
 
                        bufferG.DrawLines(link.Selected ? penChoosed : pen, new PointF[] { p1, p2 });
                        if (_Template.mapOption._ShowFlowDirection)
                        {
                            var c = new PointF((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2);
                            var ps = MapToScreen(c);
                            //将ps转换为ulong,精度为20,并加入到dict_flow_direction中
                            var ps_20 = GetUlongByPoint(ps, 5);
                            if (!dict_flow_direction.Contains(ps_20))
                            {
                                dict_flow_direction.Add(ps_20);
                                bufferG.DrawLines(link.Selected ? penChoosed : pen, new PointF[] { p1, p2 });
                                // 绘制圆形部分(水泵的泵体)
                                float radius = 5 * r;
                                float diameter = radius * 2;
                                #region 圆形拆分
                                float activeD = 1;
                                if (link.EN_FLOW < 0) activeD = -1;
                                List<PointF> p = new List<PointF>();
                                Cpoints.ForEach(cp => p.Add(getRotatePoint(c.X - activeD * cp.X * radius + activeD * radius, c.Y + cp.Y * radius, c, p1, p2)));
 
                                #endregion
 
 
                                bufferG.FillPolygon(link.Selected ? pen_valveChoosed.Brush : pen.Brush, p.ToArray());
 
                                var valveShapeHeight = link.Selected ? radius * 2 : radius;
                                PointF[] points = new PointF[] {
                                    getRotatePoint(c.X -activeD* valveShapeHeight , c.Y + valveShapeHeight ,c,p1,p2),
                                    getRotatePoint(c.X  , c.Y ,c,p1,p2),
                                    getRotatePoint(c.X - activeD*valveShapeHeight , c.Y - valveShapeHeight,c,p1,p2),
                                    getRotatePoint(c.X + activeD*valveShapeHeight , c.Y - valveShapeHeight,c,p1,p2),
                                    getRotatePoint(c.X + activeD*valveShapeHeight , c.Y + valveShapeHeight ,c,p1,p2),
                                    getRotatePoint(c.X - activeD*valveShapeHeight , c.Y + valveShapeHeight ,c,p1,p2),
                                };
 
                                bufferG.FillPolygon(link.Selected ? pen_valveChoosed.Brush : pen.Brush, points);
                            }
                        }
                    }
 
                }
            }
 
 
            r = rt;
 
 
            HashSet<long> dict_point = new HashSet<long>();
            //绘制点
            penChoosed = new Pen(Color.Green, 1f * r);
            Brush brushChoosed = penChoosed.Brush;
            SolidBrush whiteBrush = new SolidBrush(Color.White);
 
            using (Pen pen0 = new Pen(Color.FromArgb(255, 0, 0), 1 * r))
            {
                
                foreach (NodeViewModel node in _Nodes)
                {
                    if (!node.Visible) continue;
                    if (node.Elev < minElve || node.Elev >= maxElve) continue;
                    Pen pen = pen0;
                    Brush brush = pen.Brush;
                    float pr = (float)(r * 0.5);
                    pr = pr * junction_multiply;
                    PointF p = WorldPointToMapPoint(node, template.OffSet);
                    if (!isVisible(p)) continue;
                    var ps_20 = GetUlongByPoint(p, 0.1f);
                    if (dict_point.Contains(ps_20))
                        continue;
                    dict_point.Add(ps_20);
                    //var x = junction.Position.X * zoom + PanningOffset.X - radius / 2.0f;
                    //var y = junction.Position.Y * zoom + PanningOffset.Y - radius / 2.0f;
                    if (_NodeColour != null)
                    {
                        pen.Color = penChoosed.Color = getNodeColor(_NodeColour, node);
                        brush = pen.Brush;
                        brushChoosed = penChoosed.Brush;
 
 
                    }
                    if (node.Hovered)
                    {
                        pen= penHovered;
                        brush = pen.Brush;
                    }
 
                    var rectangle = new RectangleF((float)p.X - 5 * pr, (float)p.Y - 5 * pr, 10 * pr, 10 * pr);
                    float zoomAtMin = 0;
                    for (int i = 0; i < diametersZoom.Count; i++)
                    {
                        PointF point = diametersZoom[i];
                        if (node.MaxDiameter >= point.X) continue;
                        zoomAtMin = diametersZoom[i - 1].Y;
                        break;
                    }
                    if (zoomAtMin >= zoom) continue;
                    //if(node.ID == _StartPoint)
                    //{
                    //    var whiteRect = new RectangleF(rectangle.X - 4 * pr, rectangle.Y - 4 * pr, rectangle.Width + 8 * pr, rectangle.Height + 8 * pr);
                    //    bufferG.FillEllipse(whiteBrush, whiteRect);
 
                    //    whiteRect = new RectangleF(rectangle.X + 2 * pr, rectangle.Y + 2 * pr, rectangle.Width - 4 * pr, rectangle.Height - 4 * pr);
                    //    bufferG.DrawEllipse(node.Selected ? penChoosed : pen, whiteRect);
 
                    //    whiteRect = new RectangleF(rectangle.X - 4 * pr, rectangle.Y - 4 * pr, rectangle.Width + 8 * pr, rectangle.Height + 8 * pr);
                    //    bufferG.DrawEllipse(node.Selected ? penChoosed : pen, whiteRect);
                    //}
                    //else 
                    if ( node == _OperaNode)
                    {
                        var whiteRect = new RectangleF(rectangle.X - 4 * pr, rectangle.Y - 4 * pr, rectangle.Width + 8 * pr, rectangle.Height + 8 * pr);
                        bufferG.FillEllipse(whiteBrush, whiteRect);
 
                        whiteRect = new RectangleF(rectangle.X + 2 * pr, rectangle.Y + 2 * pr, rectangle.Width - 4 * pr, rectangle.Height - 4 * pr);
                        bufferG.DrawEllipse(node.Selected ? penChoosed : pen, whiteRect);
 
                        whiteRect = new RectangleF(rectangle.X - 4 * pr, rectangle.Y - 4 * pr, rectangle.Width + 8 * pr, rectangle.Height + 8 * pr);
                        bufferG.DrawEllipse(node.Selected ? penChoosed : pen, whiteRect);
                    }
                    //else if (node.ID == _EndPoint)//最不利点
                    //{
                    //    //帮我绘制一个房子,上边是三角形,下边是矩形
 
                    //    var p1 = new PointF((float)p.X - 4 * pr, (float)p.Y - 2 * pr);
                    //    var p2 = new PointF((float)p.X + 4 * pr, (float)p.Y - 2 * pr);
                    //    var p3 = new PointF((float)p.X, (float)p.Y - 4 * pr);
                    //    bufferG.DrawPolygon(node.Selected ? penChoosed : pen, new PointF[] { p1,p2,p3});
 
                    //    var whiteRect = new RectangleF(rectangle.X - 4 * pr, rectangle.Y - 4 * pr, rectangle.Width + 8 * pr, rectangle.Height + 8 * pr);
                    //    bufferG.FillEllipse(whiteBrush, whiteRect);
 
                    //    whiteRect = new RectangleF(rectangle.X - 4 * pr, rectangle.Y - 4 * pr, rectangle.Width + 8 * pr, rectangle.Height + 8 * pr);
                    //    bufferG.DrawEllipse(node.Selected ? penChoosed : pen, whiteRect);
 
 
                    //}
                    else if (node is TankViewModel)
                    {
                        pr *= 2;
                        rectangle = new RectangleF((float)p.X - 5 * pr, (float)p.Y - 5 * pr, 10 * pr, 10 * pr);
                        RectangleF r0 = new RectangleF(rectangle.X, rectangle.Y + 5 * pr, 10 * pr, 5 * pr);
                        RectangleF r1 = new RectangleF(rectangle.X + 2 * pr, rectangle.Y, 6 * pr, 5 * pr);
                        bufferG.FillRectangle(node.Selected ? brushChoosed : brush, r0);
                        bufferG.FillRectangle(node.Selected ? brushChoosed : brush, r1);
 
                    }
                    else if (node is ReservoirViewModel)
                    {
                        pr *= 2;
                        rectangle = new RectangleF((float)p.X - 5 * pr, (float)p.Y - 5 * pr, 10 * pr, 10 * pr);
 
                        RectangleF r0 = new RectangleF(rectangle.X, rectangle.Y + 2 * pr, rectangle.Width, 6 * pr);
                        RectangleF r1 = new RectangleF(rectangle.X, rectangle.Y + 8 * pr, 1 * pr, 2 * pr);
                        RectangleF r2 = new RectangleF(rectangle.X + 9 * pr, rectangle.Y + 8 * pr, 1 * pr, 2 * pr);
                        bufferG.FillRectangle(node.Selected ? brushChoosed : brush, r0);
                        bufferG.FillRectangle(node.Selected ? brushChoosed : brush, r1);
                        bufferG.FillRectangle(node.Selected ? brushChoosed : brush, r2);
                    }
                    else if (node is MeterViewModel)
                    {
 
 
                        //bufferG.DrawEllipse(junction.Choosed ? penChoosed : pen, rectangle);
                        bufferG.FillEllipse(node.Selected ? brushChoosed : brush, rectangle);
                        var whiteRect = new RectangleF(rectangle.X + 1 * pr, rectangle.Y + 1 * pr, rectangle.Width - 2 * pr, rectangle.Height - 2 * pr);
                        bufferG.FillEllipse(whiteBrush, whiteRect);
 
                        var p1 = new PointF(rectangle.X + 5 * pr, rectangle.Y);
                        var p2 = new PointF(rectangle.X + 5 * pr, rectangle.Y + 10 * pr);
                        bufferG.DrawLine(node.Selected ? penChoosed : pen, p1, p2);
                    }
                    else
                    {
                        rectangle = new RectangleF((float)p.X - 3 * pr, (float)p.Y - 3 * pr, 6 * pr, 6 * pr);
                        if (node.Selected || _ShowJunction)
                            bufferG.FillEllipse(node.Selected ? brushChoosed : brush, rectangle);
                    }
 
                }
            }
 
            using (Pen pen = new Pen(Color.FromArgb(255, 0, 0), 1 * r))
            {
                Brush brush = pen.Brush;
                //获取_Nodes中自由水压最小的节点
                var node = _Nodes.Where(n => n is JunctionViewModel || n is MeterViewModel && n.EN_PRESSURE != float.NaN).OrderBy(n => n.EN_PRESSURE).FirstOrDefault();
                //判断node.EN_PRESSURE不是float.NaN
 
                
 
                if (node != null && !float.IsNaN( node.EN_PRESSURE))
                {
 
                    //if (node.Elev < minElve || node.Elev >= maxElve) continue;
                    float pr = (float)(r * 0.5);
                    pr = pr * junction_multiply;
                    PointF p = WorldPointToMapPoint(node, template.OffSet);
 
                    var ps_20 = GetUlongByPoint(p, 0.1f);
 
                    dict_point.Add(ps_20);
                    //var x = junction.Position.X * zoom + PanningOffset.X - radius / 2.0f;
                    //var y = junction.Position.Y * zoom + PanningOffset.Y - radius / 2.0f;
                    if (_NodeColour != null)
                    {
                        pen.Color = getNodeColor(_NodeColour, node);
                        brush = pen.Brush;
                        brushChoosed = penChoosed.Brush;
 
 
                    }
 
 
                    var rectangle = new RectangleF((float)p.X - 5 * pr, (float)p.Y - 5 * pr, 10 * pr, 10 * pr);
                    float zoomAtMin = 0;
                    for (int i = 0; i < diametersZoom.Count; i++)
                    {
                        PointF point = diametersZoom[i];
                        if (node.MaxDiameter >= point.X) continue;
                        zoomAtMin = diametersZoom[i - 1].Y;
                        break;
                    }
 
 
                    //var whiteRect = new RectangleF(rectangle.X - 4 * pr, rectangle.Y - 4 * pr, rectangle.Width + 8 * pr, rectangle.Height + 8 * pr);
                    //bufferG.FillEllipse(whiteBrush, whiteRect);
 
                    //whiteRect = new RectangleF(rectangle.X + 2 * pr, rectangle.Y + 2 * pr, rectangle.Width - 4 * pr, rectangle.Height - 4 * pr);
                    //bufferG.DrawEllipse(node.Selected ? penChoosed : pen, whiteRect);
 
 
                    //whiteRect = new RectangleF(rectangle.X - 4 * pr, rectangle.Y - 4 * pr, rectangle.Width + 8 * pr, rectangle.Height + 8 * pr);
                    //bufferG.DrawEllipse(node.Selected ? penChoosed : pen, whiteRect);
 
                    var p1 = new PointF((float)p.X - 4 * pr, (float)p.Y - 2 * pr);
                    var p2 = new PointF((float)p.X + 4 * pr, (float)p.Y - 2 * pr);
                    var p3 = new PointF((float)p.X, (float)p.Y - 4 * pr);
                    bufferG.DrawPolygon(node.Selected ? penChoosed : pen, new PointF[] { p1, p2, p3 });
 
                    var whiteRect = new RectangleF(rectangle.X - 4 * pr, rectangle.Y - 4 * pr, rectangle.Width + 8 * pr, rectangle.Height + 8 * pr);
                    bufferG.FillEllipse(whiteBrush, whiteRect);
 
                    whiteRect = new RectangleF(rectangle.X - 4 * pr, rectangle.Y - 4 * pr, rectangle.Width + 8 * pr, rectangle.Height + 8 * pr);
                    bufferG.DrawEllipse(node.Selected ? penChoosed : pen, whiteRect);
 
                }
            }
            //r = r * Link_multiply;
            //using (Pen pen = new Pen(Color.FromArgb(0, 0, 255), 2 * r))
            //{
            //    foreach (var link in _Links)
            //    {
            //        if (!link.Visible) continue;
            //        if (!isVisible(WorldPointToMapPoint(link))) continue;
 
            //        float zoomAtMin = 0;
            //        for (int i = 0; i < diametersZoom.Count; i++)
            //        {
            //            PointF point = diametersZoom[i];
            //            if (link.Diameter >= point.X) continue;
            //            zoomAtMin = diametersZoom[i - 1].Y;
            //            break;
            //        }
            //        if (zoomAtMin >= zoom) continue;
 
 
            //        if (link is Valve)
            //        {
            //            if (link.Selected)
            //            {
            //                var p1 = WorldPointToMapPoint(link.StartNode);
            //                var p2 = WorldPointToMapPoint(link.EndNode);
            //                var c = new PointF((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2);
            //                bufferG.DrawLines(link.Selected ? valveChoosed : pen, new PointF[] { p1, p2 });
            //                bufferG.DrawLines(link.Selected ? valveChoosed : pen, new PointF[] {
            //                    getRotatePoint(c.X - 3 * r, c.Y + 3 * r,c,p1,p2),
            //                    getRotatePoint(c.X - 3 * r, c.Y - 2 * r,c,p1,p2),
            //                    getRotatePoint(c.X + 3 * r, c.Y + 2 * r,c,p1,p2),
            //                    getRotatePoint(c.X + 3 * r, c.Y - 2 * r,c,p1,p2),
            //                    getRotatePoint(c.X - 3 * r, c.Y + 2 * r,c,p1,p2),
 
            //                });
            //            }
            //        }
            //    }
            //}
 
        }
        Color getNodeColor(Colour colour, NodeViewModel node)
        {
            double value = 0;
            Color color = Color.Gray;
 
            switch (colour.Type)
            {
                case ColourType.节点自由压力:
                    value = node.EN_PRESSURE;
                    break;
                case ColourType.节点绝对压力:
                    value = node.EN_HEAD;
                    break;
                case ColourType.节点需水量:
                    value = node.EN_DEMAND;
                    break;
            }
 
            for (int i = 0; i < colour.Items.Count; i++)
            {
                if (colour.Items[i].DRange.IsInside(value))
                {
                    color = colour.Items[i].value;
                    break;
                }
            }
            return color;
        }
        Color getLinkColor(Colour colour, LinkViewModel link)
        {
            double value = 0;
            Color color = Color.Gray;
            switch (colour.Type)
            {
                case ColourType.管线流量:
                    value = link.EN_FLOW;
                    break;
                case ColourType.管线流速:
                    value = link.EN_VELOCITY;
                    break;
            }
 
            for (int i = 0; i < colour.Items.Count; i++)
            {
                if (colour.Items[i].DRange.IsInside(value))
                {
                    color = colour.Items[i].value;
                    break;
                }
            }
            return color;
        }
        private static long GetUlongByPoint(PointF ps, float delta = 20, int MaxY = 2000)
        {
            return (long)((int)(ps.X / delta) + ((int)Math.Round(ps.Y / delta)) * MaxY / delta);
        }
 
        public List<PointF> Get等分Nodes(PointF p1, PointF p2, int n)
        {
            // 计算线段长度
            float len = (float)Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));
            if (len == 0) len = 0.00001f;
            // 计算单位向量
            PointF u = new PointF((p2.X - p1.X) / len, (p2.Y - p1.Y) / len);
 
            // 计算间距
            float d = len / (n + 1);
 
 
            // 计算n等分点
            List<PointF> nodes = new List<PointF>();
            for (int i = 1; i < n + 1; i++)
            {
                PointF node = new PointF(p1.X + i * d * u.X, p1.Y + i * d * u.Y);
                if (node.X == float.NaN || node.Y == float.NaN) node = p1;
                nodes.Add(node);
            }
            //nodes.RemoveAt(0);
            //nodes.RemoveAt(nodes.Count - 1);
 
            //// 绘制线段
            //graphics.DrawLine(Pens.Black, p1, p2);
 
            //// 绘制3等分点和n等分点
            //foreach (PointF node in node3)
            //{
            //    graphics.FillEllipse(Brushes.Red, node.X - 2, node.Y - 2, 4, 4);
            //}
            //foreach (PointF node in nodes)
            //{
            //    graphics.FillEllipse(Brushes.Blue, node.X - 2, node.Y - 2, 4, 4);
            //}
            return nodes;
        }
 
 
        private PointF getRotatePoint(float px, float py, PointF center, PointF x, PointF y)
        {
            PointF p = new PointF(px, py);
 
            return getRotatePoint(p, center, x, y);
        }
        private PointF[] getRotatePoints(PointF[] ps, PointF center, PointF x, PointF y)
        {
            return ps.ToList().Select(p => getRotatePoint(p, center, x, y)).ToArray();
        }
 
 
        private PointF getRotatePoint(PointF p, PointF center, PointF x, PointF y)
        {
            float angle = (float)Math.Atan2(y.Y - x.Y, y.X - x.X);
            float distance = (float)Math.Sqrt(Math.Pow(p.X - center.X, 2) + Math.Pow(p.Y - center.Y, 2));
            float rotationAngle = (float)(Math.Atan2(p.Y - center.Y, p.X - center.X) + angle);
            float rotatedX = center.X + distance * (float)Math.Cos(rotationAngle);
            float rotatedY = center.Y + distance * (float)Math.Sin(rotationAngle);
            return new PointF(rotatedX, rotatedY);
        }
 
        public new void Invalidate()
        {
            _needPaintAll = true;
            PMin_Show = ScreenToMap(new PointF(0, Height));
            PMax_Show = ScreenToMap(new PointF(Width, 0));
            _timerDraw = true;
 
 
        }
        bool _timerDraw = false;
        private void timer_draw_Tick(object sender, EventArgs e)
        {
            if (_timerDraw)
                base.Invalidate();
            _timerDraw = false;
        }
        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
 
            // 当控件尺寸改变时,触发重绘
            this.Invalidate();
 
        }
 
#endregion
 
 
        #region 鼠标事件
        public PointF mouseXY = new PointF(0, 0);
 
        PointF DragStartPos;
        PointF _ClickStartPos;
        PointF RotaStartPos;
        PointF BackGroudPicLeftPos;
        bool _isPanning;
        /// <summary>
        /// 拖拽选择
        /// </summary>
        bool _isDragging;
        bool _isRotating;
        bool _isPainting;
        public List<IBaseViewModel> selectedObjs = new List<IBaseViewModel>();
        private List<NodeViewModel> selectedNodes => selectedObjs.FindAll(o => o is NodeViewModel).Select(o => (NodeViewModel)o).ToList();
        private List<LinkViewModel> selectedLinks => selectedObjs.FindAll(o => o is LinkViewModel).Select(o => (LinkViewModel)o).ToList();
        private NodeViewModel _OperaNode = null;
 
 
        PointF mousePosition;
        // control+鼠标中间按下缩放
        bool _isInsertingObject = false;
        bool _isMovingObject = false;
        bool _isPastingObject = false;
        Cursor _lastCursor;
        object _undoOldValue = null;
        private List<PointF> polygonPoints = new List<PointF>();
 
        public bool Lock2DView = false;
 
        private bool _isDrawingPolygon;
        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
 
            _ClickStartPos = new PointF(e.X, e.Y);
            DragStartPos = ScreenToMap(new PointF(e.X, e.Y));
            mousePosition = _MousePosition = ScreenToMap(new PointF(e.X, e.Y));
            if (e.Button == MouseButtons.Left && _isInsertingObject)
            {
 
            }
            else
            if (e.Button == MouseButtons.Middle || e.Button == MouseButtons.XButton2)
            {
 
                if (ModifierKeys == Keys.Control || ModifierKeys == Keys.Shift)//按下框选放大
                {
                    DragStartPos = ScreenToMap(new PointF(e.X, e.Y));
                    _isDragging = true;
                }
 
                else
                {
 
                    _lastCursor = this.Cursor;
                    this.Cursor = Cursors.SizeAll;
                    MapCenter0 = MapCenter;
                    mapOption0 = mapOption.Copy();
                    _isPanning = true;
                }
            }
            else if (e.Button == MouseButtons.Left && _mouseState == MouseState.无)
            {
 
 
                if (ModifierKeys == Keys.Shift)
                {
                    var point = ScreenToMap(new PointF(e.X, e.Y));
                    if (!_isDrawingPolygon)
                    {
                        // 开始绘制多边形
                        polygonPoints.Clear();
 
                        _isDrawingPolygon = true;
                    }
 
                    polygonPoints.Add(point);
                    mousePosition = _MousePosition = ScreenToMap(new PointF(e.X, e.Y));
                    Invalidate();
                    return;
                }
                if (_isDrawingPolygon)
                {
                    return;
                }
 
                //移动
                if (selectedObjs.Count >= 1) //&& selectedObjs[0].isNode())
                {
                    List<NodeViewModel> nodes = selectedNodes;
                    foreach (NodeViewModel node in nodes)
                    {
 
 
                        PointF mapPos = WorldPointToMapPoint(node);
                        PointF currentPoint = MapToScreen(mapPos);
                        if (Get_dist(new PointF(e.X, e.Y), currentPoint) < 15f)
                        {
 
 
                            _NewNet.Nodes.AddRange(selectedNodes);
                            _NewNet.Links.AddRange(selectedLinks);
                            _isMovingObject = true;
                            _OperaNode = node;
                            _undoOldValue = node.Position3D;
                            break;
                        }
                    }
                }
 
 
                if (!_isMovingObject)//拖拽选择
                {
                    DragStartPos = ScreenToMap(new PointF(e.X, e.Y));
                    _isDragging = true;
                }
 
            }
 
            else if (e.Button == MouseButtons.Left && _mouseState == MouseState.设置底图范围)
            {
                _mouseState = MouseState.无;
                DragStartPos = ScreenToMap(new PointF(e.X, e.Y));
                BackGroudPicLeftPos = MapPointToWorldPoint(ScreenToMap(new PointF(e.X, e.Y)), _Template.BackGroundElev);
                _isSettingBackGroundPictur = true;
            }
            else if (e.Button == MouseButtons.Right)
            {
                RotaStartPos = new PointF(e.X, e.Y);
                Rotation0 = Rotation;
                俯视角度_start = RotationF;
                _lastCursor = this.Cursor;
 
                Cursor = Cursors.Hand;
                mapOption0 = mapOption.Copy();
                _isRotating = true;
            }
 
        }
        private bool IsPointInPolygon(PointF point, List<PointF> polygon)
        {
            int count = polygon.Count;
            bool inside = false;
 
            PointF p1, p2;
            for (int i = 0, j = count - 1; i < count; j = i++)
            {
                p1 = polygon[i];
                p2 = polygon[j];
 
                if (((p1.Y > point.Y) != (p2.Y > point.Y)) &&
                    (point.X < (p2.X - p1.X) * (point.Y - p1.Y) / (p2.Y - p1.Y) + p1.X))
                {
                    inside = !inside;
                }
            }
 
            return inside;
        }
 
        public void InsertNet(Template temp)
        {
            _isInsertingObject = true;
            _newTemplate = temp;
            _undoOldValue = new PointF3D(0, 0, 0);
            _OperaNode = temp.network.Nodes.Find(node => node.ID == temp.Node1) as NodeViewModel;
            //if (_OperaNode == null) _OperaNode=_NewNet.Nodes[0];
        }
 
        bool controlDown = false;
        PointF _MousePosition = new PointF(0, 0);
        protected override void OnMouseMove(MouseEventArgs e)
        {
            //base.OnMouseMove(e);
            bool needInvalidate = false;
            _MousePosition = ScreenToMap(new PointF(e.X, e.Y));
            if (_isMovingObject)
            {
                var p = MapPointToWorldPoint(_MousePosition, _OperaNode.Elev);
                var oldP = (PointF3D)_undoOldValue;
                if (!float.IsInfinity(p.X) && !float.IsInfinity(p.Y)) _newTemplate.OffSet = new PointF3D(p.X - oldP.X, p.Y - oldP.Y, 0); //_OperaNode.Position = p;
 
                GlobalObject.PropertyForm.propertyGrid.Refresh();
 
                needInvalidate = true;
            }
 
 
            else if (_isPainting)
            {
                needInvalidate = true;
 
 
            }
            else if (_isPanning)
            {
                var vector = GetRotateVector(new PointF(e.X, e.Y), new PointF(_lastMouseX, _lastMouseY));
                MapCenter = new PointF(MapCenter.X - vector.X / Zoom.X, MapCenter.Y - vector.Y / Zoom.Y);
 
 
 
                label_center.Text = $"center:({MapCenter.X.ToString("0.000")} ,{MapCenter.Y.ToString("0.000")})";
                needInvalidate = true;
 
            }
            else if (_isDragging || _isDrawingPolygon || _isSettingBackGroundPictur)
            {
                mousePosition = _MousePosition;
                // 绘制选择框                                                                     
                // Rectangle selectionRect = new Rectangle(
                //    Math.Min((int)DragStartPos.X, (int)MP.X),
                //    Math.Min((int)DragStartPos.Y, (int)MP.Y),
                //    Math.Abs((int)DragStartPos.X - (int)MP.X),
                //    Math.Abs((int)DragStartPos.Y - (int)MP.Y));
                //DrawSelectionRect(selectionRect);
                needInvalidate = true;
 
            }
            else if (_isRotating)
            {
                mousePosition = _MousePosition;
                bool is下半屏幕 = RotaStartPos.Y >= this.Height / 2;
                if (ModifierKeys != Keys.Alt) Rotation = Rotation0 + ((float)e.X - (float)RotaStartPos.X) * 180 * 2.5 / (float)this.Width * (is下半屏幕 ? 1 : 1);
                if (ModifierKeys != Keys.Shift) RotationF = 俯视角度_start + ((float)e.Y - (float)RotaStartPos.Y) * 180 * 2.5 / (float)this.Height;
                if (RotationF > 90) RotationF = 90;
                if (RotationF < 0) RotationF = 0;
                needInvalidate = true;
 
            }
            else
 
            if (_isInsertingObject)
            {
                var p = MapPointToWorldPoint(_MousePosition, _OperaNode.Elev);
                var oldP = (PointF3D)_undoOldValue;
                if (!float.IsInfinity(p.X) && !float.IsInfinity(p.Y)) _newTemplate.OffSet = new PointF3D(p.X - oldP.X, p.Y - oldP.Y, 0); //_OperaNode.Position = p;
 
                GlobalObject.PropertyForm.propertyGrid.Refresh();
                needInvalidate = true;
 
 
            }
            //else
            /*判断是否触碰到对象*/
            {
                // 遍历所有对象,找出范围内的对象
                PointF clickedPoint = new PointF(e.X, e.Y);  //ScreenToMap(new PointF(e.X, e.Y));
                var obj = GetObj_by_ScreenPoint(clickedPoint);
                if (hoveredObjs.Count > 0 && hoveredObjs[0] == obj || hoveredObjs.Count==0 && obj==null)
                {
                    //needInvalidate = false;
                }
                else
                {
                    needInvalidate = true;
                    hoveredObjs.ForEach(o => o.Hovered = false);
                    hoveredObjs.Clear();
                    if (obj!=null)
                    {
                        obj.Hovered = true;
                        hoveredObjs.Add(obj);
                    }
                    
                   
                }
                
 
            }
            
 
 
            if (needInvalidate) this.Invalidate();
            label_mouse.Text = $"X:{e.X.ToString("0")} Y:{e.Y.ToString("0")} [Map]X:{_MousePosition.X.ToString("0.00")} Y:{_MousePosition.Y.ToString("0.00")}";
            _lastMouseX = e.X;
            _lastMouseY = e.Y;
        }
 
        bool RectangContain(RectangleF r, PointF p)
        {
            var x = p.X; var y = p.Y;
 
 
            if (r.X <= x && x < r.X + r.Width && r.Y <= y)
            {
                return y < r.Y + r.Height;
            }
 
            return false;
        }
 
        /// <summary>
        /// 用于绘制管线
        /// </summary>
        NodeViewModel _select_junction1 = null;
        NodeViewModel _select_junction2 = null;
        DateTime _lastMouseUp = DateTime.Now;
        int doubleClick_Delay = 500;//毫秒
        bool recordView = false;
        protected override void OnMouseUp(MouseEventArgs e)
        {
            //BookMark    :鼠标抬起事件
            base.OnMouseUp(e);
            bool isMouseMoved = Get_dist(_ClickStartPos, new PointF(e.X, e.Y)) > 10;
            bool isdoubleClick = (DateTime.Now - _lastMouseUp).TotalMilliseconds <= doubleClick_Delay;
            _lastMouseUp = DateTime.Now;
            if /*框选放大*/(ModifierKeys == Keys.Control && (e.Button == MouseButtons.Middle || e.Button == MouseButtons.XButton2))
            {
                _isDragging = false;
 
                this.Cursor = _lastCursor;
 
                mapOption0 = mapOption;
                var _lastMousePosition = DragStartPos;
 
                List<IBaseViewModel> objs = new List<IBaseViewModel>();
                // 绘制矩形
                var start = new Point((int)Math.Min(mousePosition.X, _lastMousePosition.X), (int)Math.Min(mousePosition.Y, _lastMousePosition.Y));
                var size = new Size((int)Math.Abs(_lastMousePosition.X - mousePosition.X), (int)Math.Abs(_lastMousePosition.Y - mousePosition.Y));
                var rectangle0 = new Rectangle(start, size);
 
                var new_center = MapPointToWorldPoint(new PointF(start.X + size.Width / 2, start.Y + size.Height / 2));
 
                this.MapCenter = new_center;
                this.zoom = Math.Max(1.0f * Width / size.Width, 1.0f * Height / size.Height);
 
                if (recordView) MapObjectExtensions.AddCommand(mapOption, "Map", mapOption0, mapOption);
 
                label_center.Text = $"center:({MapCenter.X.ToString("0.000")} ,{MapCenter.Y.ToString("0.000")})";
                label_zoom.Text = $"Zoom:{zoom.ToString("0.000")}";
                Invalidate();
                return;
            }
            if /*放大镜*/(ModifierKeys == Keys.Shift && (e.Button == MouseButtons.Middle || e.Button == MouseButtons.XButton2))
            {
                _isDragging = false;
 
                this.Cursor = _lastCursor;
 
 
                var _lastMousePosition = DragStartPos;
 
                List<IBaseViewModel> objs = new List<IBaseViewModel>();
                // 绘制矩形
                var start = new Point((int)Math.Min(mousePosition.X, _lastMousePosition.X), (int)Math.Min(mousePosition.Y, _lastMousePosition.Y));
                var size = new Size((int)Math.Abs(_lastMousePosition.X - mousePosition.X), (int)Math.Abs(_lastMousePosition.Y - mousePosition.Y));
                var rectangle0 = new Rectangle(start, size);
                for (int i = 0; i < _Nodes.Count; i++)
                {
                    var node = _Nodes[i] as NodeViewModel;
                    PointF p = WorldPointToMapPoint(node);
                    if (rectangle0.Contains(p.ToPoint()))
                    {
                        //_Nodes[i].Selected = true;
                        //selectedObjs.Add(_Nodes[i]);
                        objs.Add(node);
                    }
                }
 
                for (int i = 0; i < _Links.Count; i++)
                {
                    var link = _Links[i] as LinkViewModel;
                    //PointF p = GetPointF(Pipes[i]);
                    if (rectangle0.Contains(link.Position.ToPoint()))
                    {
                        //_Links[i].Selected = true;
                        //selectedObjs.Add(_Links[i]);
                        objs.Add(link);
                    }
                }
                Form_Magnifier fr = new Form_Magnifier(objs);
 
                fr.ShowDialog();
                return;
            }
            if /*平移视角*/(ModifierKeys == Keys.None && (e.Button == MouseButtons.Middle || e.Button == MouseButtons.XButton2))
            {
                if (recordView) MapObjectExtensions.AddCommand(mapOption, "Map", mapOption0, mapOption);
                this.Cursor = _lastCursor;
                _isPanning = false;
                return;
            }
            if /*设置背景*/(e.Button == MouseButtons.Left && _isSettingBackGroundPictur)
            {
                _Template.BackGroundPoint1 = BackGroudPicLeftPos;
                _Template.BackGroundPoint2 = MapPointToWorldPoint(mousePosition, _Template.BackGroundElev);
 
                _isSettingBackGroundPictur = false;
                mapOption.isShowPic = true;
                this.Cursor = _lastCursor;
                Invalidate();
                return;
            }
            if  /*插入结构*/(e.Button == MouseButtons.Left && _isInsertingObject)
            {
                var net = _newTemplate.network;
                List<NodeViewModel> nodes = _Nodes.Select(node => (NodeViewModel)node).ToList();
                float minDist = 100f;
                NodeViewModel minNode = null;
                foreach (NodeViewModel node in nodes)
                {
 
 
                    PointF mapPos = WorldPointToMapPoint(node);
                    PointF currentPoint = MapToScreen(mapPos);
                    float currentDist = 0;
                    if (node != _OperaNode && (currentDist = Get_dist(new PointF(e.X, e.Y), currentPoint)) < 15f)
                    {
                        if (currentDist < minDist) currentDist = minDist;
                        minNode = node;
                        break;
                    }
                }
                float dx, dy, dz;
 
                if (ModifierKeys != Keys.Alt && minNode != null)
                {
 
                    var p1 = (PointF3D)_undoOldValue;
                    var p2 = minNode.Position3D;
                    var dd = _newTemplate.OffSet;
                    dx = p2.X - p1.X;
                    dy = p2.Y - p1.Y;
                    dz = p2.Z - p1.Z;
 
 
 
                }
                else
                {
                    _NewNet.Clear();
                    _OperaNode = null;
                    _isInsertingObject = false;
                    this.Invalidate();
                    return;
 
                    var p1 = (PointF3D)_undoOldValue;
                    var p2 = _OperaNode.Position3D;
                    var dd = _newTemplate.OffSet;
                    dx = dd.X; //p2.X - p1.X;
                    dy = dd.Y;// p2.Y - p1.Y;
                    dz = dd.Z;// p2.Z - p1.Z;
 
                }
 
 
                net.Nodes.ForEach(n => { ((NodeViewModel)n).Position3D = new PointF3D(n.X + dx, n.Y + dy, n.Elev + dz); });
 
                var list = _Network.Add(net);
 
                var j = _Network.AddPipe(minNode, _OperaNode);
                j.Length = 0.0001f;
                list.Add(j);
                _OperaNode = null;
                _NewNet.Clear();
 
                _Network.BuildRelation();
 
                selectedObjs.ForEach(o => o.Selected = false);
                selectedObjs.Clear();
 
                list.ForEach(m => m.Selected = true);
                selectedObjs.AddRange(list);
 
                MapObjectExtensions.AddCommand(_Network, "Add", null, list);
                _isInsertingObject = false;
 
                //_OperaNode = null;
                //_Network.Nodes.AddRange(net.Nodes);
                //_Network.Links.AddRange(net.Links);
 
                Invalidate();
                return;
            }
            if  /*多边形选择*/(_isDrawingPolygon && e.Button == MouseButtons.Left && ModifierKeys == Keys.None)
            {
                _isDrawingPolygon = false;
                if (polygonPoints.Count >= 3)
                {
                    _Nodes.ForEach(n0 =>
                    {
                        var n = (NodeViewModel)n0;
                        if (IsPointInPolygon(WorldPointToMapPoint(n), polygonPoints))
                        {
                            selectedObjs.Add(n);
                            n.Selected = true;
                        }
                    });
                    _Links.ForEach(n0 =>
                    {
                        var n = (LinkViewModel)n0;
                        if (IsPointInPolygon(WorldPointToMapPoint(n.Position, n.Elev), polygonPoints))
                        {
                            selectedObjs.Add(n);
                            n.Selected = true;
                        }
                    });
 
                }
                Invalidate();
                // 结束绘制多边形
                return;
            }
            if  /*移动对象*/(_isMovingObject && isMouseMoved && e.Button == MouseButtons.Left)
            {
                List<NodeViewModel> nodes = _Nodes.Select(n => (NodeViewModel)n).ToList();
                float minDist = 100f;
                NodeViewModel minNode = null;
                foreach (NodeViewModel node in nodes)
                {
 
 
                    PointF mapPos = WorldPointToMapPoint(node);
                    PointF currentPoint = MapToScreen(mapPos);
                    float currentDist = 0;
                    if (node != _OperaNode && (currentDist = Get_dist(new PointF(e.X, e.Y), currentPoint)) < 15f)
                    {
                        if (currentDist < minDist) currentDist = minDist;
                        minNode = node;
                        break;
                    }
                }
 
 
                if (ModifierKeys != Keys.Alt && minNode != null)
                {
                    _isMovingObject = false;
                    var p1 = (PointF3D)_undoOldValue;
                    var p2 = minNode.Position3D;
                    var dd = _newTemplate.OffSet;
                    var dx = p2.X - p1.X;
                    var dy = p2.Y - p1.Y;
                    var dz = p2.Z - p1.Z;
                    selectedNodes.ForEach(n => { n.Position3D = new PointF3D(n.X + dx, n.Y + dy, n.Elev + dz); });
                    List<PointF3D> newPositons = selectedNodes.Select(n => n.Position3D).ToList();
                    List<PointF3D> oldPositons = newPositons.Select(n => new PointF3D(n.X - dx, n.Y - dy, n.Z - dz)).ToList();
                    MapObjectExtensions.AddCommand(selectedNodes, "Position3D", oldPositons, newPositons);
                    _OperaNode = null;
                    _NewNet.Clear();
                }
                else
                {
                    _isMovingObject = false;
                    var p1 = (PointF3D)_undoOldValue;
                    var p2 = _OperaNode.Position3D;
                    var dd = _newTemplate.OffSet;
                    var dx = dd.X; //p2.X - p1.X;
                    var dy = dd.Y;// p2.Y - p1.Y;
                    var dz = dd.Z;// p2.Z - p1.Z;
                    selectedNodes.ForEach(n => { n.Position3D = new PointF3D(n.X + dx, n.Y + dy, n.Elev + dz); });
                    List<PointF3D> newPositons = selectedNodes.Select(n => n.Position3D).ToList();
                    List<PointF3D> oldPositons = newPositons.Select(n => new PointF3D(n.X - dx, n.Y - dy, n.Z - dz)).ToList();
                    MapObjectExtensions.AddCommand(selectedNodes, "Position3D", oldPositons, newPositons);
                    _OperaNode = null;
                    _NewNet.Clear();
                }
                this.Invalidate();
                return;
            }
            if  /*取消移动对象*/(_isMovingObject && !isMouseMoved && e.Button == MouseButtons.Left)
            {
                _isMovingObject = false;
                var p1 = (PointF3D)_undoOldValue;
                var p2 = _OperaNode.Position3D;
                var dd = _newTemplate.OffSet;
                var dx = dd.X; //p2.X - p1.X;
                var dy = dd.Y;// p2.Y - p1.Y;
                var dz = dd.Z;// p2.Z - p1.Z;
                              //selectedNodes.ForEach(n => { n.Position3D = new PointF3D(n.X + dx, n.Y + dy, n.Elev + dz); });
                              //List<PointF3D> newPositons = selectedNodes.Select(n => n.Position3D).ToList();
                              //List<PointF3D> oldPositons = newPositons.Select(n => new PointF3D(n.X - dx, n.Y - dy, n.Z - dz)).ToList();
                              //MapObjectExtensions.AddCommand(selectedNodes, "Position3D", oldPositons, newPositons);
                _OperaNode = null;
                _NewNet.Clear();
                return;
            }
            if /*特殊功能*/(_mouseState != MouseState.无 && e.Button == MouseButtons.Left)
            {
                PointF p;
                float z;
                NodeViewModel n;
 
                switch (_mouseState)
                {
                    case MouseState.新增节点:
                        getPointAndHeight(e, out p, out z);
                        n = _Network.AddJunction(p, z);
                        MapObjectExtensions.AddCommand(_Network, "Add", null, new List<IBaseViewModel>() { n });
                        break;
                    case MouseState.新建水表:
                        getPointAndHeight(e, out p, out z);
                        n = _Network.AddMeter(p);
                        MapObjectExtensions.AddCommand(_Network, "Add", null, new List<IBaseViewModel>() { n });
                        break;
                    case MouseState.新建水库:
                        getPointAndHeight(e, out p, out z);
                        n = _Network.AddReservoir(p);
                        MapObjectExtensions.AddCommand(_Network, "Add", null, new List<IBaseViewModel>() { n });
                        break;
                    case MouseState.新建水池:
                        getPointAndHeight(e, out p, out z);
                        n = _Network.AddTank(p);
                        MapObjectExtensions.AddCommand(_Network, "Add", null, new List<IBaseViewModel>() { n });
                        break;
                    case MouseState.新增管线:
                    case MouseState.新增立管:
                    case MouseState.新建水泵:
                    case MouseState.新建阀门:
                    case MouseState.新建重复器:
                        if (_select_junction1 == null)
                        {
                            if (_mouseState == MouseState.新增立管)
                            {
                                var m = ScreenToVMap(new PointF(e.X, e.Y));
                                z = m.Y;
                                p = new PointF(m.X, 0);
                                Set_junction1(e);
                            }
                            else
                            {
                                getPointAndHeight(e, out p, out z);
                                Set_junction1(e);
                            }
 
                        }
                        else
                        {
                            if (_mouseState == MouseState.新增立管)
                            {
                                //需要把鼠标位置转换为立管的位置,获取鼠标位置的高程
                                
                                var wPos = GetZZWorldPoint(_select_junction1.Position3D, _MousePosition, new Vector3(0, 0, 1));
                                //var m = ScreenToVMap(new PointF(e.X, e.Y));
                                //z = m.Y;
                                p = new PointF(wPos.X, wPos.Y);
                                var l = AddLink(e, true, p, wPos.Z);
                                if (l.Count > 0) MapObjectExtensions.AddCommand(_Network, "Add", null, l);
                            }
                            else
                            {
                                getPointAndHeight(e, _select_junction1, out p, out z);
                                var l = AddLink(e, isdoubleClick, p, z);
                                if (l.Count > 0) MapObjectExtensions.AddCommand(_Network, "Add", null, l);
 
                            }
                            
                        }
                        break;
                }
                _Network.BuildRelation();
 
                Invalidate();
            }
            if /*锁定点选*/(GlobalObject.LockSelect && !isMouseMoved && _mouseState == MouseState.无 && e.Button == MouseButtons.Left)
            {
                _isDragging = false;
 
                // 遍历所有点,找出最近的点
                PointF clickedPoint = new PointF(e.X, e.Y);  //ScreenToMap(new PointF(e.X, e.Y));
                var obj = GetObj_by_ScreenPoint(clickedPoint);
                bool isJunction = obj is NodeViewModel;
 
                if (obj != null)
                {
                    GlobalObject.PropertyForm.SetObjs(new List<IBaseViewModel>() { obj });
                    if (isJunction) _OperaNode = (NodeViewModel)obj;
                    mousePosition = new PointF(0, 0);
                    Invalidate();
 
                }
                else
                {
                    GlobalObject.PropertyForm.SetObjs(new List<IBaseViewModel>() { });
                    _OperaNode = null;
                    mousePosition = new PointF(0, 0);
                    Invalidate();
                }
                return;
            }
            if /*锁定框选*/(GlobalObject.LockSelect && isMouseMoved && _mouseState == MouseState.无 && e.Button == MouseButtons.Left)
            {
                _isDragging = false;
                Cursor = Cursors.Default;
 
                var _lastMousePosition = DragStartPos;
 
                // 绘制矩形
                var start = new PointF((float)Math.Min(mousePosition.X, _lastMousePosition.X), (float)Math.Min(mousePosition.Y, _lastMousePosition.Y));
                var size = new SizeF((float)Math.Abs(_lastMousePosition.X - mousePosition.X), (float)Math.Abs(_lastMousePosition.Y - mousePosition.Y));
                var rectangle0 = new RectangleF(start, size);
                var selectedObjs = new List<IBaseViewModel>();
                for (int i = 0; i < _Nodes.Count; i++)
                {
 
                    var node = _Nodes[i] as NodeViewModel;
                    if (!node.Visible) continue;
                    PointF p = WorldPointToMapPoint(node);
 
                    if (RectangContain(rectangle0, p))
                    {
                        selectedObjs.Add(node);
 
                    }
                }
 
                for (int i = 0; i < _Links.Count; i++)
                {
                    var link = _Links[i] as LinkViewModel;
                    if (!link.Visible) continue;
                    PointF p = WorldPointToMapPoint(link.Position, link.Elev);
                    if (RectangContain(rectangle0, p))
                    {
                        selectedObjs.Add(link);
                    }
                }
                var findNode = selectedObjs.FindAll(o => o is NodeViewModel);
                if (findNode.Count > 0) _OperaNode = findNode[0] as NodeViewModel;
                if (GlobalObject.PropertyForm != null)
                    GlobalObject.PropertyForm.SetObjs(selectedObjs);
                Invalidate();
                mousePosition = new PointF(0, 0);
                return;
            }
            if /*叠加框选*/(isMouseMoved && _mouseState == MouseState.无 && e.Button == MouseButtons.Left && ModifierKeys == Keys.Control)
            {
 
                _isDragging = false;
                Cursor = Cursors.Default;
 
                var _lastMousePosition = DragStartPos;
 
                // 绘制矩形
                var start = new PointF((float)Math.Min(mousePosition.X, _lastMousePosition.X), (float)Math.Min(mousePosition.Y, _lastMousePosition.Y));
                var size = new SizeF((float)Math.Abs(_lastMousePosition.X - mousePosition.X), (float)Math.Abs(_lastMousePosition.Y - mousePosition.Y));
                var rectangle0 = new RectangleF(start, size);
                for (int i = 0; i < _Nodes.Count; i++)
                {
 
                    var node = _Nodes[i] as NodeViewModel;
                    if (!node.Visible) continue;
                    PointF p = WorldPointToMapPoint(node);
 
                    if (RectangContain(rectangle0, p))
                    {
                        if (selectedObjs.Contains(node))
                        {
                            node.Selected = false;
                            selectedObjs.Remove(node);
                        }
                        else
                        {
                            node.Selected = true;
                            selectedObjs.Add(node);
                        }
 
                    }
                }
 
                for (int i = 0; i < _Links.Count; i++)
                {
                    var link = _Links[i] as LinkViewModel;
                    if (!link.Visible) continue;
                    PointF p = WorldPointToMapPoint(link.Position, link.Elev);
                    if (RectangContain(rectangle0, p))
                    {
                        if (selectedObjs.Contains(link))
                        {
                            link.Selected = false;
                            selectedObjs.Remove(link);
                        }
                        else
                        {
                            link.Selected = true;
                            selectedObjs.Add(link);
                        }
                    }
                }
                if (GlobalObject.PropertyForm != null)
                    GlobalObject.PropertyForm.SetObjs(selectedObjs);
                Invalidate();
                mousePosition = new PointF(0, 0);
                return;
            }
            if /*框选*/(isMouseMoved && _mouseState == MouseState.无 && e.Button == MouseButtons.Left && ModifierKeys == Keys.None)
            {
                _isDragging = false;
                Cursor = Cursors.Default;
 
                var _lastMousePosition = DragStartPos;
 
                // 绘制矩形
                var start = new PointF((float)Math.Min(mousePosition.X, _lastMousePosition.X), (float)Math.Min(mousePosition.Y, _lastMousePosition.Y));
                var size = new SizeF((float)Math.Abs(_lastMousePosition.X - mousePosition.X), (float)Math.Abs(_lastMousePosition.Y - mousePosition.Y));
                var rectangle0 = new RectangleF(start, size);
                selectedObjs.ForEach(obj => obj.Selected = false);
                selectedObjs.Clear();
                for (int i = 0; i < _Nodes.Count; i++)
                {
                    var node = _Nodes[i] as NodeViewModel;
                    if (!node.Visible) continue;
                    PointF p = WorldPointToMapPoint(node);
 
                    if (RectangContain(rectangle0, p))
                    {
                        node.Selected = true;
                        selectedObjs.Add(node);
                    }
                }
 
                for (int i = 0; i < _Links.Count; i++)
                {
                    var link = _Links[i] as LinkViewModel;
 
                    if (!link.Visible) continue;
                    PointF p = WorldPointToMapPoint(link.Position, link.Elev);
                    if (RectangContain(rectangle0, p))
                    {
                        link.Selected = true;
                        selectedObjs.Add(link);
                    }
                }
                if (GlobalObject.PropertyForm != null)
                    GlobalObject.PropertyForm.SetObjs(selectedObjs);
                Invalidate();
                mousePosition = new PointF(0, 0);
                return;
            }
 
            if /*点选*/(!isMouseMoved && _mouseState == MouseState.无 && e.Button == MouseButtons.Left && ModifierKeys == Keys.None)
            {
                _isDragging = false;
 
                // 遍历所有点,找出最近的点
                PointF clickedPoint = new PointF(e.X, e.Y);  //ScreenToMap(new PointF(e.X, e.Y));
                var obj = GetObj_by_ScreenPoint(clickedPoint);
                bool isJunction = obj is NodeViewModel;
 
                if (obj != null)
                {
                    selectedObjs.ForEach(o => o.Selected = false);
                    selectedObjs.Clear();
                    obj.Selected = true;
                    selectedObjs.Add(obj);
                    if (GlobalObject.PropertyForm != null)
                        GlobalObject.PropertyForm.SetObjs(selectedObjs);
                    _OperaNode = null;
 
 
                    Invalidate();
                    mousePosition = new PointF(0, 0);
 
 
                }
                else
                {
                    //GlobalObject.LockSelect
 
                    selectedObjs.ForEach(o => o.Selected = false);
                    selectedObjs.Clear();
                    if (GlobalObject.PropertyForm != null)
                        GlobalObject.PropertyForm.SetObjs(selectedObjs);
 
                    _OperaNode = null;
 
                    Invalidate();
                }
                return;
 
 
            }
 
            if (/*叠加点选*/!isMouseMoved && _mouseState == MouseState.无 && e.Button == MouseButtons.Left && ModifierKeys == Keys.Control)
            {
                _isDragging = false;
 
                // 遍历所有点,找出最近的点
                PointF clickedPoint = new PointF(e.X, e.Y);  //ScreenToMap(new PointF(e.X, e.Y));
                var obj = GetObj_by_ScreenPoint(clickedPoint);
                bool isJunction = obj is NodeViewModel;
                if (obj != null)
                {
                    if (selectedObjs.Contains(obj))
                    {
                        obj.Selected = false;
                        selectedObjs.Remove(obj);
                        if (GlobalObject.PropertyForm != null)
                            GlobalObject.PropertyForm.SetObjs(selectedObjs);
 
                        Invalidate();
                        mousePosition = new PointF(0, 0);
                    }
                    else
                    {
                        obj.Selected = true;
                        selectedObjs.Add(obj);
                        if (GlobalObject.PropertyForm != null)
                            GlobalObject.PropertyForm.SetObjs(selectedObjs);
                        Invalidate();
                        mousePosition = new PointF(0, 0);
                    }
                }
                return;
            }
 
            if (e.Button == MouseButtons.Right)
            {
                if (_isRotating)
                {
                    _isRotating = false;
                    this.Cursor = _lastCursor;
                    if (!isMouseMoved)
                    {
                        右键_Menu.Show(this, e.Location);
                        转换为ToolStripMenuItem.Enabled = selectedNodes.Count > 0; //(selectedObjs.Count == 1);
                        删除ToolStripMenuItem.Enabled = selectedObjs.Count > 0;
                    }
 
                    if (recordView) MapObjectExtensions.AddCommand(mapOption, "Map", mapOption0, mapOption);
                    mousePosition = new PointF(0, 0);
                }
            }
        }
        private void getPointAndHeight(MouseEventArgs e, out PointF p, out float z)
        {
            z = 0;
            if (RotationF != 0)
            {
                p = MapPointToWorldPoint(ScreenToMap(new PointF(e.X, e.Y), z));
 
            }
            else
            {
                var m = ScreenToVMap(new PointF(e.X, e.Y));
                z = m.Y;
                p = new PointF(m.X, 0);
            }
        }
        private void getPointAndHeight(MouseEventArgs e, NodeViewModel j, out PointF p, out float z)
        {
            z = j.Elev;
            if (RotationF != 0)
            {
                p = MapPointToWorldPoint(ScreenToMap(new PointF(e.X, e.Y), j.Elev), j.Elev);
 
            }
            else
            {
                var m = ScreenToVMap(new PointF(e.X, e.Y));
                z = m.Y;
                p = new PointF(j.X, j.Y);
            }
        }
        IBaseViewModel GetObj_by_ScreenPoint(PointF clickedPoint, float DistLimit = 15f)
        {
            float minDist = float.MaxValue;
           
            int minIndex = -1;
            bool isJunction = true;
            IBaseViewModel obj = null;
 
            for (int i = 0; i < _Nodes.Count; i++)
            {
                var node = _Nodes[i] as NodeViewModel;
                if (!node.Visible) continue;
                PointF mapPos = WorldPointToMapPoint(node);
                PointF currentPoint = MapToScreen(mapPos);
                float dist = Get_dist(clickedPoint, currentPoint);
                if (dist < minDist && dist <= DistLimit)
                {
                    minDist = dist;
                    minIndex = i;
                    obj = node;
                }
            }
            for (int i = 0; i < _Links.Count; i++)
            {
                var link = _Links[i] as LinkViewModel;
                if (!link.Visible) continue;
                //float dist = (clickedPoint.X - Pipes[i].X) * (clickedPoint.X - Pipes[i].X) +
                //    (clickedPoint.Y - Pipes[i].Y) * (clickedPoint.Y - Pipes[i].Y);
                PointF mapPos1 = WorldPointToMapPoint(link.StartNode.Position, link.StartNode.Elev);
                PointF currentPoint1 = MapToScreen(mapPos1);
                PointF mapPos2 = WorldPointToMapPoint(link.EndNode.Position, link.EndNode.Elev);
                PointF currentPoint2 = MapToScreen(mapPos2);
                //根据currentPoint1和currentPoint2,判断clickedPoint离线段currentPoint1和currentPoint2的距离
                float dist = Get_dist(clickedPoint, currentPoint1, currentPoint2, DistLimit);
 
                //float dist = Get_dist(clickedPoint, currentPoint);
                if (dist < minDist && dist <= DistLimit)
                {
                    minDist = dist;
                    minIndex = i;
                    isJunction = false;
                    obj = link;
                }
            }
            return obj;
        }
 
        List<IBaseViewModel> GetObjs_by_ScreenPoint(PointF clickedPoint, float DistLimit = 15f)
        {
            float minDist = float.MaxValue;
 
            int minIndex = -1;
       
            IBaseViewModel obj = null;
            List < IBaseViewModel > objs = new List<IBaseViewModel>();
            for (int i = 0; i < _Nodes.Count; i++)
            {
                var node = _Nodes[i] as NodeViewModel;
                if (!node.Visible) continue;
                PointF mapPos = WorldPointToMapPoint(node);
                PointF currentPoint = MapToScreen(mapPos);
                float dist = Get_dist(clickedPoint, currentPoint);
                if (dist <= DistLimit)
                {
                    objs.Add(node);
                }
            }
            for (int i = 0; i < _Links.Count; i++)
            {
                var link = _Links[i] as LinkViewModel;
                if (!link.Visible) continue;
                //float dist = (clickedPoint.X - Pipes[i].X) * (clickedPoint.X - Pipes[i].X) +
                //    (clickedPoint.Y - Pipes[i].Y) * (clickedPoint.Y - Pipes[i].Y);
                PointF mapPos1 = WorldPointToMapPoint(link.StartNode.Position, link.StartNode.Elev);
                PointF currentPoint1 = MapToScreen(mapPos1);
                PointF mapPos2 = WorldPointToMapPoint(link.EndNode.Position, link.EndNode.Elev);
                PointF currentPoint2 = MapToScreen(mapPos2);
                //根据currentPoint1和currentPoint2,判断clickedPoint离线段currentPoint1和currentPoint2的距离
                float dist = Get_dist(clickedPoint, currentPoint1, currentPoint2, DistLimit);
 
                //float dist = Get_dist(clickedPoint, currentPoint);
                if (dist < minDist && dist <= DistLimit)
                {
                    
 
                    objs.Add(link);
                }
            }
            return objs;
        }
 
        /// <summary>
        /// 鼠标滚轮事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseWheel(MouseEventArgs e)
        {
            base.OnMouseWheel(e);
            mapOption0 = mapOption.Copy();
            float oldZoom = zoom;
            zoom *= (float)Math.Pow(2, e.Delta / 120.0 / 10.0);
            zoom = Math.Max(MinZoom, Math.Min(MaxZoom, zoom));
 
            if (recordView) MapObjectExtensions.AddCommand(mapOption, "Map", mapOption0, mapOption);
            Invalidate();
        }
 
        private int _lastMouseX;
        private int _lastMouseY;
        #endregion
 
#endregion 一、全局
 
        #region 二、工具栏
 
 
        #region 视角工具
        // 显示点属性
        private void ShowProperties(IBaseViewModel obj)
        {
            string str = "point";
            if (obj is LinkViewModel) str = "pipe";
            //MessageBox.Show($"{str}:({obj.X.ToString("0.000")} ,{obj.Y.ToString("0.000")})");
            //label_choose.Text = $"{str}[{obj.ID}]({obj.X.ToString("0.000")},{obj.Y.ToString("0.000")})";
            GlobalObject.PropertyForm.SetObj(obj);
        }
 
        private void label_center_Click(object sender, EventArgs e)
        {
            GlobalObject.PropertyForm.SetObj(MapCenter);
        }
        double 俯视角度_bak = 45;
        private void tool视角_ButtonClick(object sender, EventArgs e)
        {
            mapOption0 = mapOption.Copy();
            if (RotationF == 90)
            {
                RotationF = 俯视角度_bak;
            }
            else
            {
                俯视角度_bak = RotationF;
                RotationF = 90;
 
            }
            if (recordView) MapObjectExtensions.AddCommand(mapOption, "Map", mapOption0, mapOption);
            Invalidate();
        }
 
        private void tool设置俯视角度_Click(object sender, EventArgs e)
        {
            mapOption0 = mapOption.Copy();
            double jiaodu = 45;
            var tool = sender as ToolStripItem;
            jiaodu = Convert.ToDouble(tool.Text);
            RotationF = jiaodu;
            if (recordView) MapObjectExtensions.AddCommand(mapOption, "Map", mapOption0, mapOption);
            Invalidate();
 
        }
 
        public void 重置视角ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mapOption0 = mapOption.Copy();
 
            RotationF = 90;
            Rotation = 0;
            InitCenter();
            if (recordView) MapObjectExtensions.AddCommand(mapOption, "Map", mapOption0, mapOption);
            Invalidate();
        }
        private void 正视图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mapOption0 = mapOption.Copy();
            RotationF = 0;
            if (recordView) MapObjectExtensions.AddCommand(mapOption, "Map", mapOption0, mapOption);
 
            Invalidate();
        }
        private void 俯视图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mapOption0 = mapOption.Copy();
            RotationF = 90;
            MapObjectExtensions.AddCommand(mapOption, "Map", mapOption0, mapOption);
 
            Invalidate();
        }
        private void 默认视角ToolStripMenuItem_Click(object sender, EventArgs e)
        {
       
 
            mapOption0 = mapOption.Copy();
            
            InitCenter();
            RotationF = 45;
            Rotation = -45;
            MapObjectExtensions.AddCommand(mapOption, "Map", mapOption0, mapOption);
 
            Invalidate();
        }
        private void 设为隐藏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            selectedObjs.ForEach(v =>
            {
                if (v.Visible)
                {
                    MapObjectExtensions.AddCommand(v, "Visible", v.Visible, false);
                    v.Visible = false;
                }
 
            });
 
            this.Invalidate();
        }
        private void 设置长度ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            double length = 0;
            DialogResult result;
            InputBox input = new InputBox("输入长度");
            if (selectedObjs.Count == 1 && selectedObjs[0] is LinkViewModel l)
            {
                if (double.TryParse(input.ShowDialog(), out length))
                {
 
                    var count1 = _Links.FindAll(ll => ll.Node1 == l.StartNode.ID || ll.Node2 == l.StartNode.ID).Count;
                    var count2 = _Links.FindAll(ll => ll.Node1 == l.EndNode.ID || ll.Node2 == l.EndNode.ID).Count;
                    if (count1 > 1 && count2 <= 1)
                    {
                        MovePointbyLength(l.StartNode, l.EndNode, (float)length);
                    }
                    else if (count2 > 1 && count1 <= 1)
                    {
                        MovePointbyLength(l.EndNode, l.StartNode, (float)length);
                    }
                    else
                    {
                        MovePointbyLength(l.StartNode, l.EndNode, (float)length);
                    }
 
                    Invalidate();
 
                }
 
            }
 
 
 
 
 
            this.Invalidate();
        }
        void MovePointbyLength(NodeViewModel node1, NodeViewModel node2, float Length)
        {
 
            float distance = Vector3.Distance(new Vector3(node1.X, node1.Y, node1.Elev), new Vector3(node2.X, node2.Y, node2.Elev));
 
            if (distance > 0)
            {  // 如果 A 和 B 不是同一个点
               // 计算要移动多少距离
                float moveDistance = Length - distance;
 
                // 计算向量 AB(从 A 指向 B)
                Vector3 AB = new Vector3(node2.X - node1.X, node2.Y - node1.Y, node2.Elev - node1.Elev);
 
                // 计算 AB 的单位向量
                Vector3 unitAB = Vector3.Normalize(AB);
 
                // 计算需要移动的距离的向量(与 AB 方向相同)
                Vector3 moveVector = unitAB * moveDistance;
 
                // 更新点 B 的坐标
                node2.X += moveVector.X;
                node2.Y += moveVector.Y;
                node2.Elev += moveVector.Z;
 
                // 输出移动后的点 B 坐标
                //Console.WriteLine("移动后点 B 的坐标为 ({0}, {1}, {2})", x2, y2, z2);
            }
        }
        private void 全部显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _Nodes.Select(n => (NodeViewModel)n).ToList().ForEach(v =>
            {
                if (!v.Visible)
                {
                    MapObjectExtensions.AddCommand(v, "Visible", v.Visible, true);
                    v.Visible = true;
                }
            });
            _Links.Select(n => (LinkViewModel)n).ToList().ForEach(v0 =>
            {
                var v = (LinkViewModel)v0;
                if (!v.Visible)
                {
                    MapObjectExtensions.AddCommand(v, "Visible", v.Visible, true);
                    v.Visible = true;
                }
            });
            this.Invalidate();
        }
        #endregion
 
 
        #region 文件工具
        private void tool打开_ButtonClick(object sender, EventArgs e)
        {
 
            // 创建打开文件对话框
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "INP Files (*.inp)|*.inp|All Files (*.*)|*.*";
 
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                _Template = new Template();
                _Template.network = new MapViewNetWork();
                //_Template.network.use_old = false;
                // 获取选中文件的文件路径
                string filePath = openFileDialog.FileName;
                {
                    // 读取文件内容
                    _Network.BuildFromInp(filePath);
                    _Template.filePath = filePath;
                    //_filePath = filePath;
                    SetData(_Template);
                }
            }
        }
        private void 旧版打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 创建打开文件对话框
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "INP Files (*.inp)|*.inp|All Files (*.*)|*.*";
 
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                _Template = new Template();
                _Template.network = new MapViewNetWork();
                //_Template.network.use_old = true;
                // 获取选中文件的文件路径
                string filePath = openFileDialog.FileName;
                {
                    // 读取文件内容
                    _Network.BuildFromInp(filePath);
                    _Template.filePath = filePath;
                    //_filePath = filePath;
                    SetData(_Template);
                }
            }
        }
 
        private void 打开文件位置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_filePath == null) return;
            FileInfo fi = new FileInfo(_filePath);
            Process.Start("explorer.exe", $"/select,\"{_filePath}\"");
            //System.Diagnostics.Process.Start("explorer.exe", fi.Directory.FullName);
        }
        private void EPA中打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_filePath == null) return;
 
 
            Process.Start(@"epanetH\Epanet2wH.exe", _filePath);
        }
        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!_IsEditMode)
            {
                if (message.show("提醒", "浏览模式无法保存,是否恢复为编辑模式"))
                {
                    _IsEditMode = true;
 
                }
                else
                    return;
            }
            else
                _Network.BuildToInp(_filePath);
        }
 
        private void toolStripButton_save_Click(object sender, EventArgs e)
        {
 
 
 
 
 
        }
 
        private void 另存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
 
        }
 
        private void 导出形状ToolStripMenuItem_Click(object sender, EventArgs e)
        {
 
        }
        #endregion
 
 
        #region 绘图工具
 
 
        MouseState _mouseState = MouseState.无;
        public void toolStripButton_新建节点_Click(object sender, EventArgs e)
        {
            _mouseState = MouseState.新增节点;
            Cursor = Cursors.Cross;
        }
 
        public void toolStripButton_普通_Click(object sender, EventArgs e)
        {
            _mouseState = MouseState.无;
            Cursor = Cursors.Default;
        }
 
        public void toolStripButton_新建管线_Click(object sender, EventArgs e)
        {
            _mouseState = MouseState.新增管线;
            Cursor = Cursors.Cross;
        }
        public void toolStripButton_新建立管_Click(object sender, EventArgs e)
        {
            _mouseState = MouseState.新增立管;
            Cursor = Cursors.Cross;
        }
 
 
        private List<IBaseViewModel> AddLink(MouseEventArgs e, bool isdoubleClick, PointF p, float z)
        {
            List<IBaseViewModel> l = new List<IBaseViewModel>();
            var node = GetObj_by_ScreenPoint(new PointF(e.X, e.Y));
            if (node != null || isdoubleClick)
            {
                if (node != null && node is NodeViewModel j)
                {
                    _select_junction2 = j;
                }
                else if (isdoubleClick)
                {
                    _select_junction2 = _Network.AddJunction(p, z);
                    l.Add(_select_junction2);
                }
 
                if (_mouseState == MouseState.新增管线 || _mouseState == MouseState.新增立管)
                    l.Add(_Network.AddPipe(_select_junction1, _select_junction2));
                else if (_mouseState == MouseState.新建阀门)
                    l.Add(_Network.AddValve(_select_junction1, _select_junction2));
                else if (_mouseState == MouseState.新建重复器)
                    l.Add(_Network.AddRepeater(_select_junction1, _select_junction2));
                else if (_mouseState == MouseState.新建水泵)
                    l.Add(_Network.AddPump(_select_junction1, _select_junction2));
 
                _select_junction1 = null;
                _select_junction2 = null;
                _isPainting = false;
 
 
            }
            return l;
        }
 
        private void Set_junction1(MouseEventArgs e)
        {
            var node = GetObj_by_ScreenPoint(new PointF(e.X, e.Y));
 
            if (node != null && node is NodeViewModel j)
            {
                _select_junction1 = j;
                _isPainting = true;
            }
        }
 
        public void toolStripButton_添加水表_Click(object sender, EventArgs e)
        {
            _mouseState = MouseState.新建水表;
            Cursor = Cursors.Cross;
        }
 
        public void toolStripButton_添加阀门_Click(object sender, EventArgs e)
        {
            _mouseState = MouseState.新建阀门;
            Cursor = Cursors.Cross;
        }
        public void toolStripButton_添加水泵_Click(object sender, EventArgs e)
        {
            _mouseState = MouseState.新建水泵;
            Cursor = Cursors.Cross;
        }
        public void toolStripButton_添加水库_Click(object sender, EventArgs e)
        {
            _mouseState = MouseState.新建水库;
            Cursor = Cursors.Cross;
        }
 
        public void toolStripButton_添加水池_Click(object sender, EventArgs e)
        {
            _mouseState = MouseState.新建水池;
            Cursor = Cursors.Cross;
        }
        public void toolStripButton_重复器_Click(object sender, EventArgs e)
        {
            _mouseState = MouseState.新建重复器;
            Cursor = Cursors.Cross;
        }
 
        bool Buzylock = false;
        private void MapViewer_KeyDown(object sender, KeyEventArgs e)
        {
 
            if (e.KeyCode == Keys.Escape)
            {
                Cursor = _lastCursor;
                if (_isPainting)
                {
                    _select_junction1 = null;
                    _isPainting = false;
                    Invalidate();
                }
                else if (_isDragging)
                {
                    _isDragging = false;
                    Invalidate();
                }
                else if (_isPanning)
                {
                    _isPanning = false;
                    Invalidate();
                }
                else if (_isRotating)
                {
                    Rotation = Rotation0;
                    _isRotating = false;
                    Invalidate();
                }
                else if (_isMovingObject)
                {
                    _NewNet.Clear();
                    _isMovingObject = false;
                    Invalidate();
                }
                else if (_mouseState != MouseState.无)
                {
                    _mouseState = MouseState.无;
                    Cursor = Cursors.Default;
                }
                else if (_isInsertingObject)
                {
                    _NewNet.Clear();
                    _isInsertingObject = false;
                    _OperaNode = null;
                    Invalidate();
                }
                else
                {
                    _Nodes.ForEach(o => ((NodeViewModel)o).Selected = false);
                    _Links.ForEach(o => ((LinkViewModel)o).Selected = false);
                    selectedObjs.Clear();
                    Invalidate();
 
 
                }
 
 
            }
            if (e.KeyCode == Keys.Delete)
            {
                DeleteChoosedObj();
            }
            if (e.KeyCode == Keys.A && e.Modifiers == Keys.Control)
            {
                selectedObjs.Clear();
                _Nodes.ForEach(o => { ((NodeViewModel)o).Selected = true; selectedObjs.Add((NodeViewModel)o); });
                _Links.ForEach(o => { ((LinkViewModel)o).Selected = true; selectedObjs.Add((LinkViewModel)o); });
                Invalidate();
            }
 
            if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control)
            {
                复制ToolStripMenuItem_Click(1, new EventArgs());
            }
            if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
            {
                _ClickStartPos = Cursor.Position;
                粘贴ToolStripMenuItem1_Click(1, new EventArgs());
            }
            if (e.KeyCode == Keys.D1 && e.Modifiers == Keys.Control)
            {
                南北对齐ToolStripMenuItem_Click(1, new EventArgs());
 
            }
            if (e.KeyCode == Keys.Oemtilde && e.Modifiers == Keys.Control)
            {
                东西对齐ToolStripMenuItem_Click(1, new EventArgs());
            }
            if (e.KeyCode == Keys.D2 && e.Modifiers == Keys.Control)
            {
                竖直对齐ToolStripMenuItem_Click(1, new EventArgs());
            }
            if (e.KeyCode == Keys.D3 && e.Modifiers == Keys.Control)
            {
                自动对齐ToolStripMenuItem_Click(1, new EventArgs());
            }
        }
 
 
 
        private void MapViewer_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (ctrlPressed && e.KeyChar == 'Z' - 64)
            {
                // 执行相应的操作
                buttonUndo_Click(sender, e);
                ctrlPressed = false;
 
                // 防止默认操作
                e.Handled = true;
            }
            if (ctrlPressed && e.KeyChar == 'Y' - 64)
            {
                // 执行相应的操作
                buttonRedo_Click(sender, e);
                ctrlPressed = false;
 
                // 防止默认操作
                e.Handled = true;
            }
            if (ctrlPressed && e.KeyChar == 'R' - 64)
            {
                // 执行相应的操作
                tool视角_ButtonClick(sender, e);
                ctrlPressed = false;
 
                // 防止默认操作
                e.Handled = true;
            }
        }
        private void MapViewer_PreKeyPress(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.Z)
            {
                ctrlPressed = true;
                // 防止默认操作
                e.IsInputKey = true;
 
            }
            if (e.Control && e.KeyCode == Keys.Y)
            {
                ctrlPressed = true;
                // 防止默认操作
                e.IsInputKey = true;
 
            }
            if (e.Control && e.KeyCode == Keys.R)
            {
                ctrlPressed = true;
                // 防止默认操作
                e.IsInputKey = true;
 
            }
        }
        public void setCenter(IBaseViewModel obj)
        {
            PointF position;
            if (obj is LinkViewModel link)
                position = link.Position;
            else
                position = obj.Position;
            PointF currentPos = MapToScreen(WorldPointToMapPoint(position, obj.Elev));
            PointF centerScreen = new PointF(this.Width / 2, this.Height / 2);
            var vector = GetRotateVector(centerScreen, currentPos);
            MapCenter = new PointF(
            MapCenter.X - vector.X / Zoom.X,
            MapCenter.Y - vector.Y / Zoom.Y);
        }
 
        bool ctrlPressed = false;
        #endregion
 
 
        #region 右键菜单
 
 
        private void 转换ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var nodes = selectedNodes;
            foreach (var obj in nodes)
            {
                if (obj == null) return;
                var toolItem = sender as ToolStripItem;
                NodeViewModel junc = null;
                int i = 0;
                string ID;
                switch (toolItem.Text)
                {
                    case "水表":
                        junc = _Network.AddMeter(obj.Position);
                        i = 0;
                        ID = $"{Default.GetPreString(junc)}{i}";
                        while (_Nodes.Find(p0 => p0.ID == ID) != null)
                        {
                            i++;
                            ID = $"{Default.GetPreString(junc)}{i}";
                        }
                        junc.ID = ID;
                        break;
                    case "基本节点":
 
                        junc = _Network.AddJunction(obj.Position, obj.Elev);
                        i = 0;
                        ID = $"{Default.GetPreString(junc)}{i}";
                        while (_Nodes.Find(p0 => p0.ID == ID) != null)
                        {
                            i++;
                            ID = $"{Default.GetPreString(junc)}{i}";
                        }
                        junc.ID = ID;
                        break;
                    case "水库":
                        junc = _Network.AddReservoir(obj.Position);
                        i = 0;
                        ID = $"{Default.GetPreString(junc)}{i}";
                        while (_Nodes.Find(p0 => p0.ID == ID) != null)
                        {
                            i++;
                            ID = $"{Default.GetPreString(junc)}{i}";
                        }
                        junc.ID = ID;
                        break;
                    case "水池":
                        junc = _Network.AddTank(obj.Position);
                        i = 0;
                        ID = $"{Default.GetPreString(junc)}{i}";
                        while (_Nodes.Find(p0 => p0.ID == ID) != null)
                        {
                            i++;
                            ID = $"{Default.GetPreString(junc)}{i}";
                        }
                        junc.ID = ID;
                        break;
                }
                //junc.ID = obj.ID;
 
                junc.Level = obj.Level;
                junc.Elev = obj.Elev;
                junc.Demand = obj.Demand;
 
 
                junc.Selected = true;
                foreach (var p in _Links)
                {
                    if (p.StartNode == obj)
                    {
                        p.StartNode = junc;
 
                    }
                    else if (p.EndNode == obj)
                    {
                        p.EndNode = junc;
                    }
                }
                selectedObjs.Add(junc);
                selectedObjs.Remove(obj);
                //MapObjectExtensions.AddCommand(obj, "Add", null, new List<MapObject>() { n });
                _Nodes.Remove(obj);
            }
 
 
            Invalidate();
        }
 
        public void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteChoosedObj();
        }
 
        private void DeleteChoosedObj()
        {
            var list = _Network.Remove(selectedObjs);
            MapObjectExtensions.AddCommand(_Network, "Remove", null, list);
            selectedObjs.Clear();
            Invalidate();
        }
        #endregion
 
 
        #region 编辑模式/浏览模式切换工具
 
 
 
        private void toolStripComboBox_expandRepeater_ButtonClick(object sender, EventArgs e)
        {
            _IsEditMode = !_IsEditMode;
            //toolStripComboBox_浏览模式.Text = isEditMode ? "编辑模式" : "浏览模式";
            LoadData(true);
        }
 
        private void 浏览模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var obj = sender as ToolStripItem;
            _IsEditMode = obj.Text == "编辑模式";
            //toolStripComboBox_浏览模式.Text = isEditMode ? "编辑模式" : "浏览模式";
            LoadData(true);
        }
        #endregion
 
        /// <summary>
        /// 工具栏可用
        /// </summary>
        public void EnableToolBar()
        {
            this.toolStrip1.Enabled = true;
        }
 
        /// <summary>
        /// 工具栏不可用
        /// </summary>
        public void DisEnableToolBar()
        {
            this.toolStrip1.Enabled = false;
        }
 
        /// <summary>
        /// 隐藏工具栏
        /// </summary>
        public void HideToolBar()
        {
            this.toolStrip1.Visible = false;
        }
 
        /// <summary>
        /// 显示工具栏
        /// </summary>
        public void ShowToolBar()
        {
            this.toolStrip1.Visible = true;
        }
 
        #region 分析工具
 
        private void 水平旋转ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (!selectedObjs[0].isNode())
            //{
            //    MessageBox.Show("围绕第一个节点旋转,选择集中第一个对象必须是");
            //}
 
            var objs = GlobalObject.PropertyForm.selectionSet.selectedObjects;
            var selectobjs = objs.FindAll(o => o is NodeViewModel); //GlobalObject.PropertyForm.listBox1.SelectedItems;
            if (selectobjs.Count <= 0) return;
            //if (selectobjs.Count != 1)
            //{
            //    MessageBox.Show("围绕选中节点进行平面旋转,请在属性列表中选中一个旋转中心对象");
            //    return;
            //}
            if (!(selectobjs[0] as IBaseViewModel).isNode())
            {
                MessageBox.Show("围绕选中节点进行平面旋转,请在属性列表中选中一个节点类对象");
                return;
            }
 
            NodeViewModel origin = selectobjs[0] as NodeViewModel;
            var nodes = objs.FindAll(o => o.isNode());
 
            float jiaodu = float.Parse(toolStripTextBox_水平旋转角度.Text.ToString());
            var NewPositions = GetRotatedPoints(nodes.Select(n => n.Position).ToList(), origin.Position, jiaodu);
            var OldPositions = nodes.Select(n => n.Position).ToList();
            for (int i = 0; i < nodes.Count; i++)
            {
                nodes[i].Position = NewPositions[i];
            }
 
            MapObjectExtensions.AddCommand(nodes, "Position", OldPositions, NewPositions);
 
            Invalidate();
 
        }
 
        public List<PointF> GetRotatedPoints(List<PointF> points, PointF origin, float angle)
        {
            // 将角度转换为弧度
            float radians = angle * (float)Math.PI / 180.0f;
 
            // 计算正余弦值
            float cos = (float)Math.Cos(radians);
            float sin = (float)Math.Sin(radians);
 
            // 定义结果集合,并遍历输入点集合进行旋转处理
            List<PointF> result = new List<PointF>(points.Count);
            foreach (PointF point in points)
            {
                // 将点相对于旋转中心点平移,使其成为以原点为中心的坐标系
                float translatedX = point.X - origin.X;
                float translatedY = point.Y - origin.Y;
 
                // 应用旋转变换
                float rotatedX = translatedX * cos - translatedY * sin;
                float rotatedY = translatedX * sin + translatedY * cos;
 
                // 将点相对于原坐标系平移回去
                float finalX = rotatedX + origin.X;
                float finalY = rotatedY + origin.Y;
 
                // 添加到结果集合中
                result.Add(new PointF(finalX, finalY));
            }
 
            return result;
        }
 
 
        public List<PointF3D> GetRotatedPoints(List<PointF3D> points, Vector3 line, float angle)
        {
            // 将角度转换为弧度
            float radians = (float)(angle * Math.PI / 180.0f);
 
            // 根据旋转直线的方向矢量和旋转角度计算旋转矩阵
            float cos = (float)Math.Cos(radians);
            float sin = (float)Math.Sin(radians);
            float x = line.X;
            float y = line.Y;
            float z = line.Z;
            float[,] rotationMatrix = new float[,]
            {
        {cos + x * x * (1 - cos), x * y * (1 - cos) - z * sin, x * z * (1 - cos) + y * sin},
        {y * x * (1 - cos) + z * sin, cos + y * y * (1 - cos), y * z * (1 - cos) - x * sin},
        {z * x * (1 - cos) - y * sin, z * y * (1 - cos) + x * sin, cos + z * z * (1 - cos)}
            };
 
            // 定义结果集合,并遍历输入点集合进行旋转处理
            List<PointF3D> result = new List<PointF3D>(points.Count);
            foreach (PointF3D point in points)
            {
                // 将点按照旋转中心线平移,使其成为以原点为中心的坐标系
                Vector3 translatedPoint = new Vector3(point.X - line.X, point.Y - line.Y, point.Z - line.Z);
 
                // 应用旋转变换
                Vector3 rotatedPointVector = new Vector3(
                    translatedPoint.X * rotationMatrix[0, 0] + translatedPoint.Y * rotationMatrix[0, 1] + translatedPoint.Z * rotationMatrix[0, 2],
                    translatedPoint.X * rotationMatrix[1, 0] + translatedPoint.Y * rotationMatrix[1, 1] + translatedPoint.Z * rotationMatrix[1, 2],
                    translatedPoint.X * rotationMatrix[2, 0] + translatedPoint.Y * rotationMatrix[2, 1] + translatedPoint.Z * rotationMatrix[2, 2]);
 
                // 将点相对于原坐标系平移回去
                float finalX = rotatedPointVector.X + line.X;
                float finalY = rotatedPointVector.Y + line.Y;
                float finalZ = rotatedPointVector.Z + line.Z;
 
                // 将旋转后的点添加到结果集合中
                result.Add(new PointF3D(finalX, finalY, finalZ));
            }
 
            return result;
        }
 
        private void 缩放ToolStripMenuItem_Click(object sender, EventArgs e)
        {
 
            var objs = GlobalObject.PropertyForm.selectionSet.selectedObjects;
            var list = objs.FindAll(o => o is NodeViewModel); //GlobalObject.PropertyForm.listBox1.SelectedItems;
            if (list.Count <= 0) return;
            //if (selectobjs.Count != 1)
            //{
            //    MessageBox.Show("围绕选中节点进行三维缩放,请在属性列表中选中一个缩放中心对象");
            //    return;
            //}
            //if (!(selectobjs[0] as IBaseViewModel).isNode())
            //var list = objs.FindAll(o => o.ID == selectobjs[0]);
            if (list.Count >= 1 && !list[0].isNode())
            {
                MessageBox.Show("围绕选中节点进行三维缩放,请在属性列表中选中一个[节点类]缩放中心对象");
                return;
            }
 
            NodeViewModel origin = list[0] as NodeViewModel;
            var nodes = objs.FindAll(o => o.isNode()).Select(o => o as NodeViewModel).ToList();
 
            ToolStripMenuItem item = sender as ToolStripMenuItem;
 
            float jiaodu;
            switch (item.Text)
            {
                case "缩小2倍":
                    jiaodu = 0.5f;
                    break;
                case "放大2倍":
                    jiaodu = 2f;
 
                    break;
                default:
                    jiaodu = float.Parse(toolStripTextBox_缩放比例.Text.ToString());
 
                    break;
            }
            var OldPositions = nodes.Select(n => n.Position3D).ToList();
            var NewPositions = ScalePoints(nodes.Select(n => n.Position3D).ToList(), origin.Position3D, jiaodu);
            for (int i = 0; i < nodes.Count; i++)
            {
                nodes[i].X = NewPositions[i].X;
                nodes[i].Y = NewPositions[i].Y;
                nodes[i].Elev = NewPositions[i].Z;
            }
 
            MapObjectExtensions.AddCommand(nodes, "Position3D", OldPositions, NewPositions);
 
            Invalidate();
        }
 
        public static List<PointF3D> ScalePoints(List<PointF3D> points, PointF3D centerPoint, float scale)
        {
            //定义结果集合,并遍历输入点集合进行缩放处理
            List<PointF3D> result = new List<PointF3D>(points.Count);
            foreach (PointF3D point in points)
            {
                //将点相对于缩放中心点平移,使其成为以原点为中心的坐标系
                Vector3 translatedPoint = new Vector3(point.X - centerPoint.X, point.Y - centerPoint.Y, point.Z - centerPoint.Z);
 
                //应用缩放变换
                Vector3 scaledPointVector = new Vector3(
                    translatedPoint.X * scale + centerPoint.X,
                    translatedPoint.Y * scale + centerPoint.Y,
                    translatedPoint.Z * scale + centerPoint.Z);
 
                //将缩放后的点添加到结果集合中
                result.Add(new PointF3D(scaledPointVector.X, scaledPointVector.Y, scaledPointVector.Z));
            }
 
            return result;
        }
 
 
 
 
        public void toolStripButton_计算_Click(object sender, EventArgs e)
        {
            //LoadData();
            _Network.Calc(_Template.FullPath, GlobalPath.configPath + "config_calc.wdb");
        }
 
        public void 关阀搜索ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectedObjs.Count > 0)//&& selectedObjs[0] is Link l
            {
 
                var objs = selectedObjs.ToList();
                var selectsValve = objs.FindAll(o => o is ValveViewModel);
                selectedObjs.ForEach(o => o.Selected = false);
                selectedObjs.Clear();
                TraversePipeNetwork(objs, null, false);
                selectsValve.ForEach(o => o.Selected = false);
                this.Invalidate();
            }
 
        }
        /// <summary>
        /// 关阀分析(考虑水源的情况)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 关阀搜索考虑水源ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectedObjs.Count > 0)//&& selectedObjs[0] is Link l
            {
 
                var objs = selectedObjs.ToList();
                var selectsValve = objs.FindAll(o => o is ValveViewModel);
                selectedObjs.ForEach(o => o.Selected = false);
                selectedObjs.Clear();
                TraversePipeNetwork(objs, null);
                selectsValve.ForEach(o => o.Selected = false);
                this.Invalidate();
 
            }
        }
        //Queue<Link> queue2 = null;
        List<LinkViewModel> LinksToFindSource = null;
        Dictionary<LinkViewModel, List<IBaseViewModel>> Sets = null;
        Dictionary<LinkViewModel, bool> Sets_hasSource = null;
        private void TraversePipeNetwork(List<IBaseViewModel> startObjs, HashSet<NodeViewModel> visitedNodes = null, bool consider = true)
        {
 
            LinksToFindSource = new List<LinkViewModel>();
 
            if (visitedNodes == null)
                visitedNodes = new HashSet<NodeViewModel>();
 
            startObjs.ForEach(o =>
            {
                if (o is LinkViewModel l)
                {
                    TraversePipeNetwork(l, visitedNodes);
                }
                else if (o is NodeViewModel n)
                {
                    n.Links.Select(oo => oo as LinkViewModel).ToList().ForEach(link => TraversePipeNetwork(link, visitedNodes));
 
                }
            });
            if (!consider) return;
            Sets = new Dictionary<LinkViewModel, List<IBaseViewModel>>();
            Sets_hasSource = new Dictionary<LinkViewModel, bool>();
            LinksToFindSource.ForEach(l =>
            {
                TraversePipeNetwork_Set(l, visitedNodes);
            });
 
            foreach (var kp in Sets)
            {
                if (!Sets_hasSource[kp.Key])
                {
                    kp.Value.ForEach(o =>
                    {
                        if (!(o is ValveViewModel))
                        {
                            o.Selected = true;
                            selectedObjs.Add(o);
                        }
 
                    });
                }
            }
            if (GlobalObject.PropertyForm != null)
                GlobalObject.PropertyForm.SetObjs(selectedObjs);
 
        }
        private void TraversePipeNetwork(LinkViewModel startLink, HashSet<NodeViewModel> visitedNodes = null)
        {
 
            Queue<LinkViewModel> queue = new Queue<LinkViewModel>();
 
 
 
            queue.Enqueue(startLink);
            if (visitedNodes == null)
                visitedNodes = new HashSet<NodeViewModel>();
            //visitedNodes.Add(startLink.StartNode);
            //visitedNodes.Add(startLink.EndNode);
 
            while (queue.Count > 0)
            {
                LinkViewModel currentLink = queue.Dequeue();
                //Console.WriteLine("Traversing Link: " + currentLink.ID);
 
                foreach (var node in new NodeViewModel[] { currentLink.StartNode, currentLink.EndNode })
                {
                    if (!visitedNodes.Contains(node) && node != null)
                    {
                        visitedNodes.Add(node);
                        node.Selected = true;
                        selectedObjs.Add(node);
 
                        //Console.WriteLine("Visiting Node: " + node.ID);
                        foreach (var link in node.ViewLinks)
                        {
                            if (!visitedNodes.Contains(link.StartNode) || !visitedNodes.Contains(link.EndNode))
                            {
                                link.Selected = true;
                                selectedObjs.Add(link);
 
 
                                if (!(link is ValveViewModel))
                                {
                                    queue.Enqueue(link);
 
                                }
                                else
                                {
                                    LinksToFindSource.Add(link);
                                }
 
 
                            }
                        }
                    }
                }
 
            }
 
 
 
        }
        private void TraversePipeNetwork_Set(LinkViewModel startLink, HashSet<NodeViewModel> visitedNodes = null)
        {
 
            Queue<LinkViewModel> queue = new Queue<LinkViewModel>();
 
 
 
 
            queue.Enqueue(startLink);
            if (visitedNodes == null)
                visitedNodes = new HashSet<NodeViewModel>();
            //visitedNodes.Add(startLink.StartNode);
            //visitedNodes.Add(startLink.EndNode);
            Sets.Add(startLink, new List<IBaseViewModel>());
            Sets_hasSource.Add(startLink, false);
            while (queue.Count > 0)
            {
                LinkViewModel currentLink = queue.Dequeue();
                //Console.WriteLine("Traversing Link: " + currentLink.ID);
 
                foreach (var node in new NodeViewModel[] { currentLink.StartNode, currentLink.EndNode })
                {
                    if (node == null) continue;
                    if (!visitedNodes.Contains(node))
                    {
                        Sets[startLink].Add(node);
                        visitedNodes.Add(node);
                        if (node is TankViewModel || node is ReservoirViewModel)
                        {
                            Sets_hasSource[startLink] = true;
                        }
 
                        //Console.WriteLine("Visiting Node: " + node.ID);
                        foreach (var link in node.ViewLinks)
                        {
                            if (!visitedNodes.Contains(link.StartNode) || !visitedNodes.Contains(link.EndNode))
                            {
                                Sets[startLink].Add(link);
                                queue.Enqueue(link);
                            }
                        }
                    }
                    else
                    {
                        foreach (var kp in Sets)
                        {
                            if (kp.Key != startLink && kp.Value.Contains(node))
                            {
                                kp.Value.AddRange(Sets[startLink]);
                                Sets_hasSource[kp.Key] = Sets_hasSource[startLink] || Sets_hasSource[kp.Key];
                                Sets.Remove(startLink);
                                Sets_hasSource.Remove(startLink);
                                startLink = kp.Key;
                                break;
                            }
                        }
                    }
                }
 
            }
 
 
 
        }
        private bool FindSouce(LinkViewModel startLink, HashSet<LinkViewModel> visitedLinks, HashSet<LinkViewModel> visitedLinks2, Dictionary<IBaseViewModel, bool> hasSource = null)
        {
 
 
            foreach (var node in new NodeViewModel[] { startLink.StartNode, startLink.EndNode })
            {
 
                if (!hasSource.ContainsKey(node))
                {
                    //hasSource.Add(node, false);
                    hasSource[node] = FindSouce(node, visitedLinks, visitedLinks2, hasSource);
                }
 
                if (hasSource[node] == true) return true;
 
 
            }
            return false;
 
 
 
        }
        private bool FindSouce(NodeViewModel startNode, HashSet<LinkViewModel> visitedLinks, HashSet<LinkViewModel> visitedLinks2, Dictionary<IBaseViewModel, bool> hasSource = null)
        {
 
            foreach (var link in startNode.ViewLinks)
            {
                if (hasSource.ContainsKey(link) && hasSource[link] == true) return true;
                if (visitedLinks.Contains(link) && startNode == link.StartNode) continue;
                if (visitedLinks2.Contains(link) && startNode == link.EndNode) continue;
                if (startNode == link.StartNode)
                    visitedLinks.Add(link);
                else
                    visitedLinks2.Add(link);
                if (!hasSource.ContainsKey(link))
                {
 
                    //hasSource.Add(link,false);
                    hasSource[link] = FindSouce(link, visitedLinks, visitedLinks2, hasSource);
                }
 
                if (hasSource[link] == true) return true;
 
 
            }
            return false;
 
 
        }
 
 
 
 
        //private void 联通性ToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    if (selectedObjs.Count > 0)//&& selectedObjs[0] is Link l
        //    {
 
        //        var objs = selectedObjs.FindAll(o => o is LinkViewModel).Select(o => o as LinkViewModel).ToList();
        //        var visitedNodes = new HashSet<NodeViewModel>();
        //        objs.ForEach(o => TraversePipeNetworkALL(o, visitedNodes));
 
 
        //        this.Invalidate();
 
        //    }
        //}
        private void TraversePipeNetworkALL(LinkViewModel startLink, HashSet<NodeViewModel> visitedNodes = null, int direction = 0)
        {
 
            Queue<LinkViewModel> queue = new Queue<LinkViewModel>();
 
 
 
            queue.Enqueue(startLink);
            if (visitedNodes == null)
                visitedNodes = new HashSet<NodeViewModel>();
            //visitedNodes.Add(startLink.StartNode);
            //visitedNodes.Add(startLink.EndNode);
 
            while (queue.Count > 0)
            {
                LinkViewModel currentLink = queue.Dequeue();
                //Console.WriteLine("Traversing Link: " + currentLink.ID);
 
                foreach (var node in new NodeViewModel[] { currentLink.StartNode, currentLink.EndNode })
                {
                    if (direction == 1 && currentLink.EN_FLOW >= 0 && node == currentLink.StartNode) continue;
                    if (direction == -1 && currentLink.EN_FLOW <= 0 && node == currentLink.EndNode) continue;
                    if (node != null && !visitedNodes.Contains(node))
                    {
                        visitedNodes.Add(node);
                        node.Selected = true;
                        selectedObjs.Add(node);
 
                        //Console.WriteLine("Visiting Node: " + node.ID);
                        foreach (var link in node.ViewLinks)
                        {
                            if (!visitedNodes.Contains(link.StartNode) || !visitedNodes.Contains(link.EndNode))
                            {
                                link.Selected = true;
                                selectedObjs.Add(link);
                                queue.Enqueue(link);
 
 
 
 
                            }
                        }
                    }
                }
 
            }
 
 
 
        }
        #endregion
 
 
        #region 显示选项
 
        private void 显示节点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _ShowJunction = true;
            Invalidate();
        }
 
        private void 隐藏节点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _ShowJunction = false;
            Invalidate();
        }
 
        private void 大ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var item = sender as ToolStripItem;
            if (item.Text == "大")
            {
                junction_multiply = 1f;
            }
            else if (item.Text == "中")
            {
                junction_multiply = 0.6667f;
            }
            else
            {
                junction_multiply = 0.4f;
            }
            Invalidate();
        }
 
        private void 显示阀门ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _ShowValve = true;
            Invalidate();
 
        }
 
        private void 隐藏阀门ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _ShowValve = false;
            Invalidate();
 
 
        }
 
        private void 大ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var item = sender as ToolStripItem;
            if (item.Text == "大")
            {
                Link_multiply = 1f;
            }
            else if (item.Text == "中")
            {
                Link_multiply = 0.6667f;
            }
            else
            {
                Link_multiply = 0.4f;
            }
            Invalidate();
        }
 
 
        #endregion
 
 
        #endregion 二、工具栏
 
        #region 方法
        private void 标高推测ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int num = UpdateNodesEle();
            if (num > 0)
            {
                MessageBox.Show($"更新成功,更新节点数量:{num}个");
            }
            else
            {
                MessageBox.Show($"没有需要更新的节点");
 
            }
        }
        public int UpdateNodesEle()
        {
            int num = 0;
            foreach (NodeViewModel node in _Nodes)
            {
                if (node.Elev == 0 && node is JunctionViewModel)
                {
                    HashSet<NodeViewModel> nodeSet = new HashSet<NodeViewModel>();
                    nodeSet.Add(node);
                    List<NodeViewModel> nonZeroNeighbors = new List<NodeViewModel>();
                    FindNonZeroNeighbors(node, nonZeroNeighbors, nodeSet);
                    if (nonZeroNeighbors.Count != 0)
                    {
                        float sum = 0;
                        float weightSum = 0;
 
                        foreach (NodeViewModel neighbor in nonZeroNeighbors)
                        {
                            float dist = Get_dist(node.Position, neighbor.Position);
                            if (dist == 0)
                            {
                                dist = 0.0000000001f;
                            }
                            float weight = 1 / dist;// CalculateWeight(node, neighbor);
                            sum += neighbor.Elev * weight;
                            weightSum += weight;
                        }
 
                        float average = sum / weightSum;
                        node.Elev = average;
                        num++;
                    }
                }
            }
            return num;
        }
 
        private void FindNonZeroNeighbors(NodeViewModel node, List<NodeViewModel> result, HashSet<NodeViewModel> origin)
        {
            foreach (LinkViewModel link in node.ViewLinks)
            {
                NodeViewModel neighbor = null;
                if (link.StartNode == node)
                {
                    neighbor = link.EndNode;
 
                }
                else
                {
                    neighbor = link.StartNode;
                }
 
                if (neighbor.Elev != 0)
                {
                    result.Add(neighbor);
                }
                else if (!origin.Contains(neighbor))
                {
                    origin.Add(neighbor);
                    FindNonZeroNeighbors(neighbor, result, origin);
                }
            }
        }
        private void 标高导出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("Elev", typeof(float));
            foreach (NodeViewModel node in _Nodes)
            {
                if (node is JunctionViewModel junction)
                {
                    var dr = dt.NewRow();
                    dr.ItemArray = new object[] { junction.ID, junction.Elev };
                    dt.Rows.Add(dr);
                }
            }
            dtToSql(dt);
 
        }
        void dtToCsv(DataTable dt)
        {
            // 创建 SaveFileDialog 对象
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "CSV Files (*.csv)|*.csv";
            saveFileDialog.FileName = "output.csv";
 
            // 如果用户选择了保存位置和文件名,则执行保存操作
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                // 获取用户选择的保存路径和文件名
                string filePath = saveFileDialog.FileName;
 
                // 假设 dt 是包含数据的 DataTable 对象
 
                // 构建 CSV 字符串
                StringBuilder csvContent = new StringBuilder();
 
                // 写入表头
                foreach (DataColumn column in dt.Columns)
                {
                    csvContent.Append(column.ColumnName);
                    csvContent.Append(",");
                }
                csvContent.AppendLine();
 
                // 写入数据行
                foreach (DataRow row in dt.Rows)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        csvContent.Append(row[i]);
                        csvContent.Append(",");
                    }
                    csvContent.AppendLine();
                }
 
                // 将 CSV 内容写入文件
                File.WriteAllText(filePath, csvContent.ToString());
 
                // 显示保存成功消息框
                MessageBox.Show("文件保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        void dtToSql(DataTable dt)
        {
            // 创建 SaveFileDialog 对象
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Txt Files (*.txt)|*.txt";
 
 
            // 如果用户选择了保存位置和文件名,则执行保存操作
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                // 获取用户选择的保存路径和文件名
                string filePath = saveFileDialog.FileName;
 
                // 假设 dt 是包含数据的 DataTable 对象
                string tableString = @"
IF OBJECT_ID('Elev', 'U') IS NOT NULL
BEGIN
    -- 清空表
    TRUNCATE TABLE Elev;
END
ELSE
BEGIN
    -- 创建表
    CREATE TABLE Elev (
        ID NVARCHAR(50),
        Elev REAL
    );
END
 
 
";
                // 构建 CSV 字符串
                StringBuilder csvContent = new StringBuilder();
 
                csvContent.AppendLine(tableString);
 
 
 
                //// 写入表头
                //foreach (DataColumn column in dt.Columns)
                //{
 
                //    csvContent.Append(column.ColumnName);
                //    csvContent.Append(",");
                //}
                //csvContent.AppendLine();
 
                int i = 0;
                int j = 0;
                while (i < dt.Rows.Count)
                {
 
                    if (j == 0) csvContent.AppendLine("INSERT INTO Elev (ID, Elev) VALUES");
                    // 写入数据行
 
                    DataRow row = dt.Rows[i];
                    csvContent.Append($"('{row[0]}',{row[1]})");
                    csvContent.Append(i == dt.Rows.Count - 1 || j == 999 ? ";" : ",");
                    csvContent.AppendLine();
                    i++;
                    j++;
                    if (j == 1000) j = 0;
 
 
 
                }
 
 
                // 将 CSV 内容写入文件
                File.WriteAllText(filePath, csvContent.ToString());
 
                // 显示保存成功消息框
                MessageBox.Show("文件保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
 
        private void 导入jsonToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog();
            ofd.Filter = "json文件|*.json";
            var result = ofd.ShowDialog();
            if (result == DialogResult.OK)
            {
                _Template = new Template(new Guid().ToString(), "新建", "复制", TemplateType.其他);
                string json = File.ReadAllText(ofd.FileName);
                _Template.network = JsonConvert.DeserializeObject<MapViewNetWork>(json);
                _Template.network.BuildRelation();
                TemplateList.AddTemp(_Template);
                LoadData();
            }
        }
        public void buttonUndo_Click(object sender, EventArgs e)
        {
            SetInvalidated();
            GlobalObject.PropertyForm.propertyGrid.Refresh();
            MapObjectExtensions.Undo();
        }
        public void buttonRedo_Click(object sender, EventArgs e)
        {
            SetInvalidated();
            GlobalObject.PropertyForm.propertyGrid.Refresh();
            MapObjectExtensions.Redo();
        }
        public void toolStripButton_save_ButtonClick(object sender, EventArgs e)
        {
            if (_Template == null) return;
 
            if (!_IsEditMode)
            {
                if (message.show("提醒", "浏览模式无法保存,是否恢复为编辑模式"))
                {
                    _IsEditMode = true;
                }
                else
                    return;
            }
            else
            {
                bool isReplace = false;
                _Network.BuildToInp(_filePath, null, null, false);
            }
        }
 
        private void 以当前视角另存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_Template == null) return;
 
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("[COORDINATES]");
            sb.AppendLine(";Node                X-Coord               Y-Coord");
            _Nodes.ForEach(n =>
            {
                var p = WorldPointToMapPoint((NodeViewModel)n);
                sb.AppendLine($"{n.ID} {p.X} {p.Y}");
 
            });
 
 
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Inp Files (*.inp)|*.inp";
            saveFileDialog.InitialDirectory = Directory.GetCurrentDirectory() + $@"\template\";
            if (_filePath != null) saveFileDialog.FileName = _filePath;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = saveFileDialog.FileName;
                // 使用 filePath 变量来保存文件
                //temp.路径 = filePath;
                _Network.BuildToInp(filePath, sb.ToString(), _filePath);
                //_filePath = filePath;
 
 
            }
        }
        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
 
            bool isReplace = false;
            //isReplace = !message.show("模板选择", "使用模板新增/替换当前文件", MessageBoxButtons.YesNo);
 
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Inp Files (*.inp)|*.inp";
            saveFileDialog.InitialDirectory = Directory.GetCurrentDirectory() + $@"\template\";
            if (_filePath != null) saveFileDialog.FileName = _filePath;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = saveFileDialog.FileName;
                // 使用 filePath 变量来保存文件
                //temp.路径 = filePath;
 
 
                _Network.BuildToInp(filePath, null, _filePath, isReplace);
                //_filePath = filePath;
 
 
            }
        }
        private void 连通性检查ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (selectedObjs.Count > 0)//&& selectedObjs[0] is Link l
            {
 
                var objs = selectedObjs.FindAll(o => o is LinkViewModel).Select(o => o as LinkViewModel).ToList();
                if (objs.Count == 0) selectedObjs.FindAll(o => o is NodeViewModel).Select(o => o as NodeViewModel).ToList().ForEach(o => objs.AddRange(o.Links.Select(l => l as LinkViewModel).ToList()));
                //objs去掉重复的元素
                objs = objs.Distinct().ToList();
                var visitedNodes = new HashSet<NodeViewModel>();
                objs.ForEach(o => TraversePipeNetworkALL(o, visitedNodes));
 
 
                this.Invalidate();
 
            }
        }
        private void 下游连通性ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectedObjs.Count > 0)//&& selectedObjs[0] is Link l
            {
 
                var objs = selectedObjs.FindAll(o => o is LinkViewModel).Select(o => o as LinkViewModel).ToList();
                if (objs.Count == 0) selectedObjs.FindAll(o => o is NodeViewModel).Select(o => o as NodeViewModel).ToList().ForEach(o =>
                {
                    objs.AddRange(o.Links.Select(oo => oo as LinkViewModel).ToList().FindAll(oo => oo.StartNode == o ? oo.EN_FLOW > 0 : oo.EN_FLOW < 0));
                });
                //objs去掉重复的元素
                objs = objs.Distinct().ToList();
                var visitedNodes = new HashSet<NodeViewModel>();
                objs.ForEach(o => TraversePipeNetworkALL(o, visitedNodes, 1));
                this.Invalidate();
 
            }
        }
        public void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(hoveredObjs.Count<=0 || !(hoveredObjs[0] is NodeViewModel))
            {
                MessageBox.Show("请将鼠标悬停在一个节点对象上,作为基准点");
                return;
            }
            if (selectedObjs.Count <= 0 || selectedNodes.Count <= 0)
            {
                MessageBox.Show("请选择要复制的对象");
                return;
            }
           
            _OperaNode = hoveredObjs[0] as NodeViewModel;
 
            MapViewNetWork net = new MapViewNetWork();
            net.StartPoint = _OperaNode;
            net.Nodes.AddRange(selectedObjs.FindAll(o => o is NodeViewModel).Select(o => o as NodeViewModel));
            net.Links.AddRange(selectedObjs.FindAll(o => o is LinkViewModel).Select(o => o as LinkViewModel));
 
            string json = net.WriteToJson();
            try
            {
                Clipboard.SetText(json);
                this.Invalidate();
            }
            catch
            {
                //提醒
 
            }
 
 
        }
        public void 粘贴ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            {
                var net = new MapViewNetWork();
                string json = Clipboard.GetText();
                net.ReadFromJson(json);
                PointF minPoint = new PointF(net.StartPoint.X, net.StartPoint.Y);
                Point controlLocation = this.PointToScreen(new Point(0, 0));
                int offsetX = Cursor.Position.X - controlLocation.X;
                int offsetY = Cursor.Position.Y - controlLocation.Y;
                var position = new Point(offsetX, offsetY);
 
                net.BuildRelation();
                var basePoint = MapPointToWorldPoint(ScreenToMap(position, net.StartPoint.Elev), net.StartPoint.Elev);
                net.Nodes.ForEach(obj =>
                {
                    obj.X = obj.X + basePoint.X - minPoint.X;
                    obj.Y = obj.Y + basePoint.Y - minPoint.Y;
                });
                selectedObjs.ForEach(o => o.Selected = false);
                selectedObjs.Clear();
                selectedObjs.AddRange(net.Nodes.Select(n => (NodeViewModel)n));
                selectedObjs.AddRange(net.Links.ViewLinks);
                var list = _Network.Add(net);
                MapObjectExtensions.AddCommand(_Network, "Add", null, list);
                Invalidate();
            }
        }
        private void 增量保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_Template == null) return;
 
            if (!_IsEditMode)
            {
                if (message.show("提醒", "浏览模式无法保存,是否恢复为编辑模式"))
                {
                    _IsEditMode = true;
                }
                else
                    return;
            }
            else
            {
                bool isReplace = true;
                //isReplace = !message.show("模板选择", "使用模板新增/替换当前文件", MessageBoxButtons.YesNo);
                _Network.BuildToInp(_filePath, null, null, false);
 
 
            }
        }
        private void 设为关闭ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            selectedObjs.ForEach(obj => { if (obj is LinkViewModel link) link.Status =Hydro.Core.ObjectEnum. StatusType.CLOSED; });
            Invalidate();
        }
        private void 显示全部楼层ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //this.mapOption.ShowFloor = int.MinValue;
            _Network.MapObjects.ForEach(o => o.Visible = true);
            this.Invalidate();
        }
        private void 保存楼层视角ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //if (_Template?.Floors!=null)
            //{
            //    var fl = _Template.Floors.Find(f => f.FloorIndex == this.mapOption.ShowFloor);
            //    if (fl!=null)fl.MapView = this.mapOption.Copy();
            //}
        }
        public void 南北对齐ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectedNodes.Count < 1) return;
            List<float> list = new List<float>();
            List<float> list1 = new List<float>();
            selectedNodes.ForEach(n => { list.Add(n.X); n.X = selectedNodes[0].X; list1.Add(n.X); });
            MapObjectExtensions.AddCommand(selectedNodes, "X", list, list1);
            this.Invalidate();
        }
        public void 东西对齐ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectedNodes.Count < 1) return;
            List<float> list = new List<float>();
            List<float> list1 = new List<float>();
            selectedNodes.ForEach(n => { list.Add(n.Y); n.Y = selectedNodes[0].Y; list1.Add(n.Y); });
            MapObjectExtensions.AddCommand(selectedNodes, "Y", list, list1);
            this.Invalidate();
        }
        public void 竖直对齐ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectedNodes.Count < 1) return;
            List<PointF> list = new List<PointF>();
            List<PointF> list1 = new List<PointF>();
            selectedNodes.ForEach(n => { list.Add(n.Position); n.Position = selectedNodes[0].Position; list1.Add(n.Position); });
            MapObjectExtensions.AddCommand(selectedNodes, "Position", list, list1);
            this.Invalidate();
        }
        public void 自动对齐ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectedNodes.Count < 3) return;
            List<PointF3D> OldPosition3Ds = selectedNodes.Select(n => n.Position3D).ToList();
            List<PointF3D> NewPosition3Ds = ProjectPointsToLine(OldPosition3Ds);
            for (int i = 0; i < selectedNodes.Count; i++)
            {
                selectedNodes[i].Position3D = NewPosition3Ds[i];
            }
 
            MapObjectExtensions.AddCommand(selectedNodes, "Position3D", OldPosition3Ds, NewPosition3Ds);
            this.Invalidate();
        }
        List<PointF3D> ProjectPointsToLine(List<PointF3D> points)
        {
            // 使用最小二乘法构造直线,并将点投影到直线上
 
            // 计算均值
            double sumX = 0;
            double sumY = 0;
            double sumZ = 0;
 
            foreach (PointF3D point in points)
            {
                sumX += point.X;
                sumY += point.Y;
                sumZ += point.Z;
            }
 
            double meanX = sumX / points.Count;
            double meanY = sumY / points.Count;
            double meanZ = sumZ / points.Count;
 
            // 计算最小二乘法拟合直线的参数
 
            double sumXY = 0;
            double sumX2 = 0;
 
            foreach (PointF3D point in points)
            {
                double devX = point.X - meanX;
                double devY = point.Y - meanY;
                double devZ = point.Z - meanZ;
 
                sumXY += devX * devY;
                sumX2 += devX * devX;
            }
 
            double slope = sumXY / sumX2;
            double interceptY = meanY - slope * meanX;
            double interceptZ = meanZ - slope * meanX;
 
            // 计算点投影到直线上的坐标
 
            List<PointF3D> projectedPoints = new List<PointF3D>();
 
            foreach (PointF3D point in points)
            {
                double projectedY = slope * point.X + interceptY;
                double projectedZ = slope * point.X + interceptZ;
 
                projectedPoints.Add(new PointF3D(point.X, (float)projectedY, (float)projectedZ));
            }
 
            return projectedPoints;
        }
 
        public void 添加底图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_Template == null) return;
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Image Files (*.bmp;*.jpg;*.jpeg;*.png;*.gif)|*.bmp;*.jpg;*.jpeg;*.png;*.gif";
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
 
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                var backgroundImagePath = openFileDialog.FileName;
                Global.ClearFileReadOnly(_Template.BackGroundImg_FullPath);
                File.Copy(backgroundImagePath, _Template.BackGroundImg_FullPath, true);
                设置底图ToolStripMenuItem_Click(1, new EventArgs());
            }
        }
        bool _isSettingBackGroundPictur = false;
 
        public void 设置底图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string inputValue = "0";// Prompt.ShowDialog("请输入底图标高", "");
            float BackGroundElev = 0;
            if (float.TryParse(inputValue, out float result))
            {
                BackGroundElev = result;
            }
            else
            {
                BackGroundElev = 0;
            }
            _Template.BackGroundElev = BackGroundElev;
            _mouseState = MouseState.设置底图范围;
            this._lastCursor = this.Cursor;
            this.Cursor = Cursors.Cross;
        }
 
        public void 显示隐藏底图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mapOption.isShowPic = !mapOption.isShowPic;
            Invalidate();
        }
 
        private dict<string, dynamic> param = null;
 
        public void 清除底图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mapOption.isShowPic = false;
            Invalidate();
            try
            {
                File.Delete(_Template.BackGroundImg_FullPath);
            }
            catch
            {
            }
        }
 
        private void label_zoom_Click(object sender, EventArgs e)
        {
            string inputValue = Prompt.ShowDialog("请输入比例", "");
            if (float.TryParse(inputValue, out float result))
            {
                zoom = result;
 
            }
        }
        private void label_file_DoubleClick(object sender, EventArgs e)
        {
            if (_filePath == null) return;
            FileInfo fi = new FileInfo(_filePath);
            Process.Start("explorer.exe", $"/select,\"{_filePath}\"");
        }
        private void label_file_Click(object sender, EventArgs e)
        {
            if (_filePath == null) return;
            FileInfo fi = new FileInfo(_filePath);
            Process.Start("explorer.exe", $"/select,\"{_filePath}\"");
        }
        private void 设为立管点ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (selectedNodes.Count == 1)
            {
                _Template.Node2 = _EndPoint = selectedNodes[0].ID;
            }
 
        }
        private void 显示水流ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _Template.network.MapObjects.ForEach(o => o.Selected = false);
            selectedObjs.Clear();
            _Template.network.Links.ForEach(link =>
            {
                if (link.EN_FLOW != 0)
                {
                    selectedObjs.Add(link);
                    link.Selected = true;
                    NodeViewModel node = link.StartNode;
                    node.Selected = true;
                    if (!selectedObjs.Contains(node)) selectedObjs.Add(node);
                    node = link.EndNode;
                    node.Selected = true;
                    if (!selectedObjs.Contains(node)) selectedObjs.Add(node);
 
                }
 
            });
            this.Invalidate();
 
        }
        private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            selectedObjs.Clear();
            _Template.network.MapObjects.ForEach(o =>
            {
                if (o.Visible)
                {
                    o.Selected = true;
                    selectedObjs.Add(o);
                }
 
            });
            this.Invalidate();
 
        }
        private void 反选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
 
            _Template.network.MapObjects.ForEach(o =>
            {
                if (o.Visible)
                {
                    if (o.Selected)
                    {
                        o.Selected = false;
                        selectedObjs.Remove(o);
                    }
                    else
                    {
                        o.Selected = true;
                        selectedObjs.Add(o);
                    }
 
                }
 
            });
            this.Invalidate();
        }
        private void 显示状态ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _Template.mapOption._ShowStatus = true;
            this.Invalidate();
        }
        private void 隐藏状态ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _Template.mapOption._ShowStatus = false;
            this.Invalidate();
 
        }
        private void 显示流向ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _Template.mapOption._ShowFlowDirection = true;
            this.Invalidate();
 
 
 
        }
        private void 隐藏流向ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _Template.mapOption._ShowFlowDirection = false;
            this.Invalidate();
 
 
        }
        private void 方向修复ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _Network.Links.ForEach(l =>
            {
                //根据l.EN_FLOW重新设置l.STARTNODE和l.ENDNODE
                if (l.EN_FLOW < 0)
                {
                    var node = l.StartNode;
                    l.StartNode = l.EndNode;
                    l.EndNode = node;
                }
            });
        }
        private void 刷新楼层ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem_Floor.DropDownItems.Clear();
            var mapobjects = _Network.MapObjects;
            TagList tags = new TagList();
            foreach (var item in mapobjects)
            {
                if (item.Tags != null)
                    tags.AddRange(item.Tags);
            }
            var t = tags.Distinct().ToList();
            tags.Clear();
            tags.AddRange(t);
            for (int i = -10; i < 1000; i++)
            {
                string tagstring = i.ToString() + "楼";
                if (tags.Contains(tagstring))
                {
                    var item = ToolStripMenuItem_Floor.DropDownItems.Add(i.ToString() + "楼");
                    item.Click += (oo, ee) =>
                    {
 
 
                        mapobjects.ForEach(o =>
                        {
                            if (o.Tags.Contains(tagstring))
                            {
                                o.Visible = true;
                            }
                            else
                            {
                                o.Visible = false;
                            }
                        });
                        this.Invalidate();
 
                    };
                }
            }
            this.Invalidate();
        }
 
        private void 显示所有隐藏内容ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _Network.MapObjects.ForEach(o => o.Visible = true);
            this.Invalidate();
        }
        public void toolStripButton_CalcMiniLoss_Click(object sender, EventArgs e)
        {
            _Network.SetNodeDemand();
            _Network.Calc(_Template.FullPath, GlobalPath.configPath + "config_calc.wdb");
            _Network.CalcLinkMinorLoss();
        }
        private void toolStripButton_ClearMinor_Click(object sender, EventArgs e)
        {
 
            _Network.ClearMinorLoss();
        }
        private void 显示流向ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            _isShowDirection = !_isShowDirection;
        }
        bool _isShowDirection = false;
        private void 颜色分级管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form_Colour form_Colour = new Form_Colour(_Template.Colours);
            form_Colour.Show(this);
        }
        Colour _NodeColour = null;
        Colour _LinkColour = null;
        private List<IBaseViewModel> hoveredObjs=new List<IBaseViewModel>();
        private bool __isOrtho = true;
        private bool _isOrtho
        {
            get
            {
                return __isOrtho;
            }
            set
            {
                __isOrtho = value;
                if (__isOrtho)
                {
                    label_ZZ.Text = "正交模式:开";
                }
                else
                {
                    label_ZZ.Text = "正交模式:关";
                }
            }
        }
 
        private void cb_Node_Colour_Click(object sender, EventArgs e)
        {
 
        }
        private void cb_Link_Colour_Click(object sender, EventArgs e)
        {
 
        }
        private void cb_Link_Colour_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_Template == null) return;
            mapOption.LinkColourIndex = cb_Link_Colour.SelectedIndex;
            var type = cb_Link_Colour.SelectedItem == null ? ColourType.管线流量 : (ColourType)cb_Link_Colour.SelectedItem;
            var Colours = _Template.Colours.FindAll(c => c.Type == type);
            if (Colours.Count == 0)
            {
                _LinkColour = null;
            }
            else
            {
                var cls = Colours.FindAll(cl => cl.isChoosed);
                if (cls.Count >= 1)
                {
                    _LinkColour = cls[0];
                }
                else
                {
                    _LinkColour = Colours[0];
                }
            }
            this.Invalidate();
        }
        private void cb_Node_Colour_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_Template == null) return;
            mapOption.NodeColourIndex = cb_Node_Colour.SelectedIndex;
            var type = cb_Node_Colour.SelectedItem == null ? ColourType.节点自由压力 : (ColourType)cb_Node_Colour.SelectedItem;
            var Colours = _Template.Colours.FindAll(c => c.Type == type);
            if (Colours.Count == 0)
            {
                _NodeColour = null;
            }
            else
            {
                var cls = Colours.FindAll(cl => cl.isChoosed);
                if (cls.Count >= 1)
                {
                    _NodeColour = cls[0];
                }
                else
                {
                    _NodeColour = Colours[0];
 
                }
            }
            this.Invalidate();
        }
 
        private void label_ZZ_Click(object sender, EventArgs e)
        {
            //正交模式的全局变量开关
            _isOrtho = !_isOrtho;
        }
 
        private void 楼层管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_Template.Regions==null)
            {
                _Template.Regions = new List<TRegion>();
            }
            Form_EditFloors form_EditFloors = new Form_EditFloors(_Template.Regions);
            form_EditFloors.Show(this);
        }
 
       
 
        public class Prompt : Form
        {
            private static TextBox textBox;
            private static Button okButton;
 
            public static string ShowDialog(string text, string caption, string defaultTxt = "")
            {
                Form prompt = new Form()
                {
                    Width = 200,
                    Height = 150,
                    FormBorderStyle = FormBorderStyle.FixedDialog,
                    Text = caption,
                    StartPosition = FormStartPosition.CenterScreen
                };
 
                Label textLabel = new Label() { Left = 20, Top = 20, Text = text };
                textBox = new TextBox() { Left = 20, Top = 50, Width = 150 };
                textBox.Text = defaultTxt;
                okButton = new Button() { Text = "确定", Left = 75, Width = 75, Top = 80 };
                okButton.Click += (sender, e) => { prompt.Close(); };
 
                prompt.Controls.Add(textBox);
                prompt.Controls.Add(textLabel);
                prompt.Controls.Add(okButton);
                prompt.ShowDialog();
 
                return textBox.Text;
            }
        }
        #endregion
    }
}