프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / DTI_PID / ID2PSN / PSN.cs @ eb44d82c

이력 | 보기 | 이력해설 | 다운로드 (86.7 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

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

    
51
        int tieInPointIndex = 1;
52

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

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

    
61
        ID2Info id2Info = ID2Info.GetInstance();
62

    
63
        
64

    
65
        const string FluidPriorityType = "FLUIDCODE";
66
        const string PipingMaterialsPriorityType = "PIPINGMATERIALSCLASS";
67

    
68
        public PSN()
69
        {
70
            
71
        }
72

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
353
        }
354

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
527
                return type;
528
            }
529
        }
530

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

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

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

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

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

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

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

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

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

    
619

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

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

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

    
646
        }
647

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

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

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

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

    
673
        private List<Topology> FindMainTopology(List<Topology> data)
674
        {
675
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
676
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
677
            DataTable fluidCodeDT = DB.SelectPSNFluidCode();
678

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

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

    
701

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

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

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

    
740
                    if (result.Count > 0)
741
                        break;
742
                }
743

    
744
                return result;
745
            }
746

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

    
769
                    if (result.Count > 0)
770
                        break;
771
                }
772

    
773
                return result;
774
            }
775

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

    
781
            return main;
782
        }
783

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

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

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

    
819
                        dt.Rows.Add(newRow);
820
                    }
821
                }
822
            }
823

    
824
            return dt;
825
        }
826

    
827
        private DataTable GetTopologyRule()
828
        {
829
            DataTable dt = DB.SelectTopologyRule();
830

    
831
            return dt;
832
        }
833

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

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

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

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

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

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

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

    
898
                nozzleDT.Rows.Add(row);
899
            }
900

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

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

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

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

    
927
                equipDT.Rows.Add(row);
928
            }
929

    
930
            Equipment = equipDT;
931
            Nozzle = nozzleDT;
932
        }
933

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

    
955
                DataTable sequenceDataDT = new DataTable();
956
                sequenceDataDT.Columns.Add("OID", typeof(string));
957
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
958
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
959
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
960

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

    
977
                DataTable topologySetDT = new DataTable();
978
                topologySetDT.Columns.Add("OID", typeof(string));
979
                topologySetDT.Columns.Add("Type", typeof(string));
980
                topologySetDT.Columns.Add("SubType", typeof(string));
981
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
982
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
983
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
984
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
985

    
986
                // Set Vent/Drain Info
987
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
988
                DataTable dt = DB.SelectVentDrainSetting();
989
                foreach (DataRow row in dt.Rows)
990
                {
991
                    string groupID = row["GROUP_ID"].ToString();
992
                    string desc = row["DESCRIPTION"].ToString();
993
                    int index = Convert.ToInt32(row["INDEX"]);
994
                    string name = row["NAME"].ToString();
995

    
996
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
997
                    if (ventDrainInfo == null)
998
                    {
999
                        ventDrainInfo = new VentDrainInfo(groupID);
1000
                        ventDrainInfo.Description = desc;
1001
                        VentDrainInfos.Add(ventDrainInfo);
1002
                    }
1003

    
1004
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
1005
                    {
1006
                        Index = index,
1007
                        Name = name
1008
                    });
1009
                }
1010

    
1011
                #region Keyword Info
1012
                KeywordInfo KeywordInfos = new KeywordInfo();
1013
                DataTable dtKeyword = DB.SelectKeywordsSetting();
1014
                foreach (DataRow row in dtKeyword.Rows)
1015
                {
1016
                    int index = Convert.ToInt32(row["INDEX"]);
1017
                    string name = row["NAME"].ToString();
1018
                    string keyword = row["KEYWORD"].ToString();
1019

    
1020
                    //KeywordInfo keywordInfo = new KeywordInfo();   
1021
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
1022
                    {
1023
                        Index = index,
1024
                        Name = name,
1025
                        Keyword = keyword
1026
                    });
1027
                }               
1028
                #endregion
1029

    
1030
                // key = 미입력 branch
1031
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
1032
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
1033
                foreach (PSNItem PSNItem in PSNItems)
