프로젝트

일반

사용자정보

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

hytos / DTI_PID / ID2PSN / PSN.cs @ 27d06aa8

이력 | 보기 | 이력해설 | 다운로드 (83 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
        const string FluidPriorityType = "FLUIDCODE";
64
        const string PipingMaterialsPriorityType = "PIPINGMATERIALSCLASS";
65

    
66
        public PSN()
67
        {
68
            
69
        }
70

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

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

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

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

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

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

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

    
255
                            item.Owner = prevLineNumber.UID;
256
                        }
257
                    }
258
                    else
259
                        prevLineNumber = lineNumber;
260
                }
261

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

    
277
                            item.Owner = prevLineNumber.UID;
278
                        }
279
                    }
280
                    else
281
                        prevLineNumber = lineNumber;
282
                }
283

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

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

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

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

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

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

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

    
351
        }
352

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

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

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

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

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

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

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

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

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

    
459
                PSNItem.Groups.Clear();
460
                PSNItem.Groups.AddRange(_groups);
461
            }
462

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

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

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

    
484
                Item firstItem = firstGroup.Items.First();
485
                Item lastItem = lastGroup.Items.Last();
486

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

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

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

    
525
                return type;
526
            }
527
        }
528

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

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

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

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

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

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

    
597
                                        if (!PSNItem.Topologies.Contains(topology))
598
                                            PSNItem.Topologies.Add(topology);
599
                                    }
600
                                }
601

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

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

    
617

    
618
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
619

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

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

    
644
        }
645

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

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

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

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

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

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

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

    
699

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

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

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

    
738
                    if (result.Count > 0)
739
                        break;
740
                }
741

    
742
                return result;
743
            }
744

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

    
767
                    if (result.Count > 0)
768
                        break;
769
                }
770

    
771
                return result;
772
            }
773

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

    
779
            return main;
780
        }
781

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

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

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

    
817
                        dt.Rows.Add(newRow);
818
                    }
819
                }
820
            }
821

    
822
            return dt;
823
        }
824

    
825
        private DataTable GetTopologyRule()
826
        {
827
            DataTable dt = DB.SelectTopologyRule();
828

    
829
            return dt;
830
        }
831

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

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

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

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

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

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

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

    
896
                nozzleDT.Rows.Add(row);
897
            }
898

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

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

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

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

    
925
                equipDT.Rows.Add(row);
926
            }
927

    
928
            Equipment = equipDT;
929
            Nozzle = nozzleDT;
930
        }
931

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

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

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

    
975
                DataTable topologySetDT = new DataTable();
976
                topologySetDT.Columns.Add("OID", typeof(string));
977
                topologySetDT.Columns.Add("Type", typeof(string));
978
                topologySetDT.Columns.Add("SubType", typeof(string));
979
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
980
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
981
                topologySetDT.Columns.Add("HeadItemID", typeof(string));
982
                topologySetDT.Columns.Add("TailItemID", typeof(string));
983

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

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

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

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

    
1020
                    KeywordInfo keywordInfo = KeywordInfos.Find(x => x.UID.Equals(groupID));
1021
                    if (keywordInfo == null)
1022
                    {
1023
                        keywordInfo = new KeywordInfo(groupID);
1024
                        keywordInfo.Description = desc;
1025
                        KeywordInfos.Add(keywordInfo);
1026
                    }
1027

    
1028
                    keywordInfo.KeywordItems.Add(new KeywordItem()
1029
                    {
1030
                        Index = index,
1031
                        Name = name,
1032
                        Keyword = keyword
1033
                    });
1034
                }               
1035
                #endregion
1036

    
1037
                // key = 미입력 branch
1038
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
1039
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
1040
                foreach (PSNItem PSNItem in PSNItems)
