轮胎外观检测添加思谋语义分割模型检测工具
C3204
2026-04-02 3c837a3be1548e296d6ed1afb32ebe418b69db25
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
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Xml.Linq;
 
namespace LB_VisionFlowNode
{
    public class FlowPanel : Panel, IMessageFilter
    {
        #region 私有变量
        private PanelMode PanelMode = PanelMode.Normal;
 
        private Point mousePosition;
        private Point mouseRightStartLocation;
        private Point mouseLeftStartLocation;
        private Point dragStartPoint;
 
        private int connectStartNodeBranchIndex = -1;
        private FlowNode connectStartNode = null;
 
        private FlowNode selectedNode = null;
        private FlowConnection selectedConnection = null;
        private int selectedBranchIndex = -1;
 
        /// <summary>
        /// nodes的索引为节点名称
        /// </summary>
        private ConcurrentDictionary<string, FlowNode> nodes
            = new ConcurrentDictionary<string, FlowNode>();
 
        public ConcurrentDictionary<string, FlowNode> GetAllNodes() { return nodes; }
 
        /// <summary>
        /// connections的索引为起点节点名称(分支节点会增加{-Branch connectStartNodeBranchIndex})
        /// </summary>
        private ConcurrentDictionary<string, FlowConnection> connections
            = new ConcurrentDictionary<string, FlowConnection>();
 
        private ContextMenuStrip rContextMenu = null;
 
        private bool messageFilterInstalled = false;
 
        #endregion
 
        #region 外部调用事件
        /// <summary>
        /// 新增节点(name,class)
        /// </summary>
        public Action<string, string> AddNodeAction;
 
        /// <summary>
        /// 复制节点(name_copy,name_new,class)
        /// </summary>
        public Action<string, string, string> CopyNodeAction;
 
        /// <summary>
        /// 新增分支
        /// </summary>
        public Action<string> AddBranchAction;
 
        /// <summary>
        /// 重命名节点
        /// </summary>
        public Action<string, string> RenameNodeAction;
 
        /// <summary>
        /// 删除节点
        /// </summary>
        public Action<string> DeleteNodeAction;
 
        /// <summary>
        /// 删除节点
        /// </summary>
        public Action<string> DeleteBranchAction;
 
        /// <summary>
        /// 编辑节点
        /// </summary>
        public Action<string> EditNodeAction;
 
        /// <summary>
        /// 输入输出节点
        /// </summary>
        public Action<string> InAndOutNodeAction;
        #endregion
 
        public FlowPanel()
        {
            // 启用双缓冲和自定义绘制
            this.SetStyle(ControlStyles.AllPaintingInWmPaint |
                            ControlStyles.UserPaint |
                            ControlStyles.OptimizedDoubleBuffer, true);
 
            this.SetStyle(ControlStyles.ResizeRedraw, true);
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.SetStyle(ControlStyles.Selectable, false); // 如果不需要焦点
 
            this.UpdateStyles();
 
            this.BackColor = Color.Snow;
            this.Font = new Font("宋体", 9F);
            this.Paint += OnPaint;
            this.MouseDoubleClick += OnMouseDoubleClick;
            this.MouseDown += OnMouseDown;
            this.MouseMove += OnMouseMove;
            this.MouseUp += OnMouseUp;
 
            this.GotFocus += (s, e) => InstallMessageFilter();
            this.LostFocus += (s, e) => RemoveMessageFilter();
            this.MouseDown += (s, e) => this.Focus();
 
            rContextMenu = new ContextMenuStrip();
            this.ContextMenuStrip = rContextMenu;
 
            this.AutoScroll = false; // 禁用自动滚动
        }
 
        public readonly IFlowContext Context = null;
 
        public FlowPanel(IFlowContext context) : this()
        {
            this.Context = context;
        }
 
        // 定义委托类型
        private delegate void NodeHandler(FlowNode node);
 
        // 使用委托字典
        private Dictionary<string, NodeHandler> _nodeHandlers = new Dictionary<string, NodeHandler>();
 
        private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
 
        string NodesMsg = string.Empty;
 
        private async Task<bool> ExecuteFlowAsync(FlowNode startNode, ExecutionContext ExecutionContext)
        {
            string strRunTime = $"运行时间记录\r\n";
            // 假设 nameWidth 是动态计算的列宽(比如 20)
            int nameWidth = 30; //步骤名称小于20个列宽
            var formatString = "{0,-" + nameWidth + "}{1,-10}";
            try
            {
                var currentNode = startNode;
                string nextNodeName = string.Empty;
                DateTime StartTime = DateTime.Now;
                while (currentNode != null && !_cancellationTokenSource.IsCancellationRequested)
                {
                    await ExecuteNodeAsync(currentNode, ExecutionContext);
 
                    // 防止死循环,运行时间超过60秒则强制终止
                    if ((DateTime.Now - StartTime).TotalSeconds > 10)
                    {
                        _cancellationTokenSource.Cancel();
                        NodesMsg = $"执行所有节点超过10s";
                        return false;
                    }
 
                    // 执行完当前节点后交换到下一个节点运行
                    switch (currentNode.NodeType)
                    {
                        case NodeType.End:
                            return GetResult(ExecutionContext);
                        case NodeType.Switch:
                        case NodeType.MultiBranch:
                            if (currentNode.BranchNodes.ContainsKey($"{currentNode.Text}-Branch{currentNode.BranchIndex}"))
                            {
                                nextNodeName = currentNode.BranchNodes[$"{currentNode.Text}-Branch{currentNode.BranchIndex}"];
 
                                if (nextNodeName == null || !nodes.ContainsKey(nextNodeName))
                                {
                                    return GetResult(ExecutionContext);
                                }
                                else
                                    currentNode = nodes[nextNodeName];
                            }
                            else
                            {
                                return GetResult(ExecutionContext);
                            }
                            break;
                        case NodeType.Parallel:
                            // 并行执行多分支(直至当前branch都走到了Join汇聚分支节点(等待所有分支完成))
                            currentNode = await ExecuteParallelBranches(currentNode, ExecutionContext);
                            break;
                        case NodeType.Join:
                        default:
                            if (currentNode.BranchNodes.ContainsKey($"{currentNode.Text}-Branch0"))
                                nextNodeName = currentNode.BranchNodes[$"{currentNode.Text}-Branch0"];
                            else
                                return GetResult(ExecutionContext);
 
                            if (nextNodeName == null || !nodes.ContainsKey(nextNodeName))
                                return GetResult(ExecutionContext);
                            else
                                currentNode = nodes[nextNodeName];
                            break;
                    }
                }
 
                return GetResult(ExecutionContext);
            }
            catch (Exception ex) { NodesMsg = $"执行流程发生意外,{ex.Message}【{ex.StackTrace}】"; return false; }
        }
 