1034
                {
1035
                    int psnOrder = 0;
1036
                    int index = 0;
1037
                    bool bPSNStart = true;
1038
                    string sPSNData = string.Empty;
1039
                    bool bVentDrain = false;
1040

    
1041
                    //VentDrain 검사
1042
                    if (PSNItem.Groups.Count.Equals(1))
1043
                    {
1044
                        List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
1045
                        Group group = PSNItem.Groups[0];
1046
                        for (int i = 0; i < group.Items.Count; i++)
1047
                        {
1048
                            Item item = group.Items[i];
1049
                            foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1050
                            {
1051
                                if (endInfos.Contains(ventDrainInfo) || ventDrainInfo.VentDrainItems.Count != group.Items.Count)
1052
                                    continue;
1053
                                if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1054
                                {
1055
                                    endInfos.Add(ventDrainInfo);
1056
                                    continue;
1057
                                }
1058

    
1059
                                if (i + 1 == group.Items.Count && group.Items.Count.Equals(ventDrainInfo.VentDrainItems.Count))
1060
                                    bVentDrain = true;
1061
                            }
1062
                        }
1063

    
1064
                        if (!bVentDrain)
1065
                        {
1066
                            endInfos = new List<VentDrainInfo>();
1067
                            for (int i = 0; i < group.Items.Count; i++)
1068
                            {
1069
                                Item item = group.Items[group.Items.Count - i - 1];
1070
                                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1071
                                {
1072
                                    if (endInfos.Contains(ventDrainInfo) || ventDrainInfo.VentDrainItems.Count != group.Items.Count)
1073
                                        continue;
1074
                                    if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1075
                                    {
1076
                                        endInfos.Add(ventDrainInfo);
1077
                                        continue;
1078
                                    }
1079

    
1080
                                    if (i + 1 == group.Items.Count && group.Items.Count.Equals(ventDrainInfo.VentDrainItems.Count))
1081
                                        bVentDrain = true;
1082
                                }
1083
                            }
1084
                        }
1085
                    }
1086

    
1087
                    //foreach (KeywordInfo keywordInfo in KeywordInfos)
1088
                    //    keywordInfo.KeywordItems = keywordInfo.KeywordItems.OrderBy(x => x.Index).ToList();
1089

    
1090
                    try
1091
                    {
1092
                        //PSN, PathItems, SequenceData 관련
1093
                        foreach (Group group in PSNItem.Groups)
1094
                        {
1095
                            foreach (Item item in group.Items)
1096
                            {
1097
                                if (item.BranchItems.Count == 0)
1098
                                {
1099
                                    CreatePathItemsDataRow(item.UID, item.ID2DBType);
1100
                                    CreateSequenceDataDataRow(item.UID);
1101
                                    index++;
1102
                                }
1103
                                else
1104
                                {
1105
                                    CreatePathItemsDataRow(item.UID + "_L1", item.ID2DBType);
1106
                                    CreateSequenceDataDataRow(item.UID + "_L1");
1107
                                    index++;
1108
                                    for (int i = 0; i < item.BranchItems.Count; i++)
1109
                                    {
1110
                                        CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
1111
                                        CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
1112
                                        index++;
1113

    
1114
                                        CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
1115
                                        CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
1116
                                        index++;
1117

    
1118
                                        if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
1119
                                            startBranchDic.Add(item.BranchItems[i], item);
1120
                                        else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
1121
                                            endBranchDic.Add(item.BranchItems[i], item);
1122
                                    }
1123
                                }
1124

    
1125
                                if (bPSNStart)
1126
                                {
1127
                                    CreatePipeSystemNetworkDataRow();
1128
                                    sPSNData = item.TopologyData;
1129
                                    psnOrder++;
1130
                                    bPSNStart = false;
1131
                                }
1132
                                else
1133
                                {
1134
                                    if (item.TopologyData != sPSNData)
1135
                                    {
1136
                                        CreatePipeSystemNetworkDataRow();
1137
                                        sPSNData = item.TopologyData;
1138
                                        psnOrder++;
1139
                                    }
1140
                                }
1141
                                void CreatePathItemsDataRow(string itemOID, string itemType, string branchTopologyName = "", Item branchItem = null)
1142
                                {
1143
                                    DataRow newRow = pathItemsDT.NewRow();
1144
                                    newRow["OID"] = itemOID;
1145

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

    
1148
                                    newRow["TopologySet_OID"] = item.Topology.FullName;
1149

    
1150
                                    newRow["BranchTopologySet_OID"] = branchTopologyName;
1151
                                    newRow["PipeLine_OID"] = item.PSNPipeLineID;
1152
                                    newRow["ITEMNAME"] = GetItemName(item, itemOID);
1153
                                    newRow["ITEMTAG"] = GetItemTag(item);
1154
                                    newRow["Class"] = GetClass(item, itemOID);
1155
                                    newRow["SubClass"] = GetSubClass(item, itemOID);
1156

    
1157
                                    if (item.ItemType == ItemType.Symbol)
1158
                                        newRow["TYPE"] = item.ID2DBName;
1159
                                    else if (item.ItemType == ItemType.Line)
1160
                                        newRow["TYPE"] = item.ID2DBType;
1161
                                    newRow["PIDNAME"] = group.Document.DrawingName;
1162

    
1163
                                    // NPD
1164
                                    if (item.LineNumber != null)
1165
                                    {
1166
                                        Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1167
                                        if (attribute != null)
1168
                                            newRow["NPD"] = attribute.Value;
1169
                                    }
1170
                                    else
1171
                                        newRow["NPD"] = null;
1172

    
1173

    
1174
                                    newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1175
                                    if (branchItem == null)
1176
                                        newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1177
                                    else
1178
                                        newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
1179

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

    
1182
                                    pathItemsDT.Rows.Add(newRow);
1183
                                }
1184
                                void CreateSequenceDataDataRow(string itemOID)
1185
                                {
1186
                                    DataRow newRow = sequenceDataDT.NewRow();
1187
                                    newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1188
                                    newRow["SERIALNUMBER"] = string.Format("{0}", index);
1189
                                    newRow["PathItem_OID"] = itemOID;
1190
                                    newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1191

    
1192
                                    sequenceDataDT.Rows.Add(newRow);
1193
                                }
1194
                                void CreatePipeSystemNetworkDataRow()
1195
                                {
1196
                                    // VentDrain의 경우 제외 요청
1197
                                    if (bVentDrain)
1198
                                        return;
1199

    
1200
                                    DataRow newRow = pipeSystemNetworkDT.NewRow();
1201
                                    newRow["OID"] = PSNItem.PSN_OID();
1202
                                    
1203
                                    newRow["OrderNumber"] = psnOrder;
1204
                                    newRow["Pipeline_OID"] = item.PSNPipeLineID;
1205
                                    PSNItem.KeywordInfos = KeywordInfos;
1206
                                    newRow["FROM_DATA"] = PSNItem.GetFromData();                                   
1207

    
1208
                                    if (PSNItem.IsValid == "Keyword")
1209
                                        PSNItem.StartType = PSNType.Equipment;
1210

    
1211
                                    newRow["TO_DATA"] = PSNItem.GetToData();
1212

    
1213
                                    if (PSNItem.IsValid == "Keyword")
1214
                                        PSNItem.EndType = PSNType.Equipment;
1215

    
1216
                                    newRow["Type"] = PSNItem.GetPSNType();
1217

    
1218
                                    newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1219
                                    newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
1220
                                    
1221
                                    newRow["IsValid"] = PSNItem.IsValid;
1222
                                    newRow["Status"] = !string.IsNullOrEmpty(PSNItem.Status) ? PSNItem.Status.Remove(0, 2) : string.Empty;
1223
                                    newRow["PBS"] = PSNItem.GetPBSData();
1224
                                  
1225
                                    List<string> drawingNames = new List<string>();
1226
                                    foreach (Group _group in PSNItem.Groups)
1227
                                    {
1228
                                        if (!drawingNames.Contains(_group.Document.DrawingName))
1229
                                        {
1230
                                            if (drawingNames.Count == 0)
1231
                                                newRow["Drawings"] = _group.Document.DrawingName;
1232
                                            else
1233
                                                newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
1234
                                            drawingNames.Add(_group.Document.DrawingName);
1235
                                        }
1236
                                    }
1237
                                    newRow["IncludingVirtualData"] = "No";
1238
                                    newRow["PSNAccuracy"] = "100";
1239
                                    pipeSystemNetworkDT.Rows.Add(newRow);
1240
                                }
1241
                            }
1242
                        }
1243
                    }
1244
                    catch(Exception ex)
1245
                    {
1246
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1247
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1248
                    }
1249

    
1250
                    //TopologySet 관련
1251
                    foreach (Topology topology in PSNItem.Topologies)
1252
                    {
1253
                        DataRow newRow = topologySetDT.NewRow();
1254
                        newRow["OID"] = topology.FullName;
1255
                        newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
1256
                        if (bVentDrain)
1257
                            newRow["SubType"] = "Vent_Drain";
1258
                        else
1259
                            newRow["SubType"] = null;
1260
                        newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
1261
                        newRow["TailItemTag"] = GetItemTag(topology.Items.First());
1262
                        newRow["HeadItemSPID"] = topology.Items.Last().UID;
1263
                        newRow["TailItemSPID"] = topology.Items.First().UID;
1264
                        topologySetDT.Rows.Add(newRow);
1265
                    }
1266
                }