1041
                {
1042
                    int psnOrder = 0;
1043
                    int index = 0;
1044
                    bool bPSNStart = true;
1045
                    string sPSNData = string.Empty;
1046
                    bool bVentDrain = false;
1047

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

    
1066
                                if (i + 1 == group.Items.Count && group.Items.Count.Equals(ventDrainInfo.VentDrainItems.Count))
1067
                                    bVentDrain = true;
1068
                            }
1069
                        }
1070

    
1071
                        if (!bVentDrain)
1072
                        {
1073
                            endInfos = new List<VentDrainInfo>();
1074
                            for (int i = 0; i < group.Items.Count; i++)
1075
                            {
1076
                                Item item = group.Items[group.Items.Count - i - 1];
1077
                                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1078
                                {
1079
                                    if (endInfos.Contains(ventDrainInfo) || ventDrainInfo.VentDrainItems.Count != group.Items.Count)
1080
                                        continue;
1081
                                    if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1082
                                    {
1083
                                        endInfos.Add(ventDrainInfo);
1084
                                        continue;
1085
                                    }
1086

    
1087
                                    if (i + 1 == group.Items.Count && group.Items.Count.Equals(ventDrainInfo.VentDrainItems.Count))
1088
                                        bVentDrain = true;
1089
                                }
1090
                            }
1091
                        }
1092
                    }
1093

    
1094
                    foreach (KeywordInfo keywordInfo in KeywordInfos)
1095
                        keywordInfo.KeywordItems = keywordInfo.KeywordItems.OrderBy(x => x.Index).ToList();
1096

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

    
1121
                                        CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
1122
                                        CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
1123
                                        index++;
1124

    
1125
                                        if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
1126
                                            startBranchDic.Add(item.BranchItems[i], item);
1127
                                        else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
1128
                                            endBranchDic.Add(item.BranchItems[i], item);
1129
                                    }
1130
                                }
1131

    
1132
                                if (bPSNStart)
1133
                                {
1134
                                    CreatePipeSystemNetworkDataRow();
1135
                                    sPSNData = item.TopologyData;
1136
                                    psnOrder++;
1137
                                    bPSNStart = false;
1138
                                }
1139
                                else
1140
                                {
1141
                                    if (item.TopologyData != sPSNData)
1142
                                    {
1143
                                        CreatePipeSystemNetworkDataRow();
1144
                                        sPSNData = item.TopologyData;
1145
                                        psnOrder++;
1146
                                    }
1147
                                }
1148
                                void CreatePathItemsDataRow(string itemOID, string itemType, string branchTopologyName = "", Item branchItem = null)
1149
                                {
1150
                                    DataRow newRow = pathItemsDT.NewRow();
1151
                                    newRow["OID"] = itemOID;
1152

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

    
1155
                                    newRow["TopologySet_OID"] = item.Topology.FullName;
1156

    
1157
                                    newRow["BranchTopologySet_OID"] = branchTopologyName;
1158
                                    newRow["PipeLine_OID"] = item.PSNPipeLineID;
1159
                                    newRow["ITEMNAME"] = GetItemName(item, itemOID);
1160
                                    newRow["ITEMTAG"] = GetItemTag(item);
1161
                                    newRow["Class"] = GetClass(item, itemOID);
1162
                                    newRow["SubClass"] = GetSubClass(item, itemOID);
1163

    
1164
                                    if (item.ItemType == ItemType.Symbol)
1165
                                        newRow["TYPE"] = item.ID2DBName;
1166
                                    else if (item.ItemType == ItemType.Line)
1167
                                        newRow["TYPE"] = item.ID2DBType;
1168
                                    newRow["PIDNAME"] = group.Document.DrawingName;
1169

    
1170
                                    // NPD
1171
                                    if (item.LineNumber != null)
1172
                                    {
1173
                                        Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1174
                                        if (attribute != null)
1175
                                            newRow["NPD"] = attribute.Value;
1176
                                    }
1177
                                    else
1178
                                        newRow["NPD"] = null;
1179

    
1180

    
1181
                                    newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1182
                                    if (branchItem == null)
1183
                                        newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1184
                                    else
1185
                                        newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
1186

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

    
1189
                                    pathItemsDT.Rows.Add(newRow);
1190
                                }