        private async Task<FlowNode> ExecuteParallelBranches(FlowNode ParallelNode, ExecutionContext ExecutionContext)
        {
            try
            {
                var currentNode = ParallelNode;
                string nextNodeName = string.Empty;
                DateTime StartTime = DateTime.Now;
                while (currentNode != null && !_cancellationTokenSource.IsCancellationRequested)
                {
                    // 防止死循环,运行时间超过5秒则强制终止
                    if ((DateTime.Now - StartTime).TotalSeconds > 5)
                    {
                        _cancellationTokenSource.Cancel();
                        NodesMsg = $"{currentNode.Text},并行分支运行超过5s";
                        return null;
                    }
 
                    // 执行完当前节点后交换到下一个节点运行
                    switch (currentNode.NodeType)
                    {
                        case NodeType.End:
                            return null;
                        case NodeType.Switch:
                        case NodeType.MultiBranch:
                            await ExecuteNodeAsync(currentNode, ExecutionContext);
                            if (currentNode.BranchNodes.ContainsKey($"{currentNode.Text}-Branch{currentNode.BranchIndex}"))
                            {
                                nextNodeName = currentNode.BranchNodes[$"{currentNode.Text}-Branch{currentNode.BranchIndex}"];
 
                                if (nextNodeName == null || !nodes.ContainsKey(nextNodeName))
                                    return null;
                                else
                                    currentNode = nodes[nextNodeName];
                            }
                            else
                                return null;
                            break;
                        case NodeType.Parallel:
                            // 并行执行多分支(直至当前branch都走到了Join汇聚分支节点(等待所有分支完成))
                            var parallelTasks = new List<Task<FlowNode>>();
 
                            foreach (var branch in currentNode.BranchNodes)
                            {
                                if (!nodes.ContainsKey(branch.Value))
                                    return null;
                                else
                                {
                                    parallelTasks.Add(Task.Run(async () =>
                                    {
                                        return await ExecuteParallelBranches(nodes[branch.Value], ExecutionContext); ;
                                    }));
                                }
                            }
 
                            // 等待所有并行任务完成或超时
                            var timeoutTask = Task.Delay(currentNode.TimeoutMilliseconds, _cancellationTokenSource.Token);
                            var completedTask = await Task.WhenAny(Task.WhenAll(parallelTasks), timeoutTask);
 
                            if (completedTask == timeoutTask)
                            {
                                NodesMsg = $"并行执行超时:{currentNode.Text}";
                                return null;
                            }
 
                            var JoinNodes = await Task.WhenAll(parallelTasks);
 
                            // 找到JoinNodes第一个不为null的节点作为下一个节点
                            return JoinNodes.FirstOrDefault(node => node != null);
                        case NodeType.Join:
                            await ExecuteNodeAsync(currentNode, ExecutionContext);
                            nextNodeName = currentNode.BranchNodes[$"{currentNode.Text}-Branch0"];
 
                            if (nextNodeName == null || !nodes.ContainsKey(nextNodeName))
                                return null;
                            else
                                return nodes[nextNodeName];
                        default:
                            await ExecuteNodeAsync(currentNode, ExecutionContext);
                            nextNodeName = currentNode.BranchNodes[$"{currentNode.Text}-Branch0"];
 
                            if (nextNodeName == null || !nodes.ContainsKey(nextNodeName))
                                return null;
                            else
                                currentNode = nodes[nextNodeName];
                            break;
                    }
                }
 
                return null;
            }
            catch { return null; }
        }
 
        private bool GetResult(ExecutionContext ExecutionContext)
        {
            if (ExecutionContext.BranchResults.Values.Contains(false))
                return false;
            else
                return true;
        }
 
        private async Task ExecuteNodeAsync(FlowNode currentNode, ExecutionContext context)
        {
            if (currentNode == null) return;
 
            // 执行当前节点
            context.CurrentconnectStartNodeBranchIndex = currentNode.BranchIndex;
            context.CurrentBranchName = $"{currentNode.Text}-Branch{currentNode.BranchIndex}";
            currentNode.RunState = RunState.Running;
 
            bool result = Context.ExecuteNode(currentNode);
#if DEBUG
            //Debug.WriteLine($"执行节点[{currentNode.Text}],结果为{result}");
#endif
            context.BranchResults.TryAdd(context.CurrentBranchName, currentNode.Result);
            currentNode.Result = result;
 
            currentNode.RunState = result ? RunState.Pass : RunState.Error;
        }
 
        public bool Run(out string msg)
        {
            NodesMsg = string.Empty;
 
            try
            {
                nodes.Values.AsParallel().ForAll(node => node.RunState = RunState.Wait);
                //Parallel.ForEach(nodes.Values, node =>
                //{
                //    node.RunState = RunState.Wait;
                //});
            }
            catch { }
 
            if (nodes == null || nodes.Count <= 0 || Context == null)
            {
                msg = "未配置节点或上下文,无法运行";
                return false;
            }
 
            var beginNodes = nodes.AsParallel()
                     .Where(n => n.Value.Text == "开始")
                     .ToList();
 
            if (beginNodes.Count > 0)
            {
                _cancellationTokenSource.Cancel();
                _cancellationTokenSource = new CancellationTokenSource();
                bool result = Task.Run(() =>
                    ExecuteFlowAsync(beginNodes[0].Value, new ExecutionContext())
                ).Result;
 
                if (result)
                    msg = string.Empty;
                else
                    msg = NodesMsg;
                return result;
            }
 
            msg = "未找到开始节点";
            return false;
        }
 