1267

    
1268
                foreach (var item in startBranchDic)
1269
                {
1270
                    string uid = item.Key.UID;
1271
                    string topologyName = item.Value.Topology.FullName;
1272
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1273
                    if (rows.Length == 1)
1274
                    {
1275
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1276
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1277
                    }
1278
                    else if (rows.Length > 1)
1279
                    {
1280
                        DataRow targetRow = null;
1281
                        int index = int.MaxValue;
1282
                        foreach (DataRow row in rows)
1283
                        {
1284
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1285
                            if (split.StartsWith("L"))
1286
                            {
1287
                                int num = Convert.ToInt32(split.Remove(0, 1));
1288
                                if (index > num)
1289
                                {
1290
                                    index = num;
1291
                                    targetRow = row;
1292
                                }
1293
                            }
1294
                        }
1295

    
1296
                        if (targetRow != null)
1297
                        {
1298
                            targetRow["BranchTopologySet_OID"] = topologyName;
1299
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1300
                        }
1301
                    }
1302
                }
1303
                foreach (var item in endBranchDic)
1304
                {
1305
                    string uid = item.Key.UID;
1306
                    string topologyName = item.Value.Topology.FullName;
1307
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1308
                    if (rows.Length == 1)
1309
                    {
1310
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1311
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1312
                    }
1313
                    else if (rows.Length > 1)
1314
                    {
1315
                        DataRow targetRow = null;
1316
                        int index = int.MinValue;
1317
                        foreach (DataRow row in rows)
1318
                        {
1319
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1320
                            if (split.StartsWith("L"))
1321
                            {
1322
                                int num = Convert.ToInt32(split.Remove(0, 1));
1323
                                if (index < num)
1324
                                {
1325
                                    index = num;
1326
                                    targetRow = row;
1327
                                }
1328
                            }
1329
                        }
1330

    
1331
                        if (targetRow != null)
1332
                        {
1333
                            targetRow["BranchTopologySet_OID"] = topologyName;
1334
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1335
                        }
1336
                    }
1337
                }
