프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / ID2PSN / PSN.cs @ abc4250b

이력 | 보기 | 이력해설 | 다운로드 (95.8 KB)

1
using System;
2
using System.Collections.Generic;
3
using System.Data;
4
using System.IO;
5
using System.Linq;
6
using System.Text;
7
using System.Threading.Tasks;
8
using ID2PSN.Properties;
9
using System.Text.RegularExpressions;
10
using System.Windows.Forms;
11

    
12
namespace ID2PSN
13
{
14
    public enum PSNType
15
    {
16
        None,
17
        Branch,
18
        Equipment,
19
        Header,
20
        Symbol,
21
        OPC,
22
    }
23

    
24
    public enum ErrorType
25
    {
26
        Error = -1,
27
        OK,
28
        InValid //이값은 들어가는데가 없음..
29
    }
30

    
31
    public class PSN
32
    {
33
        private double[] DrawingSize = null;
34
        private double DrawingWidth = double.NaN;
35
        private double DrawingHeight = double.NaN;
36
        public int Revision;
37
        public string EquipTagNoAttributeName = string.Empty;
38
        public DataTable PathItems { get; set; }
39
        public DataTable SequenceData { get; set; }
40
        public DataTable PipeSystemNetwork { get; set; }
41
        public DataTable TopologySet { get; set; }
42
        public DataTable Equipment { get; set; }
43
        public DataTable Nozzle { get; set; }
44
        public DataTable PipeLine { get; set; }
45

    
46
        public string Rule1 = "Line Disconnected";
47
        public string Rule2 = "Missing LineNumber"; //토폴로지데이터가 = Empty LineNumber 인것 ??..
48
        public string Rule3 = "OPC Disconneted";
49
        public string Rule4 = "Missing ItemTag or Description";
50
        public string Rule5 = "";
51

    
52
        int tieInPointIndex = 1;
53

    
54
        List<Document> Documents;
55
        List<Group> groups = new List<Group>();
56
        List<PSNItem> PSNItems = new List<PSNItem>();
57
        List<Topology> Topologies = new List<Topology>();
58

    
59
        DataTable opcDT = null;
60
        DataTable topologyRuleDT = null;
61

    
62
        ID2Info id2Info = ID2Info.GetInstance();
63

    
64
        
65

    
66
        //const string FluidPriorityType = "FLUIDCODE";
67
        //const string PipingMaterialsPriorityType = "PIPINGMATERIALSCLASS";
68

    
69
        public PSN()
70
        {
71
            
72
        }
73

    
74
        public PSN(List<Document> documents, int Revision)
75
        {
76
            try
77
            {
78
                Documents = documents;
79
                foreach (Document document in Documents)
80
                    groups.AddRange(document.Groups);
81
                opcDT = GetOPCInfo();
82
                topologyRuleDT = GetTopologyRule();
83
                this.Revision = Revision;
84
                DrawingSize = DB.GetDrawingSize();
85
                if (DrawingSize == null)
86
                {
87
                    MessageBox.Show("There is no data whose Section is Area and Key is Drawing in the drawing table.", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
88
                    return;
89
                }
90
                DrawingWidth = DrawingSize[2] - DrawingSize[0];
91
                DrawingHeight = DrawingSize[3] - DrawingSize[1];
92
            }
93
            catch (Exception ex)
94
            {
95
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
96
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
97
            }
98
        }
99

    
100
        private string GetItemTag(Item item)
101
        {
102
            string result = string.Empty;
103
            if (item.ItemType == ItemType.Line)
104
                result = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
105
            else if (item.ItemType == ItemType.Symbol && item.SubItemType == SubItemType.Nozzle)
106
                result = Nozzle.Select(string.Format("OID = '{0}'", item.UID)).First()["ITEMTAG"].ToString();
107

    
108
            return result;
109
        }
110
        private string GetItemName(Item item, string itemOID)
111
        {
112
            string result = string.Empty;
113
            if (item.ItemType == ItemType.Line && (item.Name == "Secondary" || item.Name == "Primary"))
114
            {
115
                if (itemOID.Contains("_"))
116
                {
117
                    string split = itemOID.Split(new char[] { '_' })[1];
118
                    if (split.StartsWith("B"))
119
                        result = "Branch";
120
                    else
121
                        result = "PipeRun";
122
                }
123
                else
124
                    result = "PipeRun";
125
            }
126
            else if (item.ItemType == ItemType.Symbol)
127
            {
128
                if (item.ID2DBCategory == "Instrumentation")
129
                    result = "Instrument";
130
                else if (item.ID2DBType == "Nozzles")
131
                    result = "Nozzle";
132
                else if (item.ID2DBType == "Fittings" ||
133
                        item.ID2DBType == "Piping OPC's" ||
134
                        item.ID2DBType == "Specialty Components" ||
135
                        item.ID2DBType == "Valves" ||
136
                        item.ID2DBType == "Reducers")
137
                    result = "PipingComp";
138
            }
139
            return result;
140
        }
141

    
142
        private string GetClass(Item item, string itemOID)
143
        {
144
            string result = string.Empty;
145
            if (item.ItemType == ItemType.Line && (item.Name == "Secondary" || item.Name == "Primary"))
146
            {
147
                if (itemOID.Contains("_"))
148
                {
149
                    string split = itemOID.Split(new char[] { '_' })[1];
150
                    if (split.StartsWith("B"))
151
                        result = "Branch";
152
                    else
153
                        result = "Piping";
154
                }
155
                else
156
                    result = "Piping";
157
            }
158
            else if (item.ItemType == ItemType.Symbol)
159
            {
160
                if (item.ID2DBCategory == "Instrumentation")
161
                    result = item.ID2DBType;
162
                else if (item.ID2DBType == "Nozzles")
163
                    result = string.Empty;
164
                else if (item.ID2DBType == "Fittings" ||
165
                       item.ID2DBType == "Piping OPC's" ||
166
                       item.ID2DBType == "Specialty Components" ||
167
                       item.ID2DBType == "Valves" ||
168
                       item.ID2DBType == "Reducers")
169
                    result = item.ID2DBType;
170
            }
171
            return result;
172
        }
173

    
174
        private string GetSubClass(Item item, string itemOID)
175
        {
176
            string result = string.Empty;
177
            if (item.ItemType == ItemType.Line && (item.Name == "Secondary" || item.Name == "Primary"))
178
            {
179
                if (itemOID.Contains("_"))
180
                {
181
                    string split = itemOID.Split(new char[] { '_' })[1];
182
                    if (split.StartsWith("B"))
183
                        result = "Tee";
184
                    else
185
                        result = "";
186
                }
187
                else
188
                    result = "";
189
            }
190
            else if (item.ItemType == ItemType.Symbol)
191
            {
192
                if (item.ID2DBCategory == "Instrumentation")
193
                    result = string.Empty;
194
                else if (item.ID2DBType == "Nozzles")
195
                    result = string.Empty;
196
                else if (item.ID2DBType == "Fittings" ||
197
                       item.ID2DBType == "Piping OPC's" ||
198
                       item.ID2DBType == "Specialty Components" ||
199
                       item.ID2DBType == "Valves" ||
200
                       item.ID2DBType == "Reducers")
201
                    result = "In-line component";
202
            }
203
            return result;
204
        }
205

    
206
        public void SetPSNData()
207
        {
208
            // Item들의 속성으로 Topology Data를 생성한다.
209
            // Topology Data는 Topology Rule Setting을 기준으로 생성한다. 
210
            SetTopologyData();
211
            // ID2의 OPC연결 Data 기반으로 Group(도면단위 PSN)을 연결한다.
212
            ConnectByOPC();
213
            // 실제 PSN 생성 로직
214
            // 연결된 Group을 하나의 PSN으로 만든다.
215
            SetPSNItem();
216
            // 생성된 PSN의 Type을 설정한다.
217
            SetPSNType();
218
            // ID2에는 Branch 정보가 없어서 Branch 정보를 생성한다.
219
            SetBranchInfo();
220
            // 생성된 Topology Data들을 정리하며 Main, Branch를 판단한다.
221
            SetTopology();
222
            // PSN이 Bypass인지 검사 
223
            SetPSNBypass();
224
            // Topology들에게 Index를 부여한다
225
            SetTopologyIndex();            
226
            // Nozzle, Equipment의 정보를 저장
227
            SaveNozzleAndEquipment();
228
            // PSN의 정보를 저장
229
            SavePSNData();
230
            // Topology의 subtype을 update(bypass, Header, 등등) 
231
            UpdateSubType();
232
            // Update Error
233
            UpdateErrorForPSN();
234
            // 확도 계산
235
            UpdateAccuracy();          
236
        }
237

    
238
        private void SetTopologyData()
239
        {
240
            // 13번 excel
241
            foreach (Group group in groups)
242
            {
243
                LineNumber prevLineNumber = null;
244
                for (int i = 0; i < group.Items.Count; i++)
245
                {
246
                    Item item = group.Items[i];
247
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
248
                    if (lineNumber == null)
249
                    {
250
                        if (prevLineNumber != null)
251
                        {
252
                            if (!prevLineNumber.IsCopy)
253
                            {
254
                                prevLineNumber = prevLineNumber.Copy();
255
                                item.Document.LineNumbers.Add(prevLineNumber);
256
                            }
257

    
258
                            item.Owner = prevLineNumber.UID;
259
                        }
260
                    }
261
                    else
262
                        prevLineNumber = lineNumber;
263
                }
264

    
265
                prevLineNumber = null;
266
                for (int i = group.Items.Count - 1; i > -1; i--)
267
                {
268
                    Item item = group.Items[i];
269
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
270
                    if (lineNumber == null)
271
                    {
272
                        if (prevLineNumber != null)
273
                        {
274
                            if (!prevLineNumber.IsCopy)
275
                            {
276
                                prevLineNumber = prevLineNumber.Copy();
277
                                item.Document.LineNumbers.Add(prevLineNumber);
278
                            }
279

    
280
                            item.Owner = prevLineNumber.UID;
281
                        }
282
                    }
283
                    else
284
                        prevLineNumber = lineNumber;
285
                }
286

    
287
                if (prevLineNumber == null)
288
                {
289
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
290
                    Random random = new Random();
291
                    int index = random.Next(lineNumbers.Count - 1);
292
                    
293
                    // Copy
294
                    LineNumber cLineNumber = lineNumbers[index].Copy();
295
                    group.Document.LineNumbers.Add(cLineNumber);
296

    
297
                    foreach (Item item in group.Items)
298
                        item.Owner = cLineNumber.UID;
299
                }
300
            }
301

    
302
            foreach (Document document in Documents)
303
            {
304
                foreach (Item item in document.Items)
305
                {
306
                    item.TopologyData = string.Empty;
307
                    item.PSNPipeLineID = string.Empty;
308
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
309
                    if (lineNumber != null)
310
                    {
311
                        item.LineNumber = lineNumber;
312

    
313
                        foreach (DataRow row in topologyRuleDT.Rows)
314
                        {
315
                            string uid = row["UID"].ToString();
316
                            if (uid == "-")
317
                                item.TopologyData += "-"; 
318
                            else
319
                            {
320
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
321

    
322
                                Attribute attribute = lineNumber.Attributes.Find(x => x.Name == uid);
323
                                if (attribute != null)
324
                                    item.TopologyData += attribute.Value;
325
                            }
326
                        }
327

    
328
                        Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
329
                        if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
330
                            item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
331
                        else
332
                            item.PSNPipeLineID = item.TopologyData;
333
                    }
334
                    else
335
                    {
336
                        item.TopologyData = "Empty LineNumber";
337
                        item.LineNumber = new LineNumber();
338
                    }
339
                }
340
            }
341

    
342
            int emptyIndex = 1;
343
            foreach (Group group in groups)
344
            {
345
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
346
                if (groupItems.Count > 0)
347
                {
348
                    foreach (var item in groupItems)
349
                        item.TopologyData += string.Format("-{0}", emptyIndex);
350
                    emptyIndex++;
351
                }
352
            }
353

    
354
        }
355

    
356
        private void ConnectByOPC()
357
        {
358
            try
359
            {
360
                foreach (Group group in groups.FindAll(x => x.Items.Last().SubItemType == SubItemType.OPC))
361
                {
362
                    Item opcItem = group.Items.Last();
363
                    DataRow[] fromRows = opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID));
364
                    if (fromRows.Length.Equals(1))
365
                    {
366
                        DataRow opcRow = fromRows.First();
367
                        string toDrawing = opcRow["ToDrawing"].ToString();
368
                        string toOPCUID = opcRow["ToOPCUID"].ToString();
369

    
370
                        Document toDocument = Documents.Find(x => x.DrawingName == toDrawing);
371
                        if (toDocument != null)
372
                        {
373
                            Group toGroup = toDocument.Groups.Find(x => x.Items.Find(y => y.UID == toOPCUID) != null);
374
                            DataRow[] toRows = opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID));
375
                            //1대1 매칭이 아닐때 걸림 (2개 이상일 때) 2021.11.07 
376
                            if (toRows.Length > 1)
377
                            {
378
                                //throw new Exception("OPC error(multi connect)");
379
                                MessageBox.Show("OPC error(multi connect)", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
380
                                return;
381
                            }
382
                            group.EndGroup = toGroup;
383
                            toGroup.StartGroup = group;
384
                        }
385
                    }
386
                }
387
            }
388
            catch (Exception ex)
389
            {
390
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
391
                //MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
392
            }
393
        }