1191
                                void CreateSequenceDataDataRow(string itemOID)
1192
                                {
1193
                                    DataRow newRow = sequenceDataDT.NewRow();
1194
                                    newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1195
                                    newRow["SERIALNUMBER"] = string.Format("{0}", index);
1196
                                    newRow["PathItem_OID"] = itemOID;
1197
                                    newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1198

    
1199
                                    sequenceDataDT.Rows.Add(newRow);
1200
                                }
1201
                                void CreatePipeSystemNetworkDataRow()
1202
                                {
1203
                                    // VentDrain의 경우 제외 요청
1204
                                    if (bVentDrain)
1205
                                        return;
1206

    
1207
                                    DataRow newRow = pipeSystemNetworkDT.NewRow();
1208
                                    newRow["OID"] = PSNItem.PSN_OID();
1209
                                    newRow["Type"] = PSNItem.GetPSNType();
1210
                                    newRow["OrderNumber"] = psnOrder;
1211
                                    newRow["Pipeline_OID"] = item.PSNPipeLineID;
1212

    
1213
                                    string From_d = string.Empty;
1214
                                    string To_d = string.Empty;
1215

    
1216
                                    From_d = PSNItem.GetFromData();
1217
                                    To_d = PSNItem.GetToData();
1218
                                    newRow["FROM_DATA"] = From_d;
1219
                                    newRow["TO_DATA"] = To_d;
1220

    
1221
                                    From_d = PSNItem.GetFromKeywordData();
1222
                                    To_d = PSNItem.GetToKeywordData();
1223

    
1224
                                    if (!string.IsNullOrEmpty(From_d))
1225
                                        newRow["FROM_DATA"] = From_d;
1226

    
1227
                                    if (!string.IsNullOrEmpty(To_d))
1228
                                        newRow["TO_DATA"] = To_d;
1229

    
1230
                                    newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1231
                                    newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
1232
                                    newRow["PBS"] = PSNItem.GetPBSData();
1233
                                    newRow["Validity"] = PSNItem.Validity;
1234
                                    newRow["Status"] = !string.IsNullOrEmpty(PSNItem.Status) ? PSNItem.Status.Remove(0, 2) : string.Empty;
1235
                                    newRow["IncludingVirtualData"] = "No";
1236

    
1237
                                    newRow["PSNAccuracy"] = "100";
1238

    
1239
                                    List<string> drawingNames = new List<string>();
1240
                                    foreach (Group _group in PSNItem.Groups)
1241
                                    {
1242
                                        if (!drawingNames.Contains(_group.Document.DrawingName))
1243
                                        {
1244
                                            if (drawingNames.Count == 0)
1245
                                                newRow["PIDDrawings"] = _group.Document.DrawingName;
1246
                                            else
1247
                                                newRow["PIDDrawings"] = newRow["PIDDrawings"] + ", " + _group.Document.DrawingName;
1248
                                            drawingNames.Add(_group.Document.DrawingName);
1249
                                        }
1250
                                    }
1251

    
1252
                                    pipeSystemNetworkDT.Rows.Add(newRow);
1253
                                }
1254
                            }
1255
                        }
1256
                    }
1257
                    catch(Exception ex)
1258
                    {
1259
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1260
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1261
                    }
1262

    
1263
                    //TopologySet 관련
1264
                    foreach (Topology topology in PSNItem.Topologies)
1265
                    {
1266
                        DataRow newRow = topologySetDT.NewRow();
1267
                        newRow["OID"] = topology.FullName;
1268
                        newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
1269
                        if (bVentDrain)
1270
                            newRow["SubType"] = "Vent_Drain";
1271
                        else
1272
                            newRow["SubType"] = null;
1273
                        newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
1274
                        newRow["TailItemTag"] = GetItemTag(topology.Items.First());
1275
                        newRow["HeadItemID"] = topology.Items.Last().UID;
1276
                        newRow["TailItemID"] = topology.Items.First().UID;
1277
                        topologySetDT.Rows.Add(newRow);
1278
                    }