        private void AddNode(FlowNode node)
        {
            // 名称重复则添加(副本)
            string nodeName = node.Text;
 
            while (nodes.Any(n => n.Value.Text == nodeName))
            {
                nodeName += "(Copy)";
            }
 
            node.Text = nodeName;
            if (this.nodes.TryAdd(nodeName, node))
                AddNodeAction?.Invoke(nodeName, node.Description);
 
            this.Invalidate();
        }
 
        public void ClearNodes()
        {
            this.nodes.Clear();
            this.connections.Clear();
            this.Invalidate();
        }
 
        string filePath = string.Empty;
 
        public bool Load(string filePath)
        {
            try
            {
                PanelMode = PanelMode.Run;
 
                nodes.Clear();
                connections.Clear();
 
                string json = File.ReadAllText(filePath);
                // 反序列化
                var (deserializedNodes, deserializedConnections) = FlowSerializer.Deserialize(json);
                nodes = deserializedNodes;
                connections = deserializedConnections;
 
                //nodes.Values.AsParallel().ForAll(node => node.RunState = RunState.Wait);
                Parallel.ForEach(nodes.Values, node =>
                {
                    node.RunState = RunState.Wait;
                });
 
                PanelMode = PanelMode.Normal;
                this.filePath = filePath;
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载失败: {ex.Message}", "异常");
                return false;
            }
        }
 
        public bool Save(string filePath)
        {
            try
            {
                if (string.IsNullOrEmpty(filePath))
                    return true;
 
                PanelMode = PanelMode.Run;
 
                string json = FlowSerializer.Serialize(nodes, connections);
                File.WriteAllText(filePath, json);
 
                PanelMode = PanelMode.Normal;
                return true;
            }
            catch { return false; }
        }
 
        #region 私有函数
 
        #region 检测点击是否在节点上
        private FlowNode GetNodeAt(Point location)
        {
            foreach (var node in nodes)
            {
                if (node.Value.GetBounds().Contains(location))
                    return node.Value;
            }
            return null;
        }
        #endregion
 
        #region 检测点击是否在连接线上
        public FlowConnection GetConnectionAt(Point mousePoint)
        {
            foreach (var connection in connections)
            {
                if (IsPointNearConnection(mousePoint, connection.Value))
                    return connection.Value;
            }
            return null;
        }
 
        private bool IsPointNearConnection(Point point, FlowConnection connection, int tolerance = 3)
        {
            if (connection == null || connection.StartNode == null || connection.EndNode == null)
                return false;
 
            Point[] points = GetConnectionAllPoints(connection);
 
            // 检查每个线段
            for (int i = 0; i < points.Length - 1; i++)
            {
                if (IsPointNearLine(point, points[i], points[i + 1]))
                    return true;
            }
            return false;
        }
 
        // 判断点是否靠近线段
        private bool IsPointNearLine(Point point, Point lineStart, Point lineEnd, int tolerance = 3)
        {
            // 计算点到线段的距离
            double distance = PointToLineDistance(point, lineStart, lineEnd);
            return distance <= tolerance;
        }
 
        // 计算点到线段的距离
        private double PointToLineDistance(Point point, Point lineStart, Point lineEnd)
        {
            double lineLengthSquared = Math.Pow(lineEnd.X - lineStart.X, 2) + Math.Pow(lineEnd.Y - lineStart.Y, 2);
 
            if (lineLengthSquared == 0) // 线段长度为0
                return Distance(point, lineStart);
 
            // 计算投影比例
            double t = Math.Max(0, Math.Min(1,
                ((point.X - lineStart.X) * (lineEnd.X - lineStart.X) +
                 (point.Y - lineStart.Y) * (lineEnd.Y - lineStart.Y)) / lineLengthSquared));
 
            // 计算投影点
            Point projection = new Point(
                (int)(lineStart.X + t * (lineEnd.X - lineStart.X)),
                (int)(lineStart.Y + t * (lineEnd.Y - lineStart.Y))
            );
 
            // 返回点到投影点的距离
            return Distance(point, projection);
        }
        #endregion
 
        #region 检测点击是否在分支上
 
        private int GetBranchAt(Point location)
        {
            foreach (var connection in connections)
            {
                if (IsPointNearConnection(location, connection.Value))
                    return connection.Value.BranchIndex;
            }
            return -1;
        }
 
        private FlowNode OnNodeBranch(Point location, out int index)
        {
            index = -1;
            foreach (var node in nodes.Values)
            {
                index = GetPointIndexNearLocation(location, node.GetBranchPoints());
                if (index != -1)
                    return node;
            }
            return null;
        }
 
        /// <summary>
        /// 检测鼠标位置是否在点列表中的任意点附近,并返回该点的索引
        /// </summary>
        /// <param name="mousePoint">鼠标位置</param>
        /// <param name="points">点列表</param>
        /// <param name="tolerance">容差范围(像素)</param>
        /// <returns>找到的点的索引,如果没找到返回-1</returns>
        public int GetPointIndexNearLocation(Point mousePoint, List<Point> points, float tolerance = 8f)
        {
            if (points == null || points.Count == 0)
                return -1;
 
            for (int i = 0; i < points.Count; i++)
            {
                if (IsPointNearPoint(mousePoint, points[i], tolerance))
                    return i;
            }
 
            return -1;
        }
 
        /// <summary>
        /// 判断两个点是否在容差范围内接近
        /// </summary>
        private bool IsPointNearPoint(Point point1, Point point2, float tolerance)
        {
            float distance = Distance(point1, point2);
            return distance <= tolerance;
        }
 