394

    
395
        private void SetPSNItem()
396
        {
397
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>(); 
398
            foreach (Group group in groups)
399
                groupDic.Add(group, Guid.NewGuid().ToString());
400

    
401
            foreach (Group group in groups)
402
            {
403
                string groupKey = groupDic[group];
404
                if (group.StartGroup != null)
405
                {
406
                    string otherKey = groupDic[group.StartGroup];
407
                    ChangeGroupID(otherKey, groupKey);
408
                }
409
            }
410

    
411
            // PSN 정리
412
            foreach (var item in groupDic)
413
            {
414
                Group group = item.Key;
415
                string uid = item.Value;
416
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
417
                if (PSNItem == null)
418
                {
419
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
420
                    PSNItems.Add(PSNItem);
421
                }
422
                PSNItem.Groups.Add(group);
423
                foreach (Item groupItem in group.Items)
424
                    groupItem.PSNItem = PSNItem;
425
            }
426

    
427
            // Sort PSN
428
            foreach (PSNItem PSNItem in PSNItems)
429
            {
430
                List<Group> _groups = new List<Group>();
431

    
432
                Stack<Group> stacks = new Stack<Group>();
433
                stacks.Push(PSNItem.Groups.First());
434
                while (stacks.Count > 0)
435
                {
436
                    Group stack = stacks.Pop();
437
                    if (_groups.Contains(stack))
438
                        continue;
439

    
440
                    if (_groups.Count == 0)
441
                        _groups.Add(stack);
442
                    else
443
                    {
444
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
445
                        {
446
                            int index = _groups.IndexOf(stack.StartGroup);
447
                            _groups.Insert(index + 1, stack);
448
                        }
449
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
450
                        {
451
                            int index = _groups.IndexOf(stack.EndGroup);
452
                            _groups.Insert(index, stack);
453
                        }
454
                    }
455

    
456
                    if (stack.StartGroup != null)
457
                        stacks.Push(stack.StartGroup);
458
                    if (stack.EndGroup != null)
459
                        stacks.Push(stack.EndGroup);
460
                }
461

    
462
                PSNItem.Groups.Clear();
463
                PSNItem.Groups.AddRange(_groups);
464
            }
465

    
466
            void ChangeGroupID(string from, string to)
467
            {
468
                if (from.Equals(to))
469
                    return;
470

    
471
                List<Group> changeItems = new List<Group>();
472
                foreach (var _item in groupDic)
473
                    if (_item.Value.Equals(from))
474
                        changeItems.Add(_item.Key);
475
                foreach (var _item in changeItems)
476
                    groupDic[_item] = to;
477
            }
478
        }
479

    
480
        private void SetPSNType()
481
        {
482
            foreach (PSNItem PSNItem in PSNItems)
483
            {
484
                Group firstGroup = PSNItem.Groups.First();
485
                Group lastGroup = PSNItem.Groups.Last();
486

    
487
                Item firstItem = firstGroup.Items.First();
488
                Item lastItem = lastGroup.Items.Last();
489

    
490
                PSNItem.StartType = GetPSNType(firstItem, true);
491
                PSNItem.EndType = GetPSNType(lastItem, false);
492
            }
493

    
494
            PSNType GetPSNType(Item item, bool bFirst = true)
495
            {
496
                PSNType type = PSNType.None;
497

    
498
                if (item.ItemType == ItemType.Line)
499
                {
500
                    Group group = groups.Find(x => x.Items.Contains(item));
501
                    if (bFirst && item.Relations[0].Item != null && !group.Items.Contains(item.Relations[0].Item))
502
                    {
503
                        Item connItem = item.Relations[0].Item;
504
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
505
                            type = PSNType.Branch;
506
                        else if (connItem.ItemType == ItemType.Symbol)
507
                            type = PSNType.Symbol;
508
                    }
509
                    else if (!bFirst && item.Relations[1].Item != null && !group.Items.Contains(item.Relations[1].Item))
510
                    {
511
                        Item connItem = item.Relations[1].Item;
512
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
513
                            type = PSNType.Branch;
514
                        else if (connItem.ItemType == ItemType.Symbol)
515
                            type = PSNType.Symbol;
516
                    }
517
                }
518
                else if (item.ItemType == ItemType.Symbol)
519
                {
520
                    if (item.SubItemType == SubItemType.Nozzle)
521
                        type = PSNType.Equipment;
522
                    else if (item.SubItemType == SubItemType.Header)
523
                        type = PSNType.Header;
524
                    else if (item.SubItemType == SubItemType.OPC)
525
                        type = PSNType.OPC;
526
                }
527

    
528
                return type;
529
            }
530
        }
531

    
532
        private void SetBranchInfo()