1279
                }
1280

    
1281
                foreach (var item in startBranchDic)
1282
                {
1283
                    string uid = item.Key.UID;
1284
                    string topologyName = item.Value.Topology.FullName;
1285
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1286
                    if (rows.Length == 1)
1287
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1288
                    else if (rows.Length > 1)
1289
                    {
1290
                        DataRow targetRow = null;
1291
                        int index = int.MaxValue;
1292
                        foreach (DataRow row in rows)
1293
                        {
1294
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1295
                            if (split.StartsWith("L"))
1296
                            {
1297
                                int num = Convert.ToInt32(split.Remove(0, 1));
1298
                                if (index > num)
1299
                                {
1300
                                    index = num;
1301
                                    targetRow = row;
1302
                                }
1303
                            }
1304
                        }
1305

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

    
1335
                        if (targetRow != null)
1336
                            targetRow["BranchTopologySet_OID"] = topologyName;
1337
                    }
1338
                }
1339

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

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

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

    
1367

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

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

    
1396

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

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

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

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

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

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

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

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

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

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

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

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

    
1470
                return result;
1471
            }
1472

    
1473
            return bResult;
1474
        }
1475

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

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

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

    
1504
                PSNAccuracy = Convert.ToString(Math.Round(Convert.ToDouble(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))), 2));
1505
                if (PSNAccuracy != "100")
1506
                {
1507
                    dataRow["IncludingVirtualData"] = "Yes";
1508
                    dataRow["PSNAccuracy"] = PSNAccuracy;
1509
                }
1510
            }
1511
        }
1512

    
1513
        private void UpdateErrorForPSN()
1514
        {
1515
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
1516
            bool bCheckRule5 = false;
1517
            foreach (DataRow dataRow in errorRows)
1518
            {
1519
                PSNItem PSNItem = PSNItems.Find(x=>x.PSN_OID() == dataRow["OID"].ToString());
1520
                bool change = false;
1521
                bCheckRule5 = false;
1522

    
1523
                if (!PSNItem.EnableType(PSNItem.StartType))
1524
                {
1525
                    change = true;
1526
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1527
                    int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
1528

    
1529
                    Item item = PSNItem.Groups.First().Items.First();
1530
                    foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
1531
                        loopRow["FROM_DATA"] = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
1532
                    tieInPointIndex++;
1533

    
1534
                    
1535
                    if (item.ItemType == ItemType.Line)
1536
                    {
1537
                        //createTerminatorRow - Rule 5번
1538
                        PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First()), insertIndex);
1539

    
1540
                        bCheckRule5 = true;
1541
                    }
1542
                    else
1543
                    {
1544
                        PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
1545
                        //createTerminatorRow - Rule 5번
1546
                        PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First()), insertIndex);
1547

    
1548
                        bCheckRule5 = true;
1549
                    }
1550

    
1551
                    PSNItem.StartType = PSNType.Equipment;
1552
                }
1553

    
1554

    
1555
                if (!PSNItem.EnableType(PSNItem.EndType))
1556
                {
1557
                    change = true;
1558
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1559
                    int insertIndex = PathItems.Rows.IndexOf(pathItemRows.Last());
1560

    
1561
                    Item item = PSNItem.Groups.Last().Items.Last();
1562
                    foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
1563
                        loopRow["TO_DATA"] = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
1564
                    tieInPointIndex++;
1565

    
1566

    
1567
                    if (item.ItemType == ItemType.Line)
1568
                    {
1569
                        //createTerminatorRow - Rule 5번
1570
                        PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last()), insertIndex + 1);
1571

    
1572
                    }