        /// <summary>
        /// 计算两点之间的距离
        /// </summary>
        private float Distance(Point p1, Point p2)
        {
            return (float)Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));
        }
        #endregion
 
        #region 绘制相关
        /// <summary>
        /// 绘制节点
        /// </summary>
        /// <param name="g"></param>
        /// <param name="node"></param>
        private void DrawNode(Graphics g, FlowNode node)
        {
            // 绘制节点背景
            Color background = node.GetColor();
            using (Brush brush = new SolidBrush(background))
            {
                switch (node.NodeType)
                {
                    case NodeType.Switch:
                    case NodeType.MultiBranch:
                        g.FillPolygon(brush, FlowNode.GetDiamondPoints(node.GetBounds()));
                        break;
                    case NodeType.Begin:
                    case NodeType.End:
                    case NodeType.Parallel:
                    case NodeType.Join:
                        g.FillEllipse(brush, node.GetBounds());
                        break;
                    default:
                        g.FillRectangle(brush, node.GetBounds());
                        break;
                }
            }
 
            // 绘制边框
            if (node == selectedNode)
            {
                Color borderColor = Color.Coral;
                int borderWidth = 3;
 
                using (Pen pen = new Pen(borderColor, borderWidth))
                {
                    switch (node.NodeType)
                    {
                        case NodeType.Switch:
                        case NodeType.MultiBranch:
                            g.DrawPolygon(pen, FlowNode.GetDiamondPoints(node.GetBounds()));
                            break;
                        case NodeType.Begin:
                        case NodeType.End:
                        case NodeType.Parallel:
                        case NodeType.Join:
                            g.DrawEllipse(pen, node.GetBounds());
                            break;
                        default:
                            g.DrawRectangle(pen, node.GetBounds());
                            break;
                    }
                }
            }
 
            // 绘制文本
            using (StringFormat sf = new StringFormat())
            {
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;
                using (Brush textBrush = new SolidBrush(Color.Black))
                {
                    g.DrawString(node.Text, this.Font, textBrush, node.GetBounds(), sf);
                }
            }
 
            // 绘制连接点
            using (Brush brush = new SolidBrush(Color.Coral))
            {
                foreach (var point in node.GetConnectionPoints())
                    g.FillEllipse(brush, point.X - 2, point.Y - 2, 4, 4);
            }
        }
 
        /// <summary>
        /// 绘制连接线
        /// </summary>
        /// <param name="g"></param>
        /// <param name="connection"></param>
        private void DrawConnection(Graphics g, FlowConnection connection, Pen pen)
        {
            if (connection == null || connection.StartNode == null || connection.EndNode == null)
                return;
 
            Point[] allPoints = GetConnectionAllPoints(connection);
 
            if (allPoints.Length > 2)
            {
                // 绘制折线
                g.DrawLines(pen, allPoints);
                // 在最后一段线段上绘制箭头
                DrawArrow(g, pen, allPoints[allPoints.Length - 2], allPoints[allPoints.Length - 1]);
            }
            else if (allPoints.Length == 2)
            {
                // 从上往下直接绘制直线
                g.DrawLine(pen, allPoints[0], allPoints[1]);
                DrawArrow(g, pen, allPoints[0], allPoints[1]);
            }
            return;
        }
 
        /// <summary>
        /// 获取连接线的所有点
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        Point[] GetConnectionAllPoints(FlowConnection connection)
        {
            if (connection.StartNode == null || connection.EndNode == null)
                return new Point[] { };
 
            Point startPoint = connection.StartNode.BtmPoint;
            Point endPoint = connection.EndNode.TopPoint;
 
            switch (connection.StartNode.NodeType)
            {
                case NodeType.Switch:
                    if (connection.BranchIndex == 0)
                    {
                        // connectStartNodeBranchIndex为StartNode的左边
                        startPoint = connection.StartNode.LeftPoint;
                        if (endPoint.X > startPoint.X || startPoint.Y > endPoint.Y)
                        {
                            return new Point[]
                            {
                                startPoint,
                                new Point(startPoint.X - 10, startPoint.Y),
                                new Point(startPoint.X - 10, endPoint.Y - 10),
                                new Point(endPoint.X, endPoint.Y - 10) ,
                                endPoint
                            };
                        }
                        else
                        {
                            return new Point[]
                            {
                                startPoint,
                                new Point(endPoint.X, startPoint.Y),
                                endPoint
                            };
                        }
                    }
                    else if (connection.BranchIndex == 1)
                    {
                        // connectStartNodeBranchIndex为StartNode的右边
                        startPoint = connection.StartNode.RightPoint;
                        if (endPoint.X < startPoint.X || startPoint.Y > endPoint.Y)
                        {
                            return new Point[]
                            {
                                startPoint,
                                new Point(startPoint.X + 10, startPoint.Y),
                                new Point(startPoint.X + 10, endPoint.Y - 10),
                                new Point(endPoint.X, endPoint.Y - 10) ,
                                endPoint
                            };
                        }
                        else
                        {
                            return new Point[]
                            {
                                startPoint,
                                new Point(endPoint.X, startPoint.Y),
                                endPoint
                            };
                        }
                    }
                    break;
                case NodeType.MultiBranch:
                case NodeType.Parallel:
                    // 多分支节点:使用分支索引获取连接点
                    if (connection.BranchIndex >= 0 && connection.BranchIndex < connection.StartNode.BranchNodes.Count)
                        return CalculateMultiBranchConnectionPath(
                            connection.StartNode.GetBranchPoints(connection.BranchIndex)
                            , endPoint, connection.StartNode, connection.EndNode);
                    break;
                default:
                    startPoint = connection.StartNode.BtmPoint;
                    return CalculateMultiBranchConnectionPath(startPoint, endPoint, connection.StartNode, connection.EndNode);
            }
            return new Point[] { };
        }
 
        /// <summary>
        /// 上下连接的节点路径计算
        /// </summary>
        /// <param name="startPoint"></param>
        /// <param name="endPoint"></param>
        /// <param name="connectStartNodeBranchIndex"></param>
        /// <returns></returns>
        private Point[] CalculateMultiBranchConnectionPath(Point startPoint, Point endPoint
            , FlowNode StartNode, FlowNode EndNode)
        {
            if (startPoint.Y > endPoint.Y)
            {
                if (startPoint.X > endPoint.X)
                    return new Point[]
                    {
                        startPoint,
                        new Point(startPoint.X, startPoint.Y + 10),
                        new Point(startPoint.X - StartNode.Width, startPoint.Y + 10),
                        new Point(startPoint.X - StartNode.Width, endPoint.Y - 10),
                        new Point(endPoint.X, endPoint.Y - 10),
                        endPoint
                    };
                else
                    return new Point[]
                    {
                        startPoint,
                        new Point(startPoint.X, startPoint.Y + 10),
                        new Point(startPoint.X + StartNode.Width, startPoint.Y + 10),
                        new Point(startPoint.X + StartNode.Width, endPoint.Y - 10),
                        new Point(endPoint.X, endPoint.Y - 10),
                        endPoint
                    };
            }
            else if (startPoint.X != endPoint.X)
            {
                return new Point[]
                {
                    startPoint,
                    new Point(startPoint.X, (startPoint.Y + endPoint.Y) / 2),
                    new Point(endPoint.X, (startPoint.Y + endPoint.Y) / 2),
                    endPoint
                };
            }
            else
            {
                return new Point[]
                {
                    startPoint,
                    endPoint
                };
            }
        }
 
        /// <summary>
        /// 绘制箭头
        /// </summary>
        /// <param name="g"></param>
        /// <param name="pen"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        private void DrawArrow(Graphics g, Pen pen, Point start, Point end)
        {
            // 计算箭头方向
            double dx = end.X - start.X;
            double dy = end.Y - start.Y;
            double angle = Math.Atan2(dy, dx);
 
            int arrowLength = 8;  // 增加箭头长度
            double arrowAngle = Math.PI / 6;  // 30度角
 
            // 计算箭头的两个端点
            Point arrowPoint1 = new Point(
                (int)(end.X - arrowLength * Math.Cos(angle - arrowAngle)),
                (int)(end.Y - arrowLength * Math.Sin(angle - arrowAngle)));
 
            Point arrowPoint2 = new Point(
              (int)(end.X - arrowLength * Math.Cos(angle + arrowAngle)),
              (int)(end.Y - arrowLength * Math.Sin(angle + arrowAngle)));
 
            // 绘制箭头
            using (Pen arrowPen = new Pen(pen.Color, pen.Width))
            {
                g.DrawLine(arrowPen, end, arrowPoint1);
                g.DrawLine(arrowPen, end, arrowPoint2);
 
                // 可选:填充箭头(实心箭头)
                Point[] arrowPoints = { end, arrowPoint1, arrowPoint2 };
                using (Brush arrowBrush = new SolidBrush(pen.Color))
                {
                    g.FillPolygon(arrowBrush, arrowPoints);
                }
            }
        }
        #endregion
 
        #region 键盘相关
        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
 
            switch (e.KeyCode)
            {
                case Keys.Delete:
                    if (selectedNode != null)
                    {
                        RemoveNode(selectedNode);
                        selectedNode = null;
                        e.Handled = true;
                        return;
                    }
 
                    if (selectedConnection != null)
                    {
                        RemoveConnection(selectedConnection, selectedBranchIndex);
                        selectedConnection = null;
                        e.Handled = true;
                        return;
                    }
                    break;
                case Keys.Escape:
                    selectedConnection = null;
                    selectedNode = null;
                    Invalidate();
                    e.Handled = true;
                    return;
            }
 
            Save(filePath);
            return;
        }
 
        private void InstallMessageFilter()
        {
            if (!messageFilterInstalled)
            {
                Application.AddMessageFilter(this);
                messageFilterInstalled = true;
            }
        }
 
        private void RemoveMessageFilter()
        {
            if (messageFilterInstalled)
            {
                Application.RemoveMessageFilter(this);
                messageFilterInstalled = false;
            }
        }
 
        public bool PreFilterMessage(ref Message m)
        {
            const int WM_KEYDOWN = 0x100;
            const int WM_KEYUP = 0x101;
 
            // 只在Panel有焦点时处理消息
            if (this.Focused && (m.Msg == WM_KEYDOWN || m.Msg == WM_KEYUP))
            {
                Keys keyData = (Keys)(int)m.WParam;
 
                if (m.Msg == WM_KEYDOWN)
                {
                    var e = new KeyEventArgs(keyData);
                    OnKeyDown(e);
                    return e.Handled;
                }
            }
 
            return false;
        }
        #endregion
 
        #region 内部事件(重绘/鼠标)
        private void OnPaint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
 
            // 绘制节点
            foreach (var node in nodes.Values)
                DrawNode(g, node);
 
            // 绘制连接线
            foreach (var connection in connections.Values)
            {
                if (connection == selectedConnection)
                    DrawConnection(g, connection, new Pen(Color.Coral, connection.LineWidth));
                else
                    DrawConnection(g, connection, new Pen(connection.LineColor, connection.LineWidth));
            }
 
            // 绘制临时连接线
            if (this.PanelMode == PanelMode.CreatingConnection && connectStartNode != null)
            {
                using (Pen tempPen = new Pen(Color.Coral, 2))
                {
                    tempPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
 
                    // 虚拟节点用于绘制连接线终点
                    FlowNode virtualEndNode = new FlowNode(NodeType.Normal
                                , new Point(mousePosition.X, mousePosition.Y + connectStartNode.Height / 2)
                                , "virtualNode", "virtualNode", connectStartNode.Width, connectStartNode.Height);
                    DrawConnection(g, new FlowConnection(connectStartNode, virtualEndNode, connectStartNodeBranchIndex), tempPen);
                }
            }
        }
 
        private void OnMouseDoubleClick(object sender, MouseEventArgs e)
        {
            switch (e.Button)
            {
                case MouseButtons.Left:
                    {
                        FlowNode clickedNode = GetNodeAt(e.Location);
 
                        if (clickedNode != null)
                        {
                            try
                            {
                                EditNodeAction?.Invoke(clickedNode.Text);
                            }
                            catch { }
                        }
                    }
                    break;
                case MouseButtons.Right:
                default:
                    break;
            }
        }
 
        private void OnMouseDown(object sender, MouseEventArgs e)
        {
            PanelMode = PanelMode.Normal;
            selectedNode = GetNodeAt(e.Location);
            selectedBranchIndex = GetBranchAt(e.Location);
            switch (e.Button)
            {
                case MouseButtons.Left:
                    FlowNode isConnectingNode = OnNodeBranch(e.Location, out connectStartNodeBranchIndex);
                    selectedConnection = GetConnectionAt(e.Location);
                    mouseLeftStartLocation = e.Location;
                    // 点击在边界上并未点击在节点上,进入判断是否进入连接线模式
                    if (isConnectingNode != null && selectedNode == null)
                    {
                        // 只能从连接点开始连线 没有选中节点 选中了连接点
                        if (connectStartNodeBranchIndex < 0)
                            return;
 
                        PanelMode = PanelMode.CreatingConnection;
                        connectStartNode = isConnectingNode;
                        this.Invalidate();
                        return;
                    }
 
                    // 点击在节点上,预备进入拖动节点模式
                    if (selectedNode != null)
                    {
                        this.PanelMode = PanelMode.DraggingNode;
                        dragStartPoint = e.Location;
                        return;
                    }
                    break;
                case MouseButtons.Right:
                    rContextMenu.Items.Clear();
                    mouseRightStartLocation = e.Location;
                    if (selectedNode == null && Context != null)
                    {
                        // 没有选中节点时,显示动态节点菜单
                        var categorizedItems = Context.GetCategorizedMenuItems(ContextMenuItem_Click);
 
                        foreach (var category in categorizedItems)
                        {
                            // 创建类别下拉菜单
                            var categoryMenu = new ToolStripMenuItem(category.Key);
 
                            // 添加该类别的所有菜单项
                            foreach (var menuItem in category.Value)
                            {
                                categoryMenu.DropDownItems.Add(menuItem);
                            }
 
                            rContextMenu.Items.Add(categoryMenu);
                        }
                    }
                    else if (selectedNode != null)
                    {
                        if (selectedNode.NodeType == NodeType.Begin
                            || selectedNode.NodeType == NodeType.End)
                        {
                            rContextMenu.Items.Clear();
                            return;
                        }
                        var renameItem = new ToolStripMenuItem("编辑");
                        renameItem.Click += (s, ev) => EditInAndOutNode();
                        rContextMenu.Items.Add(renameItem);
 
                        var deleteItem = new ToolStripMenuItem("重命名");
                        deleteItem.Click += (s, ev) => RenameNode();
                        rContextMenu.Items.Add(deleteItem);
 
                        var copyItem = new ToolStripMenuItem("复制");
                        copyItem.Click += (s, ev) => CopyNode();
                        rContextMenu.Items.Add(copyItem);
 
                        if (selectedNode.NodeType == NodeType.Normal
                            || selectedNode.NodeType == NodeType.Switch
                            || selectedNode.NodeType == NodeType.MultiBranch)
                        {
                            var breakItem = new ToolStripMenuItem("禁用");
                            breakItem.Checked = selectedNode.Break;
                            breakItem.Click += (s, ev) => BreakNode();
                            rContextMenu.Items.Add(breakItem);
                        }
 
                        if (selectedNode.NodeType == NodeType.Parallel
                            || selectedNode.NodeType == NodeType.MultiBranch)
                        {
                            var addBranchItem = new ToolStripMenuItem("添加分支");
                            addBranchItem.Click += (s, ev) => AddBranch();
                            rContextMenu.Items.Add(addBranchItem);
 
                            var removeBranchItem = new ToolStripMenuItem("移除分支");
                            removeBranchItem.Click += (s, ev) => RemoveBranch();
                            rContextMenu.Items.Add(removeBranchItem);
                        }
                    }
                    break;
                default:
                    selectedNode = null;
                    break;
            }
            this.Invalidate();
        }
 
        private void OnMouseUp(object sender, MouseEventArgs e)
        {
            try
            {
                switch (e.Button)
                {
                    case MouseButtons.Left:
                        switch (this.PanelMode)
                        {
                            case PanelMode.CreatingConnection:
                                FlowNode connectEndNode = GetNodeAt(e.Location);
 
                                if (connectEndNode == null)
                                {
                                    connectStartNode = null;
                                    connectStartNodeBranchIndex = -1;
                                    return;
                                }
 
                                // 完成连线操作后需要判断该连接线所连接的起始节点和终点节点是否已经被连接
                                foreach (var conn in connections.Values)
                                {
                                    // 已经存在该连接线
                                    if (conn.StartNode == connectStartNode
                                        && conn.EndNode == connectEndNode)
                                    {
                                        connectStartNode = null;
                                        connectStartNodeBranchIndex = -1;
                                        return;
                                    }
 
                                    // 连接线的起点已经连接了其他节点,则断开之前的连接
                                    switch (conn.StartNode.NodeType)
                                    {
                                        // 分支节点逻辑单独处理
                                        case NodeType.Switch:
                                            if (conn.StartNode == connectStartNode && connectStartNodeBranchIndex >= 0
                                                && conn.BranchIndex == connectStartNodeBranchIndex)
                                            {
                                                RemoveConnection(conn, connectStartNodeBranchIndex);
                                                break;
                                            }
                                            break;
                                        // 多分支节点逻辑单独处理
                                        case NodeType.MultiBranch:
                                        case NodeType.Parallel:
                                            if (conn.StartNode == connectStartNode && connectStartNodeBranchIndex >= 0
                                                && conn.BranchIndex == connectStartNodeBranchIndex)
                                            {
                                                // 断开之前的连接
                                                RemoveConnection(conn, connectStartNodeBranchIndex);
                                                break;
                                            }
                                            break;
                                        default:
                                            if (conn.StartNode == connectStartNode)
                                            {
                                                // 断开之前的连接
                                                RemoveConnection(conn, connectStartNodeBranchIndex);
                                                break;
                                            }
                                            break;
                                    }
                                }
 
                                // 确保连接的起点和终点都不为空且不相同,创建连接线
                                if (connectStartNode != null
                                    //&& connectEndNode != null
                                    && connectEndNode != connectStartNode && connectStartNodeBranchIndex >= 0)
                                    ConnectAsBranch(connectStartNode, connectEndNode, connectStartNodeBranchIndex);
 
                                connectStartNode = null;
                                connectStartNodeBranchIndex = -1;
                                break;
                            case PanelMode.DraggingNode:
                                // 完成拖动操作后的逻辑
                                break;
                        }
                        break;
                    case MouseButtons.Right:
                    default:
                        break;
                }
            }
            catch { }
            finally
            {
                PanelMode = PanelMode.Normal;
                this.Invalidate();
                Save(filePath);
            }
 
        }
 
        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            mousePosition = e.Location;
            switch (this.PanelMode)
            {
                case PanelMode.CreatingConnection:
                    // 绘制临时连接线逻辑在paint
                    //this.Cursor = Cursors.Cross;
                    break;
                case PanelMode.DraggingNode:
                    // 绘制拖动节点逻辑在paint,当前只是修改被
                    int deltaX = e.X - dragStartPoint.X;
                    int deltaY = e.Y - dragStartPoint.Y;
                    if (selectedNode != null)
                    {
                        selectedNode.X += deltaX;
                        selectedNode.Y += deltaY;
                    }
                    dragStartPoint = e.Location;
                    this.Cursor = Cursors.Hand;
                    break;
                case PanelMode.Normal:
                    FlowNode isConnectingNode = OnNodeBranch(e.Location, out int index);
 
                    // 点击在边界上并未点击在节点上,进入判断是否进入连接线模式
                    if (isConnectingNode != null && selectedNode == null && index >= 0)
                        this.Cursor = Cursors.Cross;
                    else
                        this.Cursor = Cursors.Default;
                    break;
            }
            this.Invalidate();
        }
 
        private void ContextMenuItem_Click(object sender, EventArgs e)
        {
            if (sender is ToolStripMenuItem menuItem && menuItem.Tag is string description)
            {
                // 只能有一个开始节点
                if (description == "开始"
                    && nodes.Any(n => n.Value.Text == "开始"))
                    return;
 
                // 只能有一个结束节点
                if (description == "结束"
                    && nodes.Any(n => n.Value.Text == "结束"))
                    return;
 
                // 获取鼠标位置
                Point mousePoint = mouseRightStartLocation;
 
                // 名称重复则添加(副本)
                string nodeName = description;
                while (nodes.Any(n => n.Value.Text == nodeName))
                    nodeName += "(Copy)";
 
                FlowNode newNode = new FlowNode();
                switch (description)
                {
                    case "开始":
                        newNode = new FlowNode(NodeType.Begin, mousePoint, nodeName, description);
                        break;
                    case "结束":
                        newNode = new FlowNode(NodeType.End, mousePoint, nodeName, description);
                        break;
                    case "分支":
                        newNode = new FlowNode(NodeType.Switch, mousePoint, nodeName, description);
                        newNode.BranchNodes.TryAdd($"{newNode.Text}-Branch0", string.Empty);
                        break;
                    case "多分支":
                        newNode = new FlowNode(NodeType.MultiBranch, mousePoint, nodeName, description);
                        break;
                    case "并行分支开始":
                        newNode = new FlowNode(NodeType.Parallel, mousePoint, nodeName, description);
                        break;
                    case "并行分支结束":
                        newNode = new FlowNode(NodeType.Join, mousePoint, nodeName, description);
                        break;
                    default:
                        newNode = new FlowNode(NodeType.Normal, mousePoint, nodeName, description);
                        break;
                }
                //分支节点默认添加两个分支
                newNode.BranchNodes.TryAdd($"{newNode.Text}-Branch{newNode.BranchNodes.Count}", string.Empty);
 
                if (nodes.TryAdd(newNode.Text, newNode))
                {
                    AddNodeAction?.Invoke(newNode.Text, description);
                    Debug.WriteLine($"【{DateTime.Now:HH:mm:ss.fff}】创建了新节点: {description}");
                }
 
            }
            Save(filePath);
        }
        #endregion
 
        #region 其他函数
        private void CopyNode()
        {
            try
            {
                PanelMode = PanelMode.Run;
                if (selectedNode == null)
                    return;
 
                string description = selectedNode.Description;
                // 只能有一个开始节点
                if (description == "开始"
                    && nodes.Any(n => n.Value.Text == "开始"))
                    return;
 
                // 只能有一个结束节点
                if (description == "结束"
                    && nodes.Any(n => n.Value.Text == "结束"))
                    return;
 
                // 获取鼠标位置
                Point mousePoint = mouseRightStartLocation;
 
                // 名称重复则添加(副本)
                string nodeName = description;
                while (nodes.Any(n => n.Value.Text == nodeName))
                    nodeName += "(Copy)";
 
                FlowNode newNode = new FlowNode();
                switch (description)
                {
                    case "开始":
                        newNode = new FlowNode(NodeType.Begin, mousePoint, nodeName, description);
                        break;
                    case "结束":
                        newNode = new FlowNode(NodeType.End, mousePoint, nodeName, description);
                        break;
                    case "分支":
                        newNode = new FlowNode(NodeType.Switch, mousePoint, nodeName, description);
                        newNode.BranchNodes.TryAdd($"{newNode.Text}-Branch0", string.Empty);
                        break;
                    case "多分支":
                        newNode = new FlowNode(NodeType.MultiBranch, mousePoint, nodeName, description);
                        break;
                    case "并行分支开始":
                        newNode = new FlowNode(NodeType.Parallel, mousePoint, nodeName, description);
                        break;
                    case "并行分支结束":
                        newNode = new FlowNode(NodeType.Join, mousePoint, nodeName, description);
                        break;
                    default:
                        newNode = new FlowNode(NodeType.Normal, mousePoint, nodeName, description);
                        break;
                }
                //分支节点默认添加两个分支
                newNode.BranchNodes.TryAdd($"{newNode.Text}-Branch{newNode.BranchNodes.Count}", string.Empty);
 
                if (nodes.TryAdd(newNode.Text, newNode))
                {
                    CopyNodeAction?.Invoke(selectedNode.Text, newNode.Text, description);
                    Debug.WriteLine($"【{DateTime.Now:HH:mm:ss.fff}】复制了新节点: {description}");
                }
 
                Save(filePath);
            }
            catch { }
            finally { PanelMode = PanelMode.Normal; }
        }
 
        private void RemoveNode(FlowNode selectedNode)
        {
            try
            {
                foreach (var conn in connections)
                {
                    if (conn.Value == null)
                        continue;
 
                    if (conn.Value.StartNode == selectedNode || conn.Value.EndNode == selectedNode)
                    {
                        RemoveConnection(conn.Value, -1);
                        //connections.TryRemove(conn);
                        //break;
                    }
                }
 
                if (this.nodes.Remove(selectedNode.Text, out _))
                    DeleteNodeAction?.Invoke(selectedNode.Text);
 
                Save(filePath);
                this.Invalidate();
            }
            catch { }
        }
 
        private void EditInAndOutNode()
        {
            try
            {
                PanelMode = PanelMode.Run;
                if (selectedNode == null)
                    return;
                InAndOutNodeAction?.Invoke(selectedNode.Text);
            }
            catch { }
            finally { PanelMode = PanelMode.Normal; }
        }
 
        private void RenameNode()
        {
            try
            {
                PanelMode = PanelMode.Run;
                if (selectedNode == null)
                    return;
 
                RenameForm renameForm = new RenameForm(selectedNode.Text, true);
                renameForm.ShowDialog();
                if (renameForm.bRename)
                {
                    if (nodes.Any(n => n.Value.Text == renameForm.strNewName))
                    {
                        MessageBox.Show("已存在同名节点,请修改后重试!", "异常");
                        return;
                    }
 
                    nodes.TryRemove(renameForm.strOriName, out _);
                    selectedNode.Text = renameForm.strNewName;
                    nodes.TryAdd(selectedNode.Text, selectedNode);
 
                    if (connections.TryRemove(renameForm.strOriName, out FlowConnection conn)
                        && conn != null)
                        connections.TryAdd(selectedNode.Text, conn);
 
                    foreach (var node in nodes.Values)
                    {
                        foreach (var branch in node.BranchNodes)
                        {
                            if (branch.Key.StartsWith($"{renameForm.strOriName}-Branch"))
                            {
                                var newKey = branch.Key.Replace(renameForm.strOriName, renameForm.strNewName);
                                node.BranchNodes.TryRemove(branch.Key, out var value);
                                node.BranchNodes.TryAdd(newKey, value);
                            }
                            else if (branch.Value == renameForm.strOriName)
                            {
                                var newValue = branch.Value.Replace(renameForm.strOriName, renameForm.strNewName);
                                node.BranchNodes.TryRemove(branch.Key, out _);
                                node.BranchNodes.TryAdd(branch.Key, newValue);
                            }
                        }
                    }
                    this.Invalidate();
                    RenameNodeAction?.Invoke(renameForm.strOriName, renameForm.strNewName);
                }
            }
            catch { }
            finally { PanelMode = PanelMode.Normal; }
        }
 
        private void RemoveConnection(FlowConnection selectedConnection, int BranchIndex)
        {
            foreach (var conn in connections)
            {
                if (conn.Value == selectedConnection)
                {
                    connections.TryRemove(conn);
                    //selectedConnection.StartNode.BranchNodes
                    //    .TryRemove($"{selectedConnection.StartNode.Text}-Branch{BranchIndex}", out _);
 
                    if (selectedConnection.StartNode.BranchNodes.ContainsKey($"{selectedConnection.StartNode.Text}-Branch{selectedConnection.BranchIndex}"))
                        selectedConnection.StartNode.BranchNodes[$"{selectedConnection.StartNode.Text}-Branch{selectedConnection.BranchIndex}"] = null;
                    break;
                }
            }
            this.Invalidate();
        }
 
        public void ConnectAsBranch(FlowNode parentNode, FlowNode branchNode, int connectStartNodeBranchIndex)
        {
            //// 确保分支节点注册到主集合
            //RegisterNode(branchNode);
 
            // 更新分支引用
            string branchName = $"{parentNode.Text}-Branch{connectStartNodeBranchIndex}";
            if (parentNode != null && branchNode != null)
            {
                // 更新 BranchNodes 字典
                parentNode.BranchNodes.AddOrUpdate(branchName,
                    (branchNode.Text),
                    (key, existing) => (branchNode.Text));
            }
 
            // 创建连接线
            var connection = new FlowConnection(parentNode, branchNode, connectStartNodeBranchIndex);
 
            // 原来的连接线被替换为新的连接线
            if (connections.ContainsKey(branchName))
                connections[branchName] = connection;
            else
                connections.TryAdd(branchName, connection);
 
            // 原来的连接节点被替换为新的节点
            if (parentNode.BranchNodes.ContainsKey(branchName))
                parentNode.BranchNodes[branchName] = branchNode.Text;
            else
                parentNode.BranchNodes.TryAdd(branchName, branchNode.Text);
 
            Save(filePath);
        }
 
        private void BreakNode()
        {
            PanelMode = PanelMode.Run;
            if (selectedNode == null)
                return;
            try
            {
                selectedNode.Break = !selectedNode.Break;
            }
            catch { }
            finally { PanelMode = PanelMode.Normal; Save(filePath); }
        }
 
        private void AddBranch()
        {
            PanelMode = PanelMode.Run;
            if (selectedNode == null)
                return;
            try
            {
                selectedNode.BranchNodes.TryAdd($"{selectedNode.Text}-Branch{selectedNode.BranchNodes.Count}", string.Empty);
                AddBranchAction?.Invoke(selectedNode.Text);
            }
            catch { }
            finally { PanelMode = PanelMode.Normal; Save(filePath); }
        }
 
        private void RemoveBranch()
        {
            PanelMode = PanelMode.Run;
            if (selectedNode == null)
                return;
            try
            {
                int index = selectedNode.BranchNodes.Count - 1;
                selectedNode.BranchNodes.TryRemove($"{selectedNode.Text}-Branch{index}", out _);
                connections.TryRemove($"{selectedNode.Text}-Branch{index}", out _);
                DeleteBranchAction?.Invoke(selectedNode.Text);
            }
            catch { }
            finally { PanelMode = PanelMode.Normal; Save(filePath); }
        }
        #endregion
 
        #endregion
    }
 
    public class ExecutionContext
    {
        public string CurrentconnectStartNodeBranchIndex { get; set; } = "";
        public string CurrentBranchName { get; set; }
        public ConcurrentDictionary<string, bool> BranchResults { get; set; } = new ConcurrentDictionary<string, bool>();
 
        public ExecutionContext Clone()
        {
            return new ExecutionContext
            {
                CurrentconnectStartNodeBranchIndex = CurrentconnectStartNodeBranchIndex,
                CurrentBranchName = CurrentBranchName,
                BranchResults = new ConcurrentDictionary<string, bool>(BranchResults)
            };
        }
    }
}