533
        {
534
            foreach (Document document in Documents)
535
            {
536
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
537
                foreach (Item line in lines)
538
                {
539
                    double[] point = line.Relations[0].Point;
540
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
541
                    connLines.Sort(SortBranchLine);
542
                    line.BranchItems.AddRange(connLines);
543

    
544
                    int SortBranchLine(Item a, Item b)
545
                    {
546
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
547
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
548

    
549
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
550
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
551

    
552
                        // 내림차순
553
                        return distanceA.CompareTo(distanceB);
554
                    }
555
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
556
                    {
557
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
558
                    }
559
                }
560
            }
561
        }
562

    
563
        private void SetTopology()
564
        {
565
            try
566
            {
567
                #region 기본 topology 정리
568
                foreach (PSNItem PSNItem in PSNItems)
569
                {
570
                    Topology topology = null;
571
                    foreach (Group group in PSNItem.Groups)
572
                    {
573
                        foreach (Item item in group.Items)
574
                        {
575
                            if (string.IsNullOrEmpty(item.TopologyData))
576
                                topology = null;
577
                            else
578
                            {
579
                                if (topology == null)
580
                                {
581
                                    topology = new Topology()
582
                                    {
583
                                        ID = item.TopologyData
584
                                    };
585
                                    Topologies.Add(topology);
586

    
587
                                    if (!PSNItem.Topologies.Contains(topology))
588
                                        PSNItem.Topologies.Add(topology);
589
                                }
590
                                else
591
                                {
592
                                    if (topology.ID != item.TopologyData)
593
                                    {
594
                                        topology = new Topology()
595
                                        {
596
                                            ID = item.TopologyData
597
                                        };
598
                                        Topologies.Add(topology);
599

    
600
                                        if (!PSNItem.Topologies.Contains(topology))
601
                                            PSNItem.Topologies.Add(topology);
602
                                    }
603
                                }
604

    
605
                                item.Topology = topology;
606
                                topology.Items.Add(item);
607
                            }
608
                        }
609
                    }
610
                }
611
                #endregion
612

    
613
                #region Type
614
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
615
                foreach (string id in ids)
616
                {
617
                    try
618
                    {
619

    
620

    
621
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
622

    
623
                        // Main
624
                        List<Topology> mainTopologies = FindMainTopology(topologies);
625
                        foreach (Topology topology in mainTopologies)
626
                            topology.Type = "M";
627

    
628
                        // Branch
629
                        List<Topology> branchToplogies = topologies.FindAll(x => string.IsNullOrEmpty(x.Type));
630
                        foreach (Topology topology in branchToplogies)
631
                            topology.Type = "B";
632
                    }
633
                    catch (Exception ex)
634
                    {
635
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
636
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
637
                    }
638
                }
639
                #endregion
640
            }
641
            catch (Exception ex)
642
            {
643
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
644
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
645
            }
646

    
647
        }
648

    
649
        private void SetTopologyIndex()
650
        {
651
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
652
            foreach (string id in ids)
653
            {
654
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
655

    
656
                // Main
657
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
658
                foreach (Topology topology in mainTopologies)
659
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
660

    
661
                // Branch
662
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
663
                foreach (Topology topology in branchToplogies)
664
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
665
            }
666
        }
667

    
668
        private void SetPSNBypass()
669
        {
670
            foreach (PSNItem PSNItem in PSNItems)
671
                PSNItem.IsBypass = IsBypass(PSNItem);
672
        }
673

    
674
        private List<Topology> FindMainTopology(List<Topology> data)
675
        {
676
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
677
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
678
            //2021.11.17 안쓰네 JY
679
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
680

    
681
            List<Topology> main = new List<Topology>();
682
            main.AddRange(data);
683
            //
684
            main = GetNozzleTopology(data);
685
            if (main.Count == 1)
686
                return main;
687
            else
688
            {
689
                if (main.Count > 0)
690
                    main = GetPMCTopology(main);
691
                else
692
                    main = GetPMCTopology(data);
693

    
694
                if (main.Count == 1)
695
                    return main;
696
                else
697
                {
698
                    if (main.Count > 0)
699
                        main = GetDiaTopology(main);
700
                    else
701
                        main = GetDiaTopology(data);
702

    
703

    
704
                    if (main.Count == 1)
705
                        return main;
706
                    else
707
                    {
708
                        if (main.Count > 0)
709
                            main = GetItemTopology(main);
710
                        else
711
                            main = GetItemTopology(data);
712
                    }
713
                }
714
            }
715

    
716
            List<Topology> GetNozzleTopology(List<Topology> topologies)
717
            {
718
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
719
            }
720

    
721
            List<Topology> GetPMCTopology(List<Topology> topologies)
722
            {
723
                List<Topology> result = new List<Topology>();
724
                foreach (DataRow row in PMCDT.Rows)
725
                {
726
                    string value = row["CODE"].ToString();
727
                    foreach (Topology topology in topologies)
728
                    {
729
                        foreach (Item item in topology.Items)
730
                        {
731
                            if (item.LineNumber == null)
732
                                continue;
733
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
734
                            if (attribute != null && value == attribute.Value)
735
                            {
736
                                result.Add(topology);
737
                                break;
738
                            }
739
                        }
740
                    }
741

    
742
                    if (result.Count > 0)
743
                        break;
744
                }
745

    
746
                return result;
747
            }
748

    
749
            List<Topology> GetDiaTopology(List<Topology> topologies)
750
            {
751
                List<Topology> result = new List<Topology>();
752
                foreach (DataRow row in nominalDiameterDT.Rows)
753
                {
754
                    string inchValue = row["InchStr"].ToString();
755
                    string metricValue = row["MetricStr"].ToString();
756
                    foreach (Topology topology in topologies)
757
                    {
758
                        foreach (Item item in topology.Items)
759
                        {
760
                            if (item.LineNumber == null)
761
                                continue;
762
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
763
                            if (attribute != null && (inchValue == attribute.Value || metricValue == attribute.Value))
764
                            {
765
                                result.Add(topology);
766
                                break;
767
                            }
768
                        }
769
                    }
770

    
771
                    if (result.Count > 0)
772
                        break;
773
                }
774

    
775
                return result;
776
            }
777

    
778
            List<Topology> GetItemTopology(List<Topology> topologies)
779
            {
780
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
781
            }
782

    
783
            return main;
784
        }
785

    
786
        private DataTable GetOPCInfo()
787
        {
788
            DataTable opc = DB.SelectOPCRelations();
789
            DataTable drawing = DB.SelectDrawings();
790

    
791
            DataTable dt = new DataTable();
792
            dt.Columns.Add("FromDrawing", typeof(string));
793
            dt.Columns.Add("FromDrawingUID", typeof(string));
794
            dt.Columns.Add("FromOPCUID", typeof(string));
795
            dt.Columns.Add("ToDrawing", typeof(string));
796
            dt.Columns.Add("ToDrawingUID", typeof(string));
797
            dt.Columns.Add("ToOPCUID", typeof(string));
798
            foreach (DataRow row in opc.Rows)
799
            {
800
                string fromDrawingUID = row["From_Drawings_UID"] == null ? string.Empty : row["From_Drawings_UID"].ToString();
801
                string fromOPCUID = row["From_OPC_UID"] == null ? string.Empty : row["From_OPC_UID"].ToString(); 
802
                string toDrawingUID = row["To_Drawings_UID"] == null ? string.Empty : row["To_Drawings_UID"].ToString(); 
803
                string toOPCUID = row["To_OPC_UID"] == null ? string.Empty : row["To_OPC_UID"].ToString();
804
                if (!string.IsNullOrEmpty(toOPCUID))
805
                {
806
                    DataRow[] fromRows = drawing.Select(string.Format("UID = '{0}'", fromDrawingUID));
807
                    DataRow[] toRows = drawing.Select(string.Format("UID = '{0}'", toDrawingUID));
808
                    if (fromRows.Length.Equals(1) && toRows.Length.Equals(1))
809
                    {
810
                        string fromDrawingName = Path.GetFileNameWithoutExtension(fromRows.First()["NAME"].ToString());
811
                        string toDrawingName = Path.GetFileNameWithoutExtension(toRows.First()["NAME"].ToString());
812

    
813
                        DataRow newRow = dt.NewRow();
814
                        newRow["FromDrawing"] = fromDrawingName;
815
                        newRow["FromDrawingUID"] = fromDrawingUID;
816
                        newRow["FromOPCUID"] = fromOPCUID;
817
                        newRow["ToDrawing"] = toDrawingName;
818
                        newRow["ToDrawingUID"] = toDrawingUID;
819
                        newRow["ToOPCUID"] = toOPCUID;
820

    
821
                        dt.Rows.Add(newRow);
822
                    }
823
                }
824
            }
825

    
826
            return dt;
827
        }
828

    
829
        private DataTable GetTopologyRule()
830
        {
831
            DataTable dt = DB.SelectTopologyRule();
832

    
833
            return dt;
834
        }
835

    
836
        private bool IsConnected(Item item1, Item item2)
837
        {
838
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
839
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
840
                return true;
841
            else
842
                return false;
843
        }
844

    
845
        private void SaveNozzleAndEquipment()