1338

    
1339
                PathItems = pathItemsDT;
1340
                SequenceData = sequenceDataDT;
1341
                PipeSystemNetwork = pipeSystemNetworkDT;
1342
                TopologySet = topologySetDT;
1343
            }
1344
            catch (Exception ex)
1345
            {
1346
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1347
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1348
            }
1349
        }
1350

    
1351
        private double AccuracyCalculation(List<double> lstAcc, double acc)
1352
        {
1353
            foreach(double lacc in lstAcc)
1354
            {
1355
                acc *= lacc;
1356
            }
1357
            acc = acc;
1358
            return acc;
1359
        }
1360

    
1361
        private void UpdateSubType()
1362
        {
1363
            try
1364
            {
1365

    
1366

    
1367
                foreach (PSNItem PSNItem in PSNItems)
1368
                {
1369
                    if (PSNItem.IsBypass)
1370
                    {
1371
                        foreach (Topology topology in PSNItem.Topologies)
1372
                        {
1373
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1374
                            if (rows.Length.Equals(1))
1375
                                rows.First()["SubType"] = "Bypass";
1376
                        }
1377
                    }
1378

    
1379
                    if (PSNItem.StartType == PSNType.Header)
1380
                    {
1381
                        Topology topology = PSNItem.Topologies.First();
1382
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1383
                        if (rows.Length.Equals(1))
1384
                            rows.First()["SubType"] = "Header";
1385
                    }
1386
                    else if (PSNItem.EndType == PSNType.Header)
1387
                    {
1388
                        Topology topology = PSNItem.Topologies.Last();
1389
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1390
                        if (rows.Length.Equals(1))
1391
                            rows.First()["SubType"] = "Header";
1392
                    }
1393
                }
1394

    
1395

    
1396
                foreach (Topology topology in Topologies)
1397
                {
1398
                    try
1399
                    {
1400
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1401
                        if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
1402
                        {
1403
                            if (topology.Items == null)
1404
                                continue;
1405

    
1406
                            Item firstItem = topology.Items.First();
1407
                            Item lastItem = topology.Items.Last();
1408

    
1409
                            List<Relation> relations = new List<Relation>();
1410
                            
1411
                            if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1412
                                relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1413

    
1414
                            if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1415
                                relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1416

    
1417
                            if (relations.Count > 0)
1418
                                rows.First()["SubType"] = "OtherSystem";
1419
                        }
1420
                    }
1421
                    catch (Exception ex)
1422
                    {
1423
                       
1424
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1425
                    }
1426
                }
1427

    
1428
                    foreach (DataRow row in TopologySet.Rows)
1429
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
1430
                        row["SubType"] = "Normal";
1431
            }
1432
            catch (Exception ex)
1433
            {
1434
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1435
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1436
            }
1437
        }