1573
                    else
1574
                    {
1575
                        //createTerminatorRow - Rule 5번
1576
                        PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last()), insertIndex + 1);
1577

    
1578
                        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);
1579

    
1580
                        bCheckRule5 = true;
1581
                    }
1582

    
1583
                    PSNItem.EndType = PSNType.Equipment;
1584
                }
1585

    
1586
                dataRow["Type"] = PSNItem.GetPSNType();
1587
                if (change)
1588
                {
1589
                    int rowIndex = 0;
1590
                    foreach (DataRow row in PathItems.Rows)
1591
                    {
1592
                        if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
1593
                            continue;
1594
                        string sequenceData = row["SequenceData_OID"].ToString();
1595
                        string[] split = sequenceData.Split(new char[] { '_' });
1596

    
1597
                        StringBuilder sb = new StringBuilder();
1598
                        for (int i = 0; i < split.Length - 1; i++)
1599
                            sb.Append(split[i] + "_");
1600
                        sb.Append(rowIndex++);
1601
                        row["SequenceData_OID"] = sb.ToString(); 
1602
                    }
1603
                }
1604
                
1605
                if (bCheckRule5)
1606
                {
1607
                    string PSNAccuracy = "0.6";
1608
                    dataRow["IncludingVirtualData"] = "Yes";
1609
                    dataRow["PSNAccuracy"] = PSNAccuracy;
1610
                }
1611

    
1612
                DataRow createTerminatorRow(DataRow itemRow)
1613
                {
1614
                    DataRow newRow = PathItems.NewRow();
1615
                    newRow["OID"] = Guid.NewGuid().ToString();
1616
                    newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
1617
                    newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
1618
                    newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
1619
                    newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
1620
                    newRow["ITEMNAME"] = "End of line terminator";
1621
                    newRow["ITEMTAG"] = itemRow["ITEMTAG"];
1622
                    newRow["Class"] = "End of line terminator";
1623
                    newRow["SubClass"] = "End of line terminator";
1624
                    newRow["TYPE"] = "End of line terminator";
1625
                    newRow["PIDNAME"] = itemRow["PIDNAME"];
1626
                    newRow["NPD"] = itemRow["NPD"];
1627
                    newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
1628
                    newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
1629
                    newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
1630

    
1631
                    return newRow;
1632
                }
1633

    
1634
                DataRow createLineRow(DataRow itemRow)
1635
                {
1636
                    DataRow newRow = PathItems.NewRow();
1637
                    newRow["OID"] = Guid.NewGuid().ToString();
1638
                    newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
1639
                    newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
1640
                    newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
1641
                    newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
1642
                    newRow["ITEMNAME"] = itemRow["ITEMNAME"];
1643
                    newRow["ITEMTAG"] = itemRow["ITEMTAG"];
1644
                    newRow["Class"] = itemRow["Class"];
1645
                    newRow["SubClass"] = itemRow["SubClass"];
1646
                    newRow["TYPE"] = itemRow["TYPE"];
1647
                    newRow["PIDNAME"] = itemRow["PIDNAME"];
1648
                    newRow["NPD"] = itemRow["NPD"];
1649
                    newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
1650
                    newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
1651
                    newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
1652

    
1653
                    return newRow;
1654
                }
1655
            }            
1656
        }
1657
    }
1658

    
1659
    public class PSNItem