846
        {
847
            List<Item> nozzles = new List<Item>();
848
            List<Equipment> equipments = new List<Equipment>();
849
            foreach (Document document in Documents)
850
            {
851
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
852
                equipments.AddRange(document.Equipments);
853
            }
854
                
855

    
856
            DataTable nozzleDT = new DataTable();
857
            nozzleDT.Columns.Add("OID", typeof(string));
858
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
859
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
860
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
861
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
862
            nozzleDT.Columns.Add("FLUID", typeof(string));
863
            nozzleDT.Columns.Add("NPD", typeof(string));
864
            nozzleDT.Columns.Add("ROTATION", typeof(string));
865
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
866

    
867
            foreach (Item item in nozzles)
868
            {
869
                DataRow row = nozzleDT.NewRow();
870
                row["OID"] = item.UID;
871

    
872
                Relation relation = item.Relations.Find(x => equipments.Find(y => y.UID == x.UID) != null);
873
                if (relation != null)
874
                {
875
                    Equipment equipment = equipments.Find(x => x.UID == relation.UID);
876
                    equipment.Nozzles.Add(item);
877
                    row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", equipment.Nozzles.Count + 100));
878
                    row["Equipment_OID"] = equipment.UID;
879
                    item.Equipment = equipment;
880
                }
881
                row["XCOORDS"] = (item.POINT[0] / DrawingWidth).ToString();
882
                row["YCOORDS"] = (item.POINT[1] / DrawingHeight).ToString();
883
                Attribute fluidAttr = item.LineNumber.Attributes.Find(x => x.Name == "FluidCode");
884
                row["FLUID"] = fluidAttr != null ? fluidAttr.Value : string.Empty;
885
                Attribute npdAttr = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
886
                row["NPD"] = npdAttr != null ? npdAttr.Value : string.Empty;
887

    
888
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
889
                if (angle >= Math.PI * 2)
890
                    angle = angle - Math.PI * 2;
891
                row["ROTATION"] = angle.ToString();
892

    
893
                if (item.Topology.Items.First().Equals(item))
894
                    row["FlowDirection"] = "Outlet";
895
                else if (item.Topology.Items.Last().Equals(item))
896
                    row["FlowDirection"] = "Inlet";
897
                else
898
                    row["FlowDirection"] = string.Empty;
899

    
900
                nozzleDT.Rows.Add(row);
901
            }
902

    
903
            DataTable equipDT = new DataTable();
904
            equipDT.Columns.Add("OID", typeof(string));
905
            equipDT.Columns.Add("ITEMTAG", typeof(string));
906
            equipDT.Columns.Add("XCOORDS", typeof(string));
907
            equipDT.Columns.Add("YCOORDS", typeof(string));
908

    
909
            foreach (Equipment equipment in equipments)
910
            {
911
                DataRow row = equipDT.NewRow();
912
                row["OID"] = equipment.UID;
913
                if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
914
                {
915
                    Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
916
                    if (attribute != null)
917
                        equipment.ItemTag = attribute.Value;
918
                }
919
                else
920
                    equipment.ItemTag = equipment.Name;
921

    
922
                row["ITEMTAG"] = equipment.ItemTag;
923
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
924
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
925

    
926
                List<double> yList = equipment.POINT.Select(x => x[1]).ToList();
927
                row["YCOORDS"] = (yList.Sum() / (double)yList.Count) / DrawingHeight;
928

    
929
                equipDT.Rows.Add(row);
930
            }
931

    
932
            Equipment = equipDT;
933
            Nozzle = nozzleDT;
934
        }
935

    
936
        private void SavePSNData()
937
        {
938
            try
939
            {
940
                DataTable pathItemsDT = new DataTable();
941
                pathItemsDT.Columns.Add("OID", typeof(string));
942
                pathItemsDT.Columns.Add("SequenceData_OID", typeof(string));
943
                pathItemsDT.Columns.Add("TopologySet_OID", typeof(string));
944
                pathItemsDT.Columns.Add("BranchTopologySet_OID", typeof(string));
945
                pathItemsDT.Columns.Add("PipeLine_OID", typeof(string));
946
                pathItemsDT.Columns.Add("ITEMNAME", typeof(string));
947
                pathItemsDT.Columns.Add("ITEMTAG", typeof(string));
948
                pathItemsDT.Columns.Add("DESCRIPTION", typeof(string));                
949
                pathItemsDT.Columns.Add("Class", typeof(string));
950
                pathItemsDT.Columns.Add("SubClass", typeof(string));
951
                pathItemsDT.Columns.Add("TYPE", typeof(string));
952
                pathItemsDT.Columns.Add("PIDNAME", typeof(string));
953
                pathItemsDT.Columns.Add("Equipment_OID", typeof(string));
954
                pathItemsDT.Columns.Add("NPD", typeof(string));
955
                pathItemsDT.Columns.Add("PipeSystemNetwork_OID", typeof(string));
956
                pathItemsDT.Columns.Add("ViewPipeSystemNetwork_OID", typeof(string));
957
                pathItemsDT.Columns.Add("PipeRun_OID", typeof(string));
958

    
959
                DataTable sequenceDataDT = new DataTable();
960
                sequenceDataDT.Columns.Add("OID", typeof(string));
961
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
962
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
963
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
964

    
965
                DataTable pipeSystemNetworkDT = new DataTable();
966
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
967
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
968
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
969
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
970
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
971
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
972
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
973
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
974
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
975
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
976
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
977
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
978
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
979
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
980

    
981
                DataTable topologySetDT = new DataTable();
982
                topologySetDT.Columns.Add("OID", typeof(string));
983
                topologySetDT.Columns.Add("Type", typeof(string));
984
                topologySetDT.Columns.Add("SubType", typeof(string));
985
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
986
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
987
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
988
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
989

    
990
                DataTable pipelineDT = new DataTable();
991
                pipelineDT.Columns.Add("OID", typeof(string));
992
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
993
                pipelineDT.Columns.Add("FLUID", typeof(string));
994
                pipelineDT.Columns.Add("PMC", typeof(string));
995
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
996
                pipelineDT.Columns.Add("INSULATION", typeof(string));
997
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
998
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
999
                pipelineDT.Columns.Add("Unit", typeof(string));
1000

    
1001
                // Set Vent/Drain Info
1002
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
1003
                DataTable dt = DB.SelectVentDrainSetting();
1004
                foreach (DataRow row in dt.Rows)
1005
                {
1006
                    string groupID = row["GROUP_ID"].ToString();
1007
                    string desc = row["DESCRIPTION"].ToString();
1008
                    int index = Convert.ToInt32(row["INDEX"]);
1009
                    string name = row["NAME"].ToString();
1010

    
1011
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
1012
                    if (ventDrainInfo == null)
1013
                    {
1014
                        ventDrainInfo = new VentDrainInfo(groupID);
1015
                        ventDrainInfo.Description = desc;
1016
                        VentDrainInfos.Add(ventDrainInfo);
1017
                    }
1018

    
1019
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
1020
                    {
1021
                        Index = index,
1022
                        Name = name
1023
                    });
1024
                }
1025

    
1026
                #region Keyword Info
1027
                KeywordInfo KeywordInfos = new KeywordInfo();
1028
                DataTable dtKeyword = DB.SelectKeywordsSetting();
1029
                foreach (DataRow row in dtKeyword.Rows)
1030
                {
1031
                    int index = Convert.ToInt32(row["INDEX"]);
1032
                    string name = row["NAME"].ToString();
1033
                    string keyword = row["KEYWORD"].ToString();
1034

    
1035
                    //KeywordInfo keywordInfo = new KeywordInfo();   
1036
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
1037
                    {
1038
                        Index = index,
1039
                        Name = name,
1040
                        Keyword = keyword
1041
                    });
1042
                }               
1043
                #endregion
1044

    
1045
                // key = 미입력 branch
1046
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
1047
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
1048

    
1049
                foreach (PSNItem PSNItem in PSNItems)