1438

    
1439
        private bool IsBypass(PSNItem PSNItem)
1440
        {
1441
            bool bResult = false;
1442

    
1443
            if (PSNItem.GetPSNType() == "B2B")
1444
            {
1445
                Group firstGroup = PSNItem.Groups.First();
1446
                Group lastGroup = PSNItem.Groups.Last();
1447
                Item firstItem = firstGroup.Items.First();
1448
                Item lastItem = lastGroup.Items.Last();
1449

    
1450
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
1451
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
1452

    
1453
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
1454
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
1455
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
1456
                    bResult = true;
1457
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
1458
                    bResult = true;
1459
            }
1460

    
1461
            Item GetConnectedItemByPSN(Item item)
1462
            {
1463
                Item result = null;
1464

    
1465
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
1466
                if (relation != null)
1467
                    result = relation.Item;
1468

    
1469
                return result;
1470
            }
1471

    
1472
            return bResult;
1473
        }
1474

    
1475
        private void UpdateAccuracy()
1476
        {
1477
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
1478
            List<double> lstAcc = null;
1479
            string Status = string.Empty;
1480
            foreach (DataRow dataRow in statusRows)
1481
            {
1482
                lstAcc = new List<double>();
1483
                Status = dataRow.Field<string>("Status");
1484

    
1485
                if (!string.IsNullOrEmpty(Status))
1486
                {
1487
                    if (Status.Contains(Rule1)) //Line Disconnected
1488
                        lstAcc.Add(0.75);
1489
                    else if (Status.Contains(Rule2)) //Missing LineNumber
1490
                        lstAcc.Add(0.7);            
1491
                    else if (Status.Contains(Rule3)) //OPC Disconneted
1492
                        lstAcc.Add(0.7);            
1493
                    else if (Status.Contains(Rule4)) //Missing ItemTag or Description
1494
                        lstAcc.Add(0.65);           
1495
                    //else if (Status.Contains(Rule5))
1496
                    //    lstAcc.Add(0.6);
1497
                }
1498

    
1499
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
1500
                if (PSNAccuracy == "100")
1501
                    PSNAccuracy = "1";
1502

    
1503
                PSNAccuracy = Convert.ToString(Math.Round(Convert.ToDouble(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))), 2));
1504
                if (PSNAccuracy != "100")
1505
                {
1506
                    dataRow["IncludingVirtualData"] = "Yes";
1507
                    dataRow["PSNAccuracy"] = PSNAccuracy;
1508
                }
1509
            }
1510
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
1511
            foreach (DataRow dr in dt.Rows)
1512
            {
1513
                string oid = dr.Field<string>("OID");
1514
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
1515
                double totalDdr = 0;
1516
                foreach (DataRow ddr in select)
1517
                {
1518
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
1519
                    if (acc == 100) acc = 1;
1520
                    if (totalDdr == 0) totalDdr = acc;
1521
                    else totalDdr *= acc;
1522
                }
1523

    
1524
                totalDdr *= 100;
1525

    
1526
                foreach (DataRow ddr in select)
1527
                {
1528
                    ddr["IncludingVirtualData"] = "Yes";
1529
                    ddr["PSNAccuracy"] = totalDdr;
1530
                }
1531
            }
1532

    
1533
        }
1534

    
1535
        private void UpdateErrorForPSN()
1536
        {
1537
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
1538
            bool bCheckRule5 = false;
1539
            foreach (DataRow dataRow in errorRows)
1540
            {
1541
                try
1542
                {
1543
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
1544
                    bool change = false;
1545
                    bCheckRule5 = false;
1546

    
1547
                    if (!PSNItem.EnableType(PSNItem.StartType))
1548
                    {
1549
                        change = true;
1550
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1551
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
1552

    
1553
                        Item item = PSNItem.Groups.First().Items.First();
1554
                        try
1555
                        { 
1556
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
1557
                                loopRow["FROM_DATA"] = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
1558
                            tieInPointIndex++;
1559

    
1560

    
1561
                            if (item.ItemType == ItemType.Line)
1562
                            {
1563
                                //createTerminatorRow - Rule 5번
1564
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First()), insertIndex);
1565

    
1566
                                bCheckRule5 = true;
1567
                            }
1568
                            else
1569
                            {
1570
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
1571
                                //createTerminatorRow - Rule 5번
1572
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First()), insertIndex);
1573

    
1574
                                bCheckRule5 = true;
1575
                            }
1576

    
1577
                            PSNItem.StartType = PSNType.Equipment;
1578
                        }