1660
    {
1661
        public PSNItem(int count, int Revision)
1662
        {
1663
            Groups = new List<Group>();
1664
            Topologies = new List<Topology>();
1665

    
1666
            Index = count + 1;
1667
            this.Revision = Revision;
1668
        }
1669
        private int Revision;
1670
        public string UID { get; set; }
1671
        public List<Group> Groups { get; set; }
1672
        public List<Topology> Topologies { get; set; }
1673
        public PSNType StartType { get; set; }
1674
        public PSNType EndType { get; set; }
1675
        public int Index { get; set; }
1676
        public string Validity { get; set; }
1677
        public string Status { get; set; }
1678
        public string IncludingVirtualData { get; set; }
1679
        public string PSNAccuracy { get; set; }
1680

    
1681
        public string PSN_OID()
1682
        {
1683
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
1684
        }
1685
        public string GetPSNType()
1686
        {
1687
            string result = string.Empty;
1688

    
1689
            if (EnableType(StartType) && EnableType(EndType))
1690
            {
1691
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
1692
                    result = "E2E";
1693
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
1694
                    result = "B2B";
1695
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
1696
                    result = "HD2";
1697

    
1698
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
1699
                    result = "E2B";
1700
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
1701
                    result = "B2E";
1702

    
1703
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
1704
                    result = "HDB";
1705
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
1706
                    result = "HDB";
1707

    
1708
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
1709
                    result = "HDE";
1710
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
1711
                    result = "HDE";
1712
                else
1713
                    result = "Error";
1714
            }
1715
            else
1716
                result = "Error";
1717

    
1718
            return result;
1719

    
1720
            
1721
        }
1722
        public bool EnableType(PSNType type)
1723
        {
1724
            bool result = false;
1725

    
1726
            if (type == PSNType.Branch ||
1727
                type == PSNType.Equipment ||
1728
                type == PSNType.Header)
1729
            {
1730
                result = true;
1731
            }
1732

    
1733
            return result;
1734
        }
1735
        public bool IsBypass { get; set; }
1736

    
1737
        public string GetFromData()
1738
        {
1739
            string result = string.Empty;
1740
            try
1741
            {
1742
                if (StartType == PSNType.Header)
1743
                    result = "ENDOFHEADER";
1744
                else if (StartType == PSNType.Branch)
1745
                {
1746
                    Item item = Groups.First().Items.First();
1747
                    if (item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
1748
                        result = item.Relations.First().Item.LineNumber.Name;
1749
                    else
1750
                    {
1751
                        Status += ", Missing LineNumber";
1752
                        result = "Empty LineNumber";
1753
                    }
1754
                }
1755
                else if (StartType == PSNType.Equipment)
1756
                    result = Groups.First().Items.First().Equipment.ItemTag;
1757
                else
1758
                {
1759
                    Validity = "Error";
1760
                    Item item = Groups.First().Items.First();
1761
                    if (item.ItemType == ItemType.Symbol)
1762
                    {
1763
                        if (item.ID2DBType.Contains("OPC's"))
1764
                            Status += ", OPC Disconneted";
1765
                        else
1766
                            Status += ", Missing ItemTag or Description";
1767

    
1768
                        result = item.ID2DBName;
1769
                    }
1770
                    else if (item.ItemType == ItemType.Line)
1771
                    {
1772
                        Status += ", Line Disconnected";
1773
                        result = item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
1774
                    }
1775
                    else
1776
                        result = "Unknown";
1777
                }
1778
            }
1779
            catch(Exception ex)
1780
            {
1781

    
1782
            }
1783

    
1784
            return result;
1785
        }
1786

    
1787
        public string GetFromKeywordData()
1788
        {
1789
            string result = string.Empty;
1790
           
1791
            Item item = Groups.First().Items.First();
1792
            if(!string.IsNullOrEmpty(item.Keyword))
1793
            {
1794
                result = item.Keyword;
1795
            }
1796
            return result;
1797
        }
1798

    
1799
        public string GetToKeywordData()
1800
        {
1801
            string result = string.Empty;
1802

    
1803
            Item item = Groups.Last().Items.Last();
1804
            if (!string.IsNullOrEmpty(item.Keyword))
1805
            {
1806
                result = item.Keyword;
1807
            }
1808
            return result;
1809
        }
1810

    
1811
        public string GetToData()
1812
        {
1813
            string result = string.Empty;
1814
            if (EndType == PSNType.Header)
1815
                result = "ENDOFHEADER";
1816
            else if (EndType == PSNType.Branch)
1817
            {
1818
                Item item = Groups.Last().Items.Last();
1819
                if (item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
1820
                    result = item.Relations.Last().Item.LineNumber.Name;
1821
                else
1822
                {
1823
                    Status += ", Missing LineNumber";
1824
                    result = "Empty LineNumber";
1825
                }
1826
            }
1827
            else if (EndType == PSNType.Equipment)
1828
                result = Groups.Last().Items.Last().Equipment.ItemTag;
1829
            else
1830
            {
1831
                Validity = "Error";
1832
                Item item = Groups.Last().Items.Last();
1833
                if (item.ItemType == ItemType.Symbol)
1834
                {
1835
                    if (item.ID2DBType.Contains("OPC's"))
1836
                        Status += ", OPC Disconneted";
1837
                    else
1838
                        Status += ", Missing ItemTag or Description";
1839
                    
1840
                    result = item.ID2DBName;
1841
                }
1842
                else if (item.ItemType == ItemType.Line)
1843
                {
1844
                    Status += ", Line Disconnected";
1845
                    result = item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
1846
                }
1847
                else
1848
                    result = "Unknown";
1849
            }
1850
            return result;
1851
        }
1852

    
1853
        public string GetPBSData()
1854
        {
1855
            string result = string.Empty;
1856
            List<string> PBSList = new List<string>();
1857
            if (Settings.Default.PBSSetting.Equals("Line Number"))
1858
            {
1859
                string attrValue = Settings.Default.PBSSettingValue;
1860

    
1861
                foreach (Group group in Groups)
1862
                {
1863
                    List<LineNumber> lineNumbers = group.Items.Select(x =>x.LineNumber).Distinct().ToList();
1864
                    foreach (LineNumber lineNumber in lineNumbers)
1865
                    {
1866
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
1867
                        if (attribute != null)
1868
                        {
1869
                            string value = attribute.Value;
1870
                            if (!PBSList.Contains(value))
1871
                                PBSList.Add(value);
1872
                        }
1873
                    }
1874
                }
1875
            }
1876
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
1877
            {
1878
                string attrValue = Settings.Default.PBSSettingValue;
1879

    
1880
                foreach (Group group in Groups)
1881
                {
1882
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
1883
                    foreach (Item item in items)
1884
                    {
1885
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
1886
                        if (!PBSList.Contains(value))
1887
                            PBSList.Add(value);
1888
                    }
1889
                }
1890
            }
1891
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
1892
            {
1893
                string attrValue = Settings.Default.PBSSettingValue;
1894

    
1895
                foreach (Group group in Groups)
1896
                {
1897
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
1898
                    foreach (Document document in documents)
1899
                    {
1900
                        string name = document.DrawingName;
1901

    
1902
                        int startIndex = Settings.Default.PBSSettingStartValue;
1903
                        int endIndex = Settings.Default.PBSSettingEndValue;
1904

    
1905
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
1906
                        if (!PBSList.Contains(subStr))
1907
                            PBSList.Add(subStr);
1908
                    }
1909
                }
1910
            }
1911
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
1912
            {
1913
                foreach (Group group in Groups)
1914
                {
1915
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
1916
                    foreach (Document document in documents)
1917
                    {
1918
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
1919
                        foreach (TextInfo textInfo in textInfos)
1920
                        {
1921
                            if (!PBSList.Contains(textInfo.Value))
1922
                                PBSList.Add(textInfo.Value);
1923
                        }
1924
                    }
1925
                }
1926
            }
1927

    
1928
            foreach (var item in PBSList)
1929
            {
1930
                if (string.IsNullOrEmpty(result))
1931
                    result = item;
1932
                else
1933
                    result += ", " + item;
1934
            }
1935
            return result;
1936
        }
1937
    }
1938
}
클립보드 이미지 추가 (최대 크기: 500 MB)