1050
                {
1051
                    int psnOrder = 0;
1052
                    int index = 0;
1053
                    bool bPSNStart = true;
1054
                    string sPSNData = string.Empty;
1055
                    bool bVentDrain = false;
1056

    
1057
                    //VentDrain 검사
1058
                    if (PSNItem.Groups.Count.Equals(1))
1059
                    {
1060
                        List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
1061
                        Group group = PSNItem.Groups[0];
1062
                        for (int i = 0; i < group.Items.Count; i++)
1063
                        {
1064
                            Item item = group.Items[i];
1065
                            foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1066
                            {
1067
                                if (endInfos.Contains(ventDrainInfo) || ventDrainInfo.VentDrainItems.Count != group.Items.Count)
1068
                                    continue;
1069
                                if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1070
                                {
1071
                                    endInfos.Add(ventDrainInfo);
1072
                                    continue;
1073
                                }
1074

    
1075
                                if (i + 1 == group.Items.Count && group.Items.Count.Equals(ventDrainInfo.VentDrainItems.Count))
1076
                                    bVentDrain = true;
1077
                            }
1078
                        }
1079

    
1080
                        if (!bVentDrain)
1081
                        {
1082
                            endInfos = new List<VentDrainInfo>();
1083
                            for (int i = 0; i < group.Items.Count; i++)
1084
                            {
1085
                                Item item = group.Items[group.Items.Count - i - 1];
1086
                                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1087
                                {
1088
                                    if (endInfos.Contains(ventDrainInfo) || ventDrainInfo.VentDrainItems.Count != group.Items.Count)
1089
                                        continue;
1090
                                    if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1091
                                    {
1092
                                        endInfos.Add(ventDrainInfo);
1093
                                        continue;
1094
                                    }
1095

    
1096
                                    if (i + 1 == group.Items.Count && group.Items.Count.Equals(ventDrainInfo.VentDrainItems.Count))
1097
                                        bVentDrain = true;
1098
                                }
1099
                            }
1100
                        }
1101
                    }
1102

    
1103
                    //foreach (KeywordInfo keywordInfo in KeywordInfos)
1104
                    //    keywordInfo.KeywordItems = keywordInfo.KeywordItems.OrderBy(x => x.Index).ToList();
1105

    
1106
                    try
1107
                    {
1108
                        //PSN, PathItems, SequenceData 관련
1109
                        foreach (Group group in PSNItem.Groups)
1110
                        {
1111
                            foreach (Item item in group.Items)
1112
                            {
1113
                                if (item.BranchItems.Count == 0)
1114
                                {
1115
                                    CreatePathItemsDataRow(item.UID, item.ID2DBType);
1116
                                    CreateSequenceDataDataRow(item.UID);
1117
                                    index++;
1118
                                }
1119
                                else
1120
                                {
1121
                                    CreatePathItemsDataRow(item.UID + "_L1", item.ID2DBType);
1122
                                    CreateSequenceDataDataRow(item.UID + "_L1");
1123
                                    index++;
1124
                                    for (int i = 0; i < item.BranchItems.Count; i++)
1125
                                    {
1126
                                        CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
1127
                                        CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
1128
                                        index++;
1129

    
1130
                                        CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
1131
                                        CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
1132
                                        index++;
1133

    
1134
                                        if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
1135
                                            startBranchDic.Add(item.BranchItems[i], item);
1136
                                        else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
1137
                                            endBranchDic.Add(item.BranchItems[i], item);
1138
                                    }
1139
                                }
1140

    
1141
                                if (bPSNStart)
1142
                                {
1143
                                    CreatePipeSystemNetworkDataRow();
1144
                                    sPSNData = item.TopologyData;
1145
                                    psnOrder++;
1146
                                    bPSNStart = false;
1147
                                }
1148
                                else
1149
                                {
1150
                                    if (item.TopologyData != sPSNData)
1151
                                    {
1152
                                        CreatePipeSystemNetworkDataRow();
1153
                                        sPSNData = item.TopologyData;
1154
                                        psnOrder++;
1155
                                    }
1156
                                }
1157
                                void CreatePathItemsDataRow(string itemOID, string itemType, string branchTopologyName = "", Item branchItem = null)
1158
                                {
1159
                                    DataRow newRow = pathItemsDT.NewRow();
1160

    
1161
                                    if(itemType == "Nozzles")
1162
                                    {
1163
                                        newRow["Equipment_OID"] = item.Equipment.UID;
1164
                                    }
1165

    
1166
                                    newRow["OID"] = itemOID;
1167

    
1168
                                    newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1169

    
1170
                                    newRow["TopologySet_OID"] = item.Topology.FullName;
1171

    
1172
                                    newRow["BranchTopologySet_OID"] = branchTopologyName;
1173
                                    newRow["PipeLine_OID"] = item.PSNPipeLineID;
1174
                                    newRow["ITEMNAME"] = GetItemName(item, itemOID);
1175
                                    newRow["ITEMTAG"] = GetItemTag(item);
1176
                                    newRow["Class"] = GetClass(item, itemOID);
1177
                                    newRow["SubClass"] = GetSubClass(item, itemOID);
1178

    
1179
                                    if (item.ItemType == ItemType.Symbol)
1180
                                        newRow["TYPE"] = item.ID2DBName;
1181
                                    else if (item.ItemType == ItemType.Line)
1182
                                        newRow["TYPE"] = item.ID2DBType;
1183
                                    newRow["PIDNAME"] = group.Document.DrawingName;
1184

    
1185
                                    // NPD
1186
                                    if (item.LineNumber != null)
1187
                                    {
1188
                                        Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1189
                                        if (attribute != null)
1190
                                            newRow["NPD"] = attribute.Value;
1191
                                    }
1192
                                    else
1193
                                        newRow["NPD"] = null;
1194

    
1195

    
1196
                                    newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1197
                                    if (branchItem == null)
1198
                                        newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1199
                                    else
1200
                                        newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
1201

    
1202
                                    newRow["PipeRun_OID"] = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
1203

    
1204
                                    pathItemsDT.Rows.Add(newRow);
1205
                                }
1206
                                void UpdatePathItemsDataRow(string itemOID, string Type, string Text)
1207
                                {
1208
                                    if(pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault() != null)
1209
                                    {
1210
                                        //pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["TYPE"] = Type;
1211
                                        pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["ITEMTAG"] = Text;
1212
                                        pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["DESCRIPTION"] = Text;
1213
                                        pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["ITEMNAME"] = "PipingComp";
1214
                                    }
1215
                                }
1216
                                void UpdatePathItemsKeywordDataRow(string itemOID, string Text)
1217
                                {
1218
                                    if (pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault() != null)
1219
                                    {
1220
                                        pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["TYPE"] = "End";
1221
                                        pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["ITEMTAG"] = Text;
1222
                                        pathItemsDT.Select(string.Format("OID = '{0}'", itemOID)).FirstOrDefault()["DESCRIPTION"] = Text;
1223
                                    }
1224
                                }
1225
                                void CreateSequenceDataDataRow(string itemOID)
1226
                                {
1227
                                    DataRow newRow = sequenceDataDT.NewRow();
1228
                                    newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1229
                                    newRow["SERIALNUMBER"] = string.Format("{0}", index);
1230
                                    newRow["PathItem_OID"] = itemOID;
1231
                                    newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1232

    
1233
                                    sequenceDataDT.Rows.Add(newRow);
1234
                                }
1235
                                void CreatePipeSystemNetworkDataRow()
1236
                                {
1237
                                    // VentDrain의 경우 제외 요청
1238
                                    if (bVentDrain)
1239
                                        return;
1240

    
1241
                                    DataRow newPipelineRow = pipelineDT.NewRow();
1242
                                    newPipelineRow["OID"] = item.PSNPipeLineID; //Topology Rule Setting으로 넣은 값 (F/C, PMC, I/C, SEQ NO)
1243
                                    newPipelineRow["PipeSystem_OID"] = PSNItem.PSN_OID();
1244
                                    /* PipeSystem_OID
1245
                                      Topology Rule Setting이 F/C-PMC-SEQ NO-I/C일 때, 아래 2) + 5) + 6) 조합으로 생성
1246
                    * 도면에 있는 Pipe Line Number 기준 생성해주고, Post-processing으로 Virtual Data (20"-PG-25-031V-9A1A1)로 생성해준 데이터도 여기에 다시 생성
1247
                    */
1248
                                    newPipelineRow["FLUID"] = "";
1249
                                    newPipelineRow["PMC"] = "";
1250
                                    newPipelineRow["SEQNUMBER"] = "";
1251
                                    newPipelineRow["INSULATION"] = "";
1252
                                    newPipelineRow["FROM_DATA"] = string.Empty;
1253
                                    newPipelineRow["TO_DATA"] = string.Empty;
1254
                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
1255
                                    pipelineDT.Rows.Add(newPipelineRow);
1256

    
1257
                                    DataRow newRow = pipeSystemNetworkDT.NewRow();
1258
                                    newRow["OID"] = PSNItem.PSN_OID();
1259
                                    
1260
                                    newRow["OrderNumber"] = psnOrder;
1261
                                    newRow["Pipeline_OID"] = item.PSNPipeLineID;
1262
                                    PSNItem.KeywordInfos = KeywordInfos;
1263
                                    PSNItem.Nozzle = Nozzle;
1264

    
1265
                                    string FROM_DATA = PSNItem.GetFromData();
1266
                                    newRow["FROM_DATA"] = FROM_DATA;
1267
                                    Item From_item = group.Items.First();
1268

    
1269
                                    if (PSNItem.IsKeyword)
1270
                                    {
1271
                                        PSNItem.StartType = PSNType.Equipment;
1272
                                        UpdatePathItemsKeywordDataRow(From_item.UID, FROM_DATA);                                     
1273
                                    }
1274
                                    else if(FROM_DATA == "ENDOFHEADER")
1275
                                    {
1276
                                        
1277
                                        UpdatePathItemsDataRow(From_item.UID, From_item.ID2DBName, FROM_DATA);
1278
                                    }
1279

    
1280
                                    string TO_DATA = PSNItem.GetToData();
1281
                                    newRow["TO_DATA"] = TO_DATA;
1282
                                    Item To_item = group.Items.First();
1283
                                    if (PSNItem.IsKeyword)
1284
                                    {
1285
                                        PSNItem.EndType = PSNType.Equipment;
1286
                                        UpdatePathItemsKeywordDataRow(To_item.UID, TO_DATA);
1287
                                    }
1288
                                    else if (TO_DATA == "ENDOFHEADER")
1289
                                    {
1290
                                        UpdatePathItemsDataRow(To_item.UID, From_item.ID2DBName, TO_DATA);
1291
                                    }
1292

    
1293
                                    newRow["Type"] = PSNItem.GetPSNType();
1294

    
1295
                                    newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1296
                                    newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
1297
                                    
1298
                                    newRow["IsValid"] = PSNItem.IsValid;
1299
                                    newRow["Status"] = !string.IsNullOrEmpty(PSNItem.Status) ? PSNItem.Status.Remove(0, 2) : string.Empty;
1300
                                    newRow["PBS"] = PSNItem.GetPBSData();
1301
                                  
1302
                                    List<string> drawingNames = new List<string>();
1303
                                    foreach (Group _group in PSNItem.Groups)
1304
                                    {
1305
                                        if (!drawingNames.Contains(_group.Document.DrawingName))
1306
                                        {
1307
                                            if (drawingNames.Count == 0)
1308
                                                newRow["Drawings"] = _group.Document.DrawingName;
1309
                                            else
1310
                                                newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
1311
                                            drawingNames.Add(_group.Document.DrawingName);
1312
                                        }
1313
                                    }
1314
                                    newRow["IncludingVirtualData"] = "No";
1315
                                    newRow["PSNAccuracy"] = "100";
1316
                                    pipeSystemNetworkDT.Rows.Add(newRow);
1317
                                }
1318
                            }
1319
                        }
1320
                    }
1321
                    catch(Exception ex)
1322
                    {
1323
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1324
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1325
                    }
1326

    
1327
                    //TopologySet 관련
1328
                    foreach (Topology topology in PSNItem.Topologies)
1329
                    {
1330
                        DataRow newRow = topologySetDT.NewRow();
1331
                        newRow["OID"] = topology.FullName;
1332
                        newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
1333
                        if (bVentDrain)
1334
                            newRow["SubType"] = "Vent_Drain";
1335
                        else
1336
                            newRow["SubType"] = null;
1337
                        newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
1338
                        newRow["TailItemTag"] = GetItemTag(topology.Items.First());
1339
                        newRow["HeadItemSPID"] = topology.Items.Last().UID;
1340
                        newRow["TailItemSPID"] = topology.Items.First().UID;
1341
                        topologySetDT.Rows.Add(newRow);
1342
                    }
1343
                }