1579
                        catch (Exception ex)
1580
                        {
1581
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
1582
                            return;
1583
                        }
1584
                    }
1585

    
1586

    
1587
                    if (!PSNItem.EnableType(PSNItem.EndType))
1588
                    {
1589
                        change = true;
1590
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1591
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.Last());
1592
                        Item item = PSNItem.Groups.Last().Items.Last();
1593
                        try
1594
                        {                           
1595
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
1596
                                loopRow["TO_DATA"] = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
1597
                            tieInPointIndex++;
1598

    
1599

    
1600
                            if (item.ItemType == ItemType.Line)
1601
                            {
1602
                                //createTerminatorRow - Rule 5번
1603
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last()), insertIndex + 1);
1604

    
1605
                                bCheckRule5 = true;
1606
                            }
1607
                            else
1608
                            {
1609
                                //createTerminatorRow - Rule 5번
1610
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last()), insertIndex + 1);
1611
                                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);
1612

    
1613
                                bCheckRule5 = true;
1614
                            }
1615

    
1616
                            PSNItem.EndType = PSNType.Equipment;
1617
                        }
1618
                        catch(Exception ex)
1619
                        {
1620
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
1621
                            return;
1622
                        }
1623
                    }
1624

    
1625
                    dataRow["Type"] = PSNItem.GetPSNType();
1626
                    if (change)
1627
                    {
1628
                        int rowIndex = 0;
1629
                        for (int i = 0; i < PathItems.Rows.Count; i++)
1630
                        {
1631
                            DataRow row = PathItems.Rows[i];
1632
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
1633
                                continue;
1634
                            string sequenceData = row["SequenceData_OID"].ToString();
1635
                            string[] split = sequenceData.Split(new char[] { '_' });
1636

    
1637
                            StringBuilder sb = new StringBuilder();
1638
                            for (int j = 0; j < split.Length - 1; j++)
1639
                                sb.Append(split[j] + "_");
1640
                            sb.Append(rowIndex++);
1641
                            row["SequenceData_OID"] = sb.ToString();
1642
                        }
1643
                    }
1644

    
1645
                    if (bCheckRule5)
1646
                    {                       
1647
                        string PSNAccuracy = "0.6";
1648
                        dataRow["IncludingVirtualData"] = "Yes";
1649
                        dataRow["PSNAccuracy"] = PSNAccuracy;
1650
                       
1651
                    }
1652

    
1653
                    DataRow createTerminatorRow(DataRow itemRow)
1654
                    {
1655
                        DataRow newRow = PathItems.NewRow();
1656
                        newRow["OID"] = Guid.NewGuid().ToString();
1657
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
1658
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
1659
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
1660
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
1661
                        newRow["ITEMNAME"] = "End of line terminator";
1662
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
1663
                        newRow["Class"] = "End of line terminator";
1664
                        newRow["SubClass"] = "End of line terminator";
1665
                        newRow["TYPE"] = "End of line terminator";
1666
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
1667
                        newRow["NPD"] = itemRow["NPD"];
1668
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
1669
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
1670
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
1671

    
1672
                        return newRow;
1673
                    }
1674

    
1675
                    DataRow createLineRow(DataRow itemRow)
1676
                    {
1677
                        DataRow newRow = PathItems.NewRow();
1678
                        newRow["OID"] = Guid.NewGuid().ToString();
1679
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
1680
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
1681
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
1682
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
1683
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
1684
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
1685
                        newRow["Class"] = itemRow["Class"];
1686
                        newRow["SubClass"] = itemRow["SubClass"];
1687
                        newRow["TYPE"] = itemRow["TYPE"];
1688
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
1689
                        newRow["NPD"] = itemRow["NPD"];
1690
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
1691
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
1692
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
1693

    
1694
                        return newRow;
1695
                    }
1696
                }
1697
                catch(Exception ex)
1698
                {
1699

    
1700
                }
1701
            }
1702
        }
1703
    }
1704

    
1705
    public class PSNItem