1344

    
1345
                foreach (var item in startBranchDic)
1346
                {
1347
                    string uid = item.Key.UID;
1348
                    string topologyName = item.Value.Topology.FullName;
1349
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1350
                    if (rows.Length == 1)
1351
                    {
1352
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1353
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1354
                    }
1355
                    else if (rows.Length > 1)
1356
                    {
1357
                        DataRow targetRow = null;
1358
                        int index = int.MaxValue;
1359
                        foreach (DataRow row in rows)
1360
                        {
1361
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1362
                            if (split.StartsWith("L"))
1363
                            {
1364
                                int num = Convert.ToInt32(split.Remove(0, 1));
1365
                                if (index > num)
1366
                                {
1367
                                    index = num;
1368
                                    targetRow = row;
1369
                                }
1370
                            }
1371
                        }
1372

    
1373
                        if (targetRow != null)
1374
                        {
1375
                            targetRow["BranchTopologySet_OID"] = topologyName;
1376
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1377
                        }
1378
                    }
1379
                }
1380

    
1381
                foreach (var item in endBranchDic)
1382
                {
1383
                    string uid = item.Key.UID;
1384
                    string topologyName = item.Value.Topology.FullName;
1385
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1386
                    if (rows.Length == 1)
1387
                    {
1388
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1389
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1390
                    }
1391
                    else if (rows.Length > 1)
1392
                    {
1393
                        DataRow targetRow = null;
1394
                        int index = int.MinValue;
1395
                        foreach (DataRow row in rows)
1396
                        {
1397
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1398
                            if (split.StartsWith("L"))
1399
                            {
1400
                                int num = Convert.ToInt32(split.Remove(0, 1));
1401
                                if (index < num)
1402
                                {
1403
                                    index = num;
1404
                                    targetRow = row;
1405
                                }
1406
                            }
1407
                        }
1408

    
1409
                        if (targetRow != null)
1410
                        {
1411
                            targetRow["BranchTopologySet_OID"] = topologyName;
1412
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1413
                        }
1414
                    }
1415
                }
1416

    
1417
                PathItems = pathItemsDT;
1418
                SequenceData = sequenceDataDT;
1419
                PipeSystemNetwork = pipeSystemNetworkDT;
1420
                TopologySet = topologySetDT;
1421
                PipeLine = pipelineDT;
1422
            }
1423
            catch (Exception ex)
1424
            {
1425
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1426
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1427
            }
1428
        }
1429

    
1430
        private double AccuracyCalculation(List<double> lstAcc, double acc)
1431
        {
1432
            foreach(double lacc in lstAcc)
1433
            {
1434
                acc *= lacc;
1435
            }
1436
            acc = acc;
1437
            return acc;
1438
        }
1439

    
1440
        private void UpdateSubType()
1441
        {
1442
            try
1443
            {
1444

    
1445

    
1446
                foreach (PSNItem PSNItem in PSNItems)
1447
                {
1448
                    if (PSNItem.IsBypass)
1449
                    {
1450
                        foreach (Topology topology in PSNItem.Topologies)
1451
                        {
1452
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1453
                            if (rows.Length.Equals(1))
1454
                                rows.First()["SubType"] = "Bypass";
1455
                        }
1456
                    }
1457

    
1458
                    if (PSNItem.StartType == PSNType.Header)
1459
                    {
1460
                        Topology topology = PSNItem.Topologies.First();
1461
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1462
                        if (rows.Length.Equals(1))
1463
                            rows.First()["SubType"] = "Header";
1464
                    }
1465
                    else if (PSNItem.EndType == PSNType.Header)
1466
                    {
1467
                        Topology topology = PSNItem.Topologies.Last();
1468
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1469
                        if (rows.Length.Equals(1))
1470
                            rows.First()["SubType"] = "Header";
1471
                    }
1472
                }
1473

    
1474

    
1475
                foreach (Topology topology in Topologies)
1476
                {
1477
                    try
1478
                    {
1479
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1480
                        if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
1481
                        {
1482
                            if (topology.Items == null)
1483
                                continue;
1484

    
1485
                            Item firstItem = topology.Items.First();
1486
                            Item lastItem = topology.Items.Last();
1487

    
1488
                            List<Relation> relations = new List<Relation>();
1489
                            
1490
                            if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1491
                                relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1492

    
1493
                            if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1494
                                relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1495

    
1496
                            if (relations.Count > 0)
1497
                                rows.First()["SubType"] = "OtherSystem";
1498
                        }
1499
                    }
1500
                    catch (Exception ex)
1501
                    {
1502
                       
1503
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1504
                    }
1505
                }
1506

    
1507
                    foreach (DataRow row in TopologySet.Rows)
1508
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
1509
                        row["SubType"] = "Normal";
1510
            }
1511
            catch (Exception ex)
1512
            {
1513
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1514
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1515
            }
1516
        }
1517

    
1518
        private bool IsBypass(PSNItem PSNItem)
1519
        {
1520
            bool bResult = false;
1521

    
1522
            if (PSNItem.GetPSNType() == "B2B")
1523
            {
1524
                Group firstGroup = PSNItem.Groups.First();
1525
                Group lastGroup = PSNItem.Groups.Last();
1526
                Item firstItem = firstGroup.Items.First();
1527
                Item lastItem = lastGroup.Items.Last();
1528

    
1529
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
1530
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
1531

    
1532
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
1533
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
1534
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
1535
                    bResult = true;
1536
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
1537
                    bResult = true;
1538
            }
1539

    
1540
            Item GetConnectedItemByPSN(Item item)
1541
            {
1542
                Item result = null;
1543

    
1544
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
1545
                if (relation != null)
1546
                    result = relation.Item;
1547

    
1548
                return result;
1549
            }
1550

    
1551
            return bResult;
1552
        }
1553

    
1554
     
1555
        private void UpdateAccuracy()
1556
        {
1557
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
1558
            List<double> lstAcc = null;
1559
            string Status = string.Empty;
1560

    
1561
            foreach (DataRow dataRow in statusRows)
1562
            {
1563
                lstAcc = new List<double>();
1564
                Status = dataRow.Field<string>("Status");
1565

    
1566
                if (!string.IsNullOrEmpty(Status))
1567
                {
1568
                    if (Status.Contains(Rule1)) //Line Disconnected
1569
                        lstAcc.Add(0.75);
1570

    
1571
                    if (Status.Contains(Rule2)) //Missing LineNumber
1572
                        lstAcc.Add(0.7);            
1573

    
1574
                    if (Status.Contains(Rule3)) //OPC Disconneted
1575
                        lstAcc.Add(0.5);            
1576

    
1577
                    if (Status.Contains(Rule4)) //Missing ItemTag or Description
1578
                        lstAcc.Add(0.65);           
1579
                    //else if (Status.Contains(Rule5))
1580
                    //    lstAcc.Add(0.6);
1581
                }
1582

    
1583
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
1584
                if (PSNAccuracy == "100")
1585
                    PSNAccuracy = "1";
1586

    
1587
                PSNAccuracy = Convert.ToString(Math.Round(Convert.ToDouble(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))), 2));
1588
                if (PSNAccuracy != "100")
1589
                {
1590
                    dataRow["IncludingVirtualData"] = "No";
1591
                    dataRow["PSNAccuracy"] = PSNAccuracy;
1592
                }
1593
            }
1594
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
1595
            foreach (DataRow dr in dt.Rows)
1596
            {
1597
                string oid = dr.Field<string>("OID");
1598
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
1599
                double totalDdr = 0;
1600
                foreach (DataRow ddr in select)
1601
                {
1602
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
1603
                    if (acc == 100) acc = 1;
1604
                    if (totalDdr == 0) totalDdr = acc;
1605
                    else totalDdr *= acc;
1606
                }
1607

    
1608
                totalDdr *= 100;
1609

    
1610
                if(totalDdr != 100)
1611
                {
1612
                    foreach (DataRow ddr in select)
1613
                    {
1614
                        ddr["IncludingVirtualData"] = "Yes";
1615
                        ddr["PSNAccuracy"] = totalDdr;
1616
                    }
1617
                }
1618
            }
1619

    
1620
        }
1621

    
1622
        private void UpdateErrorForPSN()
1623
        {
1624
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
1625
            bool bCheckRule5 = false;
1626
            foreach (DataRow dataRow in errorRows)
1627
            {
1628
                try
1629
                {
1630
                   
1631
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
1632
                    bool change = false;
1633
                    bCheckRule5 = false;
1634

    
1635
                    if (!PSNItem.EnableType(PSNItem.StartType))
1636
                    {
1637
                        change = true;
1638
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));                       
1639
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
1640

    
1641
                        DataRow[] seqItemRows = SequenceData.Select(string.Format("PathItem_OID = '{0}'", pathItemRows.First()["OID"]));
1642
                        int insertSeqIndex = SequenceData.Rows.IndexOf(seqItemRows.First());
1643

    
1644
                        Item item = PSNItem.Groups.First().Items.First();
1645
                        try
1646
                        {
1647
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
1648
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
1649
                                loopRow["FROM_DATA"] = FROM_DATA;
1650
                            tieInPointIndex++;
1651

    
1652

    
1653
                            if (item.ItemType == ItemType.Line)
1654
                            {
1655
                                //createTerminatorRow - Rule 5번
1656
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
1657
                                SequenceData.Rows.InsertAt(createSequenceTerminatorRow(pathItemRows.First(), insertSeqIndex), insertSeqIndex);
1658

    
1659
                                bCheckRule5 = true;
1660
                            }
1661
                            else
1662
                            {
1663
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
1664
                                SequenceData.Rows.InsertAt(createSequenceTerminatorRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First(), insertSeqIndex), insertSeqIndex);
1665
                                //createTerminatorRow - Rule 5번
1666
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
1667
                                SequenceData.Rows.InsertAt(createSequenceTerminatorRow(pathItemRows.First(), insertSeqIndex), insertSeqIndex);
1668

    
1669
                                bCheckRule5 = true;
1670
                            }
1671

    
1672
                            PSNItem.StartType = PSNType.Equipment;
1673
                        }
1674
                        catch (Exception ex)
1675
                        {
1676
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
1677
                            return;
1678
                        }
1679
                    }
1680

    
1681

    
1682
                    if (!PSNItem.EnableType(PSNItem.EndType))
1683
                    {
1684
                        change = true;
1685
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1686
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.Last());
1687

    
1688
                        DataRow[] seqItemRows = SequenceData.Select(string.Format("PathItem_OID = '{0}'", pathItemRows.Last()["OID"]));
1689
                        int insertSeqIndex = SequenceData.Rows.IndexOf(seqItemRows.Last());
1690

    
1691
                        Item item = PSNItem.Groups.Last().Items.Last();
1692
                        try
1693
                        {
1694
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
1695

    
1696
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
1697
                                loopRow["TO_DATA"] = TO_DATA;
1698
                            tieInPointIndex++;
1699

    
1700

    
1701
                            if (item.ItemType == ItemType.Line)
1702
                            {
1703
                                //createTerminatorRow - Rule 5번
1704
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
1705
                                SequenceData.Rows.InsertAt(createSequenceTerminatorRow(pathItemRows.Last(), insertSeqIndex + 1), insertSeqIndex + 1);
1706

    
1707
                                bCheckRule5 = true;
1708
                            }
1709
                            else
1710
                            {
1711
                                //createTerminatorRow - Rule 5번
1712
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
1713
                                SequenceData.Rows.InsertAt(createSequenceTerminatorRow(pathItemRows.Last(), insertSeqIndex + 1), insertSeqIndex + 1);
1714
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last()), insertIndex + 1);
1715
                                SequenceData.Rows.InsertAt(createSequenceTerminatorRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last(), insertSeqIndex + 1), insertSeqIndex + 1);
1716
                                bCheckRule5 = true;
1717
                            }
1718

    
1719
                            PSNItem.EndType = PSNType.Equipment;
1720
                        }
1721
                        catch(Exception ex)
1722
                        {
1723
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
1724
                            return;
1725
                        }
1726
                    }
1727

    
1728
                    dataRow["Type"] = PSNItem.GetPSNType();
1729
                    if (change)
1730
                    {
1731
                        int rowIndex = 0;
1732
                        for (int i = 0; i < PathItems.Rows.Count; i++)
1733
                        {
1734
                            DataRow row = PathItems.Rows[i];
1735
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
1736
                                continue;
1737
                            string sequenceData = row["SequenceData_OID"].ToString();
1738
                            string[] split = sequenceData.Split(new char[] { '_' });
1739

    
1740
                            StringBuilder sb = new StringBuilder();
1741
                            for (int j = 0; j < split.Length - 1; j++)
1742
                                sb.Append(split[j] + "_");
1743
                            sb.Append(rowIndex++);
1744
                            row["SequenceData_OID"] = sb.ToString();
1745
                        }
1746

    
1747
                        rowIndex = 0;
1748
                        for (int i = 0; i < SequenceData.Rows.Count; i++)
1749
                        {
1750
                            DataRow row = SequenceData.Rows[i];
1751
                            if (row["PathItem_OID"].ToString() != dataRow["OID"].ToString())
1752
                                continue;
1753
                            string sequenceData = row["SequenceData_OID"].ToString();
1754
                            string[] split = sequenceData.Split(new char[] { '_' });
1755

    
1756
                            row["SERIALNUMBER"] = rowIndex++;
1757
                        }
1758
                    }
1759

    
1760
                    if (bCheckRule5)
1761
                    {                       
1762
                        string PSNAccuracy = "0.6";
1763
                        dataRow["IncludingVirtualData"] = "Yes";
1764
                        dataRow["PSNAccuracy"] = PSNAccuracy;
1765
                       
1766
                    }
1767

    
1768
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
1769
                    {
1770
                        DataRow newRow = PathItems.NewRow();
1771
                        newRow["OID"] = Guid.NewGuid().ToString();
1772
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
1773
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
1774
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
1775
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];                        
1776
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
1777
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
1778
                        newRow["DESCRIPTION"] = DATA; 
1779
                        newRow["Class"] = "End of line terminator";
1780
                        newRow["SubClass"] = "End of line terminator";
1781
                        newRow["TYPE"] = "End";
1782
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
1783
                        newRow["NPD"] = itemRow["NPD"];
1784
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
1785
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
1786
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
1787

    
1788
                        
1789

    
1790
                        return newRow;
1791
                    }
1792

    
1793
                    DataRow createSequenceTerminatorRow(DataRow itemRow, int insertIndex)
1794
                    {
1795
                        DataRow newRow = SequenceData.NewRow();
1796
                        newRow["OID"] = Guid.NewGuid().ToString(); 
1797
                        newRow["SERIALNUMBER"] = string.Format("{0}", insertIndex);
1798
                        newRow["PathItem_OID"] = itemRow["OID"];
1799
                        newRow["TopologySet_OID_Key"] = itemRow["TopologySet_OID"];
1800

    
1801
                        return newRow;
1802
                    }
1803

    
1804
                    DataRow createLineRow(DataRow itemRow)
1805
                    {
1806
                        DataRow newRow = PathItems.NewRow();
1807
                        newRow["OID"] = Guid.NewGuid().ToString();
1808
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
1809
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
1810
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
1811
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
1812
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
1813
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
1814
                        newRow["Class"] = itemRow["Class"];
1815
                        newRow["SubClass"] = itemRow["SubClass"];
1816
                        newRow["TYPE"] = itemRow["TYPE"];
1817
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
1818
                        newRow["NPD"] = itemRow["NPD"];
1819
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
1820
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
1821
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
1822

    
1823
                        return newRow;
1824
                    }
1825
                }
1826
                catch(Exception ex)
1827
                {
1828

    
1829
                }
1830
            }
1831
        }
1832
    }
1833

    
1834
    public class PSNItem