1706
    {
1707
        public PSNItem(int count, int Revision)
1708
        {
1709
            Groups = new List<Group>();
1710
            Topologies = new List<Topology>();
1711

    
1712
            Index = count + 1;
1713
            this.Revision = Revision;
1714
        }
1715

    
1716
        private int Revision;
1717
        public string UID { get; set; }
1718
        public List<Group> Groups { get; set; }
1719
        public List<Topology> Topologies { get; set; }
1720
        public PSNType StartType { get; set; }
1721
        public PSNType EndType { get; set; }
1722
        public int Index { get; set; }
1723
        public string IsValid { get; set; }
1724
        public string Status { get; set; }
1725
        public string IncludingVirtualData { get; set; }
1726
        public string PSNAccuracy { get; set; }
1727
        public KeywordInfo KeywordInfos = new KeywordInfo();
1728

    
1729
        public string PSN_OID()
1730
        {
1731
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
1732
        }
1733
        public string GetPSNType()
1734
        {
1735
            string result = string.Empty;
1736

    
1737
            if (EnableType(StartType) && EnableType(EndType))
1738
            {
1739
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
1740
                    result = "E2E";
1741
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
1742
                    result = "B2B";
1743
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
1744
                    result = "HD2";
1745

    
1746
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
1747
                    result = "E2B";
1748
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
1749
                    result = "B2E";
1750

    
1751
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
1752
                    result = "HDB";
1753
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
1754
                    result = "HDB";
1755

    
1756
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
1757
                    result = "HDE";
1758
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
1759
                    result = "HDE";
1760
                else
1761
                    result = "Error";
1762
            }
1763
            else
1764
                result = "Error";
1765

    
1766
            return result;
1767

    
1768
            
1769
        }
1770
        public bool EnableType(PSNType type)
1771
        {
1772
            bool result = false;
1773

    
1774
            if (type == PSNType.Branch ||
1775
                type == PSNType.Equipment ||
1776
                type == PSNType.Header)
1777
            {
1778
                result = true;
1779
            }
1780

    
1781
            return result;
1782
        }
1783
        public bool IsBypass { get; set; }
1784

    
1785
        public string GetFromData()
1786
        {
1787
            string result = string.Empty;
1788
            if (IsValid == "Keyword")
1789
                IsValid = string.Empty;
1790
            try
1791
            {
1792
                if (StartType == PSNType.Header)
1793
                    result = "ENDOFHEADER";
1794
                else if (StartType == PSNType.Branch)
1795
                {
1796
                    Item item = Groups.First().Items.First();
1797
                    if (item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
1798
                        result = item.Relations.First().Item.LineNumber.Name;
1799
                    else
1800
                    {
1801
                        Status += ", Missing LineNumber";
1802
                        result = "Empty LineNumber";
1803
                    }
1804
                }
1805
                else if (StartType == PSNType.Equipment)
1806
                    result = Groups.First().Items.First().Equipment.ItemTag;
1807
                else
1808
                {
1809
                    IsValid = "Error";
1810
                    Item item = Groups.First().Items.First();
1811
                    if (item.ItemType == ItemType.Symbol)
1812
                    {
1813

    
1814
                        string keyword = string.Empty;
1815
                        keyword = GetFromKeywordData();
1816

    
1817
                        if (string.IsNullOrEmpty(keyword))
1818
                        {
1819
                            if (item.ID2DBType.Contains("OPC's"))
1820
                                Status += ", OPC Disconneted";
1821
                            else
1822
                                Status += ", Missing ItemTag or Description";
1823

    
1824
                            result = item.ID2DBName;
1825
                        }
1826
                        else
1827
                        {
1828
                            result = keyword;
1829
                            IsValid = "Keyword";
1830
                        }
1831
                        
1832
                    }
1833
                    else if (item.ItemType == ItemType.Line)
1834
                    {
1835
                        Status += ", Line Disconnected";
1836
                        result = item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
1837
                    }
1838
                    else
1839
                        result = "Unknown";
1840
                }
1841
            }
1842
            catch(Exception ex)
1843
            {
1844

    
1845
            }
1846

    
1847
            return result;
1848
        }
1849

    
1850
        public string GetFromKeywordData()
1851
        {
1852
            string result = string.Empty;
1853
           
1854
            Item item = Groups.First().Items.First();
1855

    
1856
            foreach(KeywordItem keyitem in KeywordInfos.KeywordItems)
1857
            {
1858
                if(keyitem.Name.Equals(item.Name))
1859
                    result = keyitem.Keyword;
1860
            }
1861
          
1862
            return result;
1863
        }
1864

    
1865
        public string GetToKeywordData()
1866
        {
1867
            string result = string.Empty;
1868

    
1869
            Item item = Groups.Last().Items.Last();
1870
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
1871
            {
1872
                if (keyitem.Name.Equals(item.Name))
1873
                    result = keyitem.Keyword;
1874
            }
1875
            return result;
1876
        }
1877

    
1878
        public string GetToData()
1879
        {
1880
            string result = string.Empty;
1881
            if(IsValid == "Keyword")
1882
                IsValid = string.Empty;
1883

    
1884
            if (EndType == PSNType.Header)
1885
                result = "ENDOFHEADER";
1886
            else if (EndType == PSNType.Branch)
1887
            {
1888
                Item item = Groups.Last().Items.Last();
1889
                if (item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
1890
                    result = item.Relations.Last().Item.LineNumber.Name;
1891
                else
1892
                {
1893
                    Status += ", Missing LineNumber";
1894
                    result = "Empty LineNumber";
1895
                }
1896
            }
1897
            else if (EndType == PSNType.Equipment)
1898
                result = Groups.Last().Items.Last().Equipment.ItemTag;
1899
            else
1900
            {
1901
                IsValid = "Error";
1902
                Item item = Groups.Last().Items.Last();
1903
                if (item.ItemType == ItemType.Symbol)
1904
                {
1905
                    string keyword = string.Empty;
1906
                    keyword = GetToKeywordData();
1907

    
1908
                    if (string.IsNullOrEmpty(keyword))
1909
                    {
1910
                        if (item.ID2DBType.Contains("OPC's"))
1911
                            Status += ", OPC Disconneted";
1912
                        else
1913
                            Status += ", Missing ItemTag or Description";
1914

    
1915
                        result = item.ID2DBName;
1916
                    }
1917
                    else
1918
                    {
1919
                        result = keyword;
1920
                        IsValid = "Keyword";
1921
                    }
1922
                    
1923
                }
1924
                else if (item.ItemType == ItemType.Line)
1925
                {
1926
                    Status += ", Line Disconnected";
1927
                    result = item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
1928
                }
1929
                else
1930
                    result = "Unknown";
1931
            }
1932
            return result;
1933
        }
1934

    
1935
        public string GetPBSData()
1936
        {
1937
            string result = string.Empty;
1938
            List<string> PBSList = new List<string>();
1939
            if (Settings.Default.PBSSetting.Equals("Line Number"))
1940
            {
1941
                string attrValue = Settings.Default.PBSSettingValue;
1942

    
1943
                foreach (Group group in Groups)
1944
                {
1945
                    List<LineNumber> lineNumbers = group.Items.Select(x =>x.LineNumber).Distinct().ToList();
1946
                    foreach (LineNumber lineNumber in lineNumbers)
1947
                    {
1948
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
1949
                        if (attribute != null)
1950
                        {
1951
                            string value = attribute.Value;
1952
                            if (!PBSList.Contains(value))
1953
                                PBSList.Add(value);
1954
                        }
1955
                    }
1956
                }
1957
            }
1958
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
1959
            {
1960
                string attrValue = Settings.Default.PBSSettingValue;
1961

    
1962
                foreach (Group group in Groups)
1963
                {
1964
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
1965
                    foreach (Item item in items)
1966
                    {
1967
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
1968
                        if (!PBSList.Contains(value))
1969
                            PBSList.Add(value);
1970
                    }
1971
                }
1972
            }
1973
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
1974
            {
1975
                string attrValue = Settings.Default.PBSSettingValue;
1976

    
1977
                foreach (Group group in Groups)
1978
                {
1979
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
1980
                    foreach (Document document in documents)
1981
                    {
1982
                        string name = document.DrawingName;
1983

    
1984
                        int startIndex = Settings.Default.PBSSettingStartValue;
1985
                        int endIndex = Settings.Default.PBSSettingEndValue;
1986

    
1987
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
1988
                        if (!PBSList.Contains(subStr))
1989
                            PBSList.Add(subStr);
1990
                    }
1991
                }
1992
            }
1993
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
1994
            {
1995
                foreach (Group group in Groups)
1996
                {
1997
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
1998
                    foreach (Document document in documents)
1999
                    {
2000
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
2001
                        foreach (TextInfo textInfo in textInfos)
2002
                        {
2003
                            if (!PBSList.Contains(textInfo.Value))
2004
                                PBSList.Add(textInfo.Value);
2005
                        }
2006
                    }
2007
                }
2008
            }
2009

    
2010
            foreach (var item in PBSList)
2011
            {
2012
                if (string.IsNullOrEmpty(result))
2013
                    result = item;
2014
                else
2015
                    result += ", " + item;
2016
            }
2017
            return result;
2018
        }
2019
    }
2020
}