1835
    {
1836
        public PSNItem(int count, int Revision)
1837
        {
1838
            Groups = new List<Group>();
1839
            Topologies = new List<Topology>();
1840

    
1841
            Index = count + 1;
1842
            this.Revision = Revision;
1843
        }
1844

    
1845
        private int Revision;
1846
        public string UID { get; set; }
1847
        public List<Group> Groups { get; set; }
1848
        public List<Topology> Topologies { get; set; }
1849
        public PSNType StartType { get; set; }
1850
        public PSNType EndType { get; set; }
1851
        public int Index { get; set; }
1852
        public string IsValid { get; set; }
1853
        public bool IsKeyword { get; set; }
1854
        public string Status { get; set; }
1855
        public string IncludingVirtualData { get; set; }
1856
        public string PSNAccuracy { get; set; }
1857
        public KeywordInfo KeywordInfos = new KeywordInfo();
1858
        public DataTable Nozzle = new DataTable();
1859

    
1860
        public string PSN_OID()
1861
        {
1862
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
1863
        }
1864
        public string GetPSNType()
1865
        {
1866
            string result = string.Empty;
1867

    
1868
            if (EnableType(StartType) && EnableType(EndType))
1869
            {
1870
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
1871
                    result = "E2E";
1872
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
1873
                    result = "B2B";
1874
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
1875
                    result = "HD2";
1876

    
1877
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
1878
                    result = "E2B";
1879
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
1880
                    result = "B2E";
1881

    
1882
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
1883
                    result = "HDB";
1884
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
1885
                    result = "HDB";
1886

    
1887
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
1888
                    result = "HDE";
1889
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
1890
                    result = "HDE";
1891
                else
1892
                    result = "Error";
1893
            }
1894
            else
1895
                result = "Error";
1896

    
1897
            return result;
1898

    
1899
            
1900
        }
1901
        public bool EnableType(PSNType type)
1902
        {
1903
            bool result = false;
1904

    
1905
            if (type == PSNType.Branch ||
1906
                type == PSNType.Equipment ||
1907
                type == PSNType.Header)
1908
            {
1909
                result = true;
1910
            }
1911

    
1912
            return result;
1913
        }
1914
        public bool IsBypass { get; set; }
1915

    
1916
        public string GetFromData()
1917
        {
1918
            string result = string.Empty;
1919
            if (IsKeyword)
1920
                IsKeyword = false;
1921
            try
1922
            {
1923
                if (StartType == PSNType.Header)
1924
                    result = "ENDOFHEADER";
1925
                else if (StartType == PSNType.Branch)
1926
                {
1927
                    Item item = Groups.First().Items.First();
1928
                    if (item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
1929
                        result = item.Relations.First().Item.LineNumber.Name;
1930
                    else
1931
                    {
1932
                        Status += ", Missing LineNumber";
1933
                        result = "Empty LineNumber";
1934
                    }
1935
                }
1936
                else if (StartType == PSNType.Equipment)
1937
                {
1938
                    result = Groups.First().Items.First().Equipment.ItemTag;
1939
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
1940

    
1941
                    if (drNozzle != null)
1942
                        result += " ["+ drNozzle.Field<string>("ITEMTAG") + "]";
1943
                }
1944
                
1945
                else
1946
                {
1947
                    IsValid = "Error";
1948
                    Item item = Groups.First().Items.First();
1949
                    if (item.ItemType == ItemType.Symbol)
1950
                    {
1951

    
1952
                        string keyword = string.Empty;
1953
                        keyword = GetFromKeywordData();
1954

    
1955
                        if (string.IsNullOrEmpty(keyword))
1956
                        {
1957
                            if (item.ID2DBType.Contains("OPC's"))
1958
                                Status += ", OPC Disconneted";
1959
                            else
1960
                                Status += ", Missing ItemTag or Description";
1961

    
1962
                            result = item.ID2DBName;
1963
                        }
1964
                        else
1965
                        {
1966
                            result = keyword;
1967
                            IsKeyword = true;
1968
                            IsValid = string.Empty;
1969
                        }
1970
                        
1971
                    }
1972
                    else if (item.ItemType == ItemType.Line)
1973
                    {
1974
                        Status += ", Line Disconnected";
1975
                        result = item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
1976
                    }
1977
                    else
1978
                        result = "Unknown";
1979
                }
1980
            }
1981
            catch(Exception ex)
1982
            {
1983

    
1984
            }
1985

    
1986
            return result;
1987
        }
1988

    
1989
        public string GetFromKeywordData()
1990
        {
1991
            string result = string.Empty;
1992
           
1993
            Item item = Groups.First().Items.First();
1994

    
1995
            foreach(KeywordItem keyitem in KeywordInfos.KeywordItems)
1996
            {
1997
                if(keyitem.Name.Equals(item.Name))
1998
                    result = keyitem.Keyword;
1999
            }
2000
          
2001
            return result;
2002
        }
2003

    
2004
        public string GetToKeywordData()
2005
        {
2006
            string result = string.Empty;
2007

    
2008
            Item item = Groups.Last().Items.Last();
2009
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2010
            {
2011
                if (keyitem.Name.Equals(item.Name))
2012
                    result = keyitem.Keyword;
2013
            }
2014
            return result;
2015
        }
2016

    
2017
        public string GetToData()
2018
        {
2019
            string result = string.Empty;
2020
            if (IsKeyword)
2021
                IsKeyword = false;
2022

    
2023
            if (EndType == PSNType.Header)
2024
                result = "ENDOFHEADER";
2025
            else if (EndType == PSNType.Branch)
2026
            {
2027
                Item item = Groups.Last().Items.Last();
2028
                if (item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
2029
                    result = item.Relations.Last().Item.LineNumber.Name;
2030
                else
2031
                {
2032
                    Status += ", Missing LineNumber";
2033
                    result = "Empty LineNumber";
2034
                }
2035
            }
2036
            else if (EndType == PSNType.Equipment)
2037
            {
2038
                result = Groups.Last().Items.Last().Equipment.ItemTag;
2039
                DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
2040

    
2041
                if (drNozzle != null)
2042
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
2043
            }
2044
            else
2045
            {
2046
                IsValid = "Error";
2047
                Item item = Groups.Last().Items.Last();
2048
                if (item.ItemType == ItemType.Symbol)
2049
                {
2050
                    string keyword = string.Empty;
2051
                    keyword = GetToKeywordData();
2052

    
2053
                    if (string.IsNullOrEmpty(keyword))
2054
                    {
2055
                        if (item.ID2DBType.Contains("OPC's"))
2056
                            Status += ", OPC Disconneted";
2057
                        else
2058
                            Status += ", Missing ItemTag or Description";
2059

    
2060
                        result = item.ID2DBName;
2061
                    }
2062
                    else
2063
                    {
2064
                        result = keyword;
2065
                        IsValid = string.Empty;
2066
                        IsKeyword = true;
2067
                    }
2068
                    
2069
                }
2070
                else if (item.ItemType == ItemType.Line)
2071
                {
2072
                    Status += ", Line Disconnected";
2073
                    result = item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2074
                }
2075
                else
2076
                    result = "Unknown";
2077
            }
2078
            return result;
2079
        }
2080

    
2081
        public string GetPBSData()
2082
        {
2083
            string result = string.Empty;
2084
            List<string> PBSList = new List<string>();
2085
            if (Settings.Default.PBSSetting.Equals("Line Number"))
2086
            {
2087
                string attrValue = Settings.Default.PBSSettingValue;
2088

    
2089
                foreach (Group group in Groups)
2090
                {
2091
                    List<LineNumber> lineNumbers = group.Items.Select(x =>x.LineNumber).Distinct().ToList();
2092
                    foreach (LineNumber lineNumber in lineNumbers)
2093
                    {
2094
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
2095
                        if (attribute != null)
2096
                        {
2097
                            string value = attribute.Value;
2098
                            if (!PBSList.Contains(value))
2099
                                PBSList.Add(value);
2100
                        }
2101
                    }
2102
                }
2103
            }
2104
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
2105
            {
2106
                string attrValue = Settings.Default.PBSSettingValue;
2107

    
2108
                foreach (Group group in Groups)
2109
                {
2110
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
2111
                    foreach (Item item in items)
2112
                    {
2113
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
2114
                        if (!PBSList.Contains(value))
2115
                            PBSList.Add(value);
2116
                    }
2117
                }
2118
            }
2119
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
2120
            {
2121
                string attrValue = Settings.Default.PBSSettingValue;
2122

    
2123
                foreach (Group group in Groups)
2124
                {
2125
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
2126
                    foreach (Document document in documents)
2127
                    {
2128
                        string name = document.DrawingName;
2129

    
2130
                        int startIndex = Settings.Default.PBSSettingStartValue;
2131
                        int endIndex = Settings.Default.PBSSettingEndValue;
2132

    
2133
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
2134
                        if (!PBSList.Contains(subStr))
2135
                            PBSList.Add(subStr);
2136
                    }
2137
                }
2138
            }
2139
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
2140
            {
2141
                foreach (Group group in Groups)
2142
                {
2143
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
2144
                    foreach (Document document in documents)
2145
                    {
2146
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
2147
                        foreach (TextInfo textInfo in textInfos)
2148
                        {
2149
                            if (!PBSList.Contains(textInfo.Value))
2150
                                PBSList.Add(textInfo.Value);
2151
                        }
2152
                    }
2153
                }
2154
            }
2155

    
2156
            foreach (var item in PBSList)
2157
            {
2158
                if (string.IsNullOrEmpty(result))
2159
                    result = item;
2160
                else
2161
                    result += ", " + item;
2162
            }
2163
            return result;
2164
        }
2165
    }
2166
}
클립보드 이미지 추가 (최대 크기: 500 MB)