프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / ID2PSN / PSN.cs @ 839708c6

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

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

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

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

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

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

    
52
        int tieInPointIndex = 1;
53

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

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

    
62
        ID2Info id2Info = ID2Info.GetInstance();
63

    
64
        
65

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

    
69
        public PSN()
70
        {
71
            
72
        }
73

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
354
        }
355

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
528
                return type;
529
            }
530
        }
531

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

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

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

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

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

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

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

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

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

    
620

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

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

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

    
647
        }
648

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

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

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

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

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

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

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

    
703

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

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

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

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

    
746
                return result;
747
            }
748

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

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

    
775
                return result;
776
            }
777

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

    
783
            return main;
784
        }
785

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

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

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

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

    
826
            return dt;
827
        }
828

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

    
833
            return dt;
834
        }
835

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1166
                                    newRow["OID"] = itemOID;
1167

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

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

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

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

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

    
1195

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

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

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

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

    
1241
                                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1242
                                    if (lineNumber != null)
1243
                                    {
1244
                                        List<Attribute> att = lineNumber.Attributes;
1245
                                        if(att != null)
1246
                                        {
1247
                                            DataRow newPipelineRow = pipelineDT.NewRow();
1248
                                            List<string> oid = new List<string>();
1249
                                            string FluidCode = att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault() != null ? att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault().Value : string.Empty;
1250
                                            string PMC = lineNumber.Attributes.Where(x => x.Name.ToUpper().Equals("PIPINGMATERIALSCLASS")).FirstOrDefault() != null ? lineNumber.Attributes.Where(x => x.Name.ToUpper().Equals("PIPINGMATERIALSCLASS")).FirstOrDefault().Value : string.Empty;
1251
                                            string SEQNUMBER = lineNumber.Attributes.Where(x => x.Name.ToUpper().Equals("TAG SEQ NO")).FirstOrDefault() != null ? lineNumber.Attributes.Where(x => x.Name.ToUpper().Equals("TAG SEQ NO")).FirstOrDefault().Value : string.Empty;
1252
                                            string INSULATION = lineNumber.Attributes.Where(x => x.Name.ToUpper().Equals("INSULATIONPURPOSE")).FirstOrDefault() != null ? lineNumber.Attributes.Where(x => x.Name.ToUpper().Equals("INSULATIONPURPOSE")).FirstOrDefault().Value : string.Empty;
1253
                                            //InsulationPurpose
1254
                                            if (!string.IsNullOrEmpty(FluidCode)) oid.Add(FluidCode);
1255
                                            if (!string.IsNullOrEmpty(PMC)) oid.Add(PMC);                                          
1256

    
1257
                                            string PipeSystem_OID = string.Join("-", oid);
1258

    
1259
                                            if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
1260
                                            if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
1261

    
1262
                                            string OID = string.Join("-", oid);
1263
                                           
1264
                                            newPipelineRow["OID"] = OID;
1265
                                            newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
1266
                                            newPipelineRow["FLUID"] = FluidCode;
1267
                                            newPipelineRow["PMC"] = PMC;
1268
                                            newPipelineRow["SEQNUMBER"] = SEQNUMBER;
1269
                                            newPipelineRow["INSULATION"] = INSULATION;
1270
                                            newPipelineRow["FROM_DATA"] = string.Empty;
1271
                                            newPipelineRow["TO_DATA"] = string.Empty;
1272
                                            newPipelineRow["Unit"] = PSNItem.GetPBSData();
1273
                                            pipelineDT.Rows.Add(newPipelineRow);
1274
                                        }                                        
1275
                                    }
1276

    
1277
                                    DataRow newRow = pipeSystemNetworkDT.NewRow();
1278
                                    newRow["OID"] = PSNItem.PSN_OID();
1279
                                    
1280
                                    newRow["OrderNumber"] = psnOrder;
1281
                                    newRow["Pipeline_OID"] = item.PSNPipeLineID;
1282
                                    PSNItem.KeywordInfos = KeywordInfos;
1283
                                    PSNItem.Nozzle = Nozzle;
1284

    
1285
                                    string FROM_DATA = PSNItem.GetFromData();
1286
                                    newRow["FROM_DATA"] = FROM_DATA;
1287
                                    Item From_item = group.Items.First();
1288

    
1289
                                    if (PSNItem.IsKeyword)
1290
                                    {
1291
                                        PSNItem.StartType = PSNType.Equipment;
1292
                                        UpdatePathItemsKeywordDataRow(From_item.UID, FROM_DATA);                                     
1293
                                    }
1294
                                    else if(FROM_DATA == "ENDOFHEADER")
1295
                                    {
1296
                                        
1297
                                        UpdatePathItemsDataRow(From_item.UID, From_item.ID2DBName, FROM_DATA);
1298
                                    }
1299

    
1300
                                    string TO_DATA = PSNItem.GetToData();
1301
                                    newRow["TO_DATA"] = TO_DATA;
1302
                                    Item To_item = group.Items.First();
1303
                                    if (PSNItem.IsKeyword)
1304
                                    {
1305
                                        PSNItem.EndType = PSNType.Equipment;
1306
                                        UpdatePathItemsKeywordDataRow(To_item.UID, TO_DATA);
1307
                                    }
1308
                                    else if (TO_DATA == "ENDOFHEADER")
1309
                                    {
1310
                                        UpdatePathItemsDataRow(To_item.UID, From_item.ID2DBName, TO_DATA);
1311
                                    }
1312

    
1313
                                    newRow["Type"] = PSNItem.GetPSNType();
1314

    
1315
                                    newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1316
                                    newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
1317
                                    
1318
                                    newRow["IsValid"] = PSNItem.IsValid;
1319
                                    newRow["Status"] = !string.IsNullOrEmpty(PSNItem.Status) ? PSNItem.Status.Remove(0, 2) : string.Empty;
1320
                                    newRow["PBS"] = PSNItem.GetPBSData();
1321
                                  
1322
                                    List<string> drawingNames = new List<string>();
1323
                                    foreach (Group _group in PSNItem.Groups)
1324
                                    {
1325
                                        if (!drawingNames.Contains(_group.Document.DrawingName))
1326
                                        {
1327
                                            if (drawingNames.Count == 0)
1328
                                                newRow["Drawings"] = _group.Document.DrawingName;
1329
                                            else
1330
                                                newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
1331
                                            drawingNames.Add(_group.Document.DrawingName);
1332
                                        }
1333
                                    }
1334
                                    newRow["IncludingVirtualData"] = "No";
1335
                                    newRow["PSNAccuracy"] = "100";
1336
                                    pipeSystemNetworkDT.Rows.Add(newRow);
1337
                                }
1338
                            }
1339
                        }
1340
                    }
1341
                    catch(Exception ex)
1342
                    {
1343
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1344
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1345
                    }
1346

    
1347
                    //TopologySet 관련
1348
                    foreach (Topology topology in PSNItem.Topologies)
1349
                    {
1350
                        DataRow newRow = topologySetDT.NewRow();
1351
                        newRow["OID"] = topology.FullName;
1352
                        newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
1353
                        if (bVentDrain)
1354
                            newRow["SubType"] = "Vent_Drain";
1355
                        else
1356
                            newRow["SubType"] = null;
1357
                        newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
1358
                        newRow["TailItemTag"] = GetItemTag(topology.Items.First());
1359
                        newRow["HeadItemSPID"] = topology.Items.Last().UID;
1360
                        newRow["TailItemSPID"] = topology.Items.First().UID;
1361
                        topologySetDT.Rows.Add(newRow);
1362
                    }
1363
                }
1364

    
1365
                foreach (var item in startBranchDic)
1366
                {
1367
                    string uid = item.Key.UID;
1368
                    string topologyName = item.Value.Topology.FullName;
1369
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1370
                    if (rows.Length == 1)
1371
                    {
1372
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1373
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1374
                    }
1375
                    else if (rows.Length > 1)
1376
                    {
1377
                        DataRow targetRow = null;
1378
                        int index = int.MaxValue;
1379
                        foreach (DataRow row in rows)
1380
                        {
1381
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1382
                            if (split.StartsWith("L"))
1383
                            {
1384
                                int num = Convert.ToInt32(split.Remove(0, 1));
1385
                                if (index > num)
1386
                                {
1387
                                    index = num;
1388
                                    targetRow = row;
1389
                                }
1390
                            }
1391
                        }
1392

    
1393
                        if (targetRow != null)
1394
                        {
1395
                            targetRow["BranchTopologySet_OID"] = topologyName;
1396
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1397
                        }
1398
                    }
1399
                }
1400

    
1401
                foreach (var item in endBranchDic)
1402
                {
1403
                    string uid = item.Key.UID;
1404
                    string topologyName = item.Value.Topology.FullName;
1405
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1406
                    if (rows.Length == 1)
1407
                    {
1408
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1409
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1410
                    }
1411
                    else if (rows.Length > 1)
1412
                    {
1413
                        DataRow targetRow = null;
1414
                        int index = int.MinValue;
1415
                        foreach (DataRow row in rows)
1416
                        {
1417
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1418
                            if (split.StartsWith("L"))
1419
                            {
1420
                                int num = Convert.ToInt32(split.Remove(0, 1));
1421
                                if (index < num)
1422
                                {
1423
                                    index = num;
1424
                                    targetRow = row;
1425
                                }
1426
                            }
1427
                        }
1428

    
1429
                        if (targetRow != null)
1430
                        {
1431
                            targetRow["BranchTopologySet_OID"] = topologyName;
1432
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1433
                        }
1434
                    }
1435
                }
1436

    
1437
                PathItems = pathItemsDT;
1438
                SequenceData = sequenceDataDT;
1439
                PipeSystemNetwork = pipeSystemNetworkDT;
1440
                TopologySet = topologySetDT;
1441
                PipeLine = pipelineDT;
1442
            }
1443
            catch (Exception ex)
1444
            {
1445
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1446
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1447
            }
1448
        }
1449

    
1450
        private double AccuracyCalculation(List<double> lstAcc, double acc)
1451
        {
1452
            foreach(double lacc in lstAcc)
1453
            {
1454
                acc *= lacc;
1455
            }
1456
            acc = acc;
1457
            return acc;
1458
        }
1459

    
1460
        private void UpdateSubType()
1461
        {
1462
            try
1463
            {
1464

    
1465

    
1466
                foreach (PSNItem PSNItem in PSNItems)
1467
                {
1468
                    if (PSNItem.IsBypass)
1469
                    {
1470
                        foreach (Topology topology in PSNItem.Topologies)
1471
                        {
1472
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1473
                            if (rows.Length.Equals(1))
1474
                                rows.First()["SubType"] = "Bypass";
1475
                        }
1476
                    }
1477

    
1478
                    if (PSNItem.StartType == PSNType.Header)
1479
                    {
1480
                        Topology topology = PSNItem.Topologies.First();
1481
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1482
                        if (rows.Length.Equals(1))
1483
                            rows.First()["SubType"] = "Header";
1484
                    }
1485
                    else if (PSNItem.EndType == PSNType.Header)
1486
                    {
1487
                        Topology topology = PSNItem.Topologies.Last();
1488
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1489
                        if (rows.Length.Equals(1))
1490
                            rows.First()["SubType"] = "Header";
1491
                    }
1492
                }
1493

    
1494

    
1495
                foreach (Topology topology in Topologies)
1496
                {
1497
                    try
1498
                    {
1499
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1500
                        if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
1501
                        {
1502
                            if (topology.Items == null)
1503
                                continue;
1504

    
1505
                            Item firstItem = topology.Items.First();
1506
                            Item lastItem = topology.Items.Last();
1507

    
1508
                            List<Relation> relations = new List<Relation>();
1509
                            
1510
                            if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1511
                                relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1512

    
1513
                            if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1514
                                relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1515

    
1516
                            if (relations.Count > 0)
1517
                                rows.First()["SubType"] = "OtherSystem";
1518
                        }
1519
                    }
1520
                    catch (Exception ex)
1521
                    {
1522
                       
1523
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1524
                    }
1525
                }
1526

    
1527
                    foreach (DataRow row in TopologySet.Rows)
1528
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
1529
                        row["SubType"] = "Normal";
1530
            }
1531
            catch (Exception ex)
1532
            {
1533
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1534
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1535
            }
1536
        }
1537

    
1538
        private bool IsBypass(PSNItem PSNItem)
1539
        {
1540
            bool bResult = false;
1541

    
1542
            if (PSNItem.GetPSNType() == "B2B")
1543
            {
1544
                Group firstGroup = PSNItem.Groups.First();
1545
                Group lastGroup = PSNItem.Groups.Last();
1546
                Item firstItem = firstGroup.Items.First();
1547
                Item lastItem = lastGroup.Items.Last();
1548

    
1549
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
1550
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
1551

    
1552
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
1553
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
1554
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
1555
                    bResult = true;
1556
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
1557
                    bResult = true;
1558
            }
1559

    
1560
            Item GetConnectedItemByPSN(Item item)
1561
            {
1562
                Item result = null;
1563

    
1564
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
1565
                if (relation != null)
1566
                    result = relation.Item;
1567

    
1568
                return result;
1569
            }
1570

    
1571
            return bResult;
1572
        }
1573

    
1574
     
1575
        private void UpdateAccuracy()
1576
        {
1577
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
1578
            List<double> lstAcc = null;
1579
            string Status = string.Empty;
1580

    
1581
            foreach (DataRow dataRow in statusRows)
1582
            {
1583
                lstAcc = new List<double>();
1584
                Status = dataRow.Field<string>("Status");
1585

    
1586
                if (!string.IsNullOrEmpty(Status))
1587
                {
1588
                    if (Status.Contains(Rule1)) //Line Disconnected
1589
                        lstAcc.Add(0.75);
1590

    
1591
                    if (Status.Contains(Rule2)) //Missing LineNumber
1592
                        lstAcc.Add(0.7);            
1593

    
1594
                    if (Status.Contains(Rule3)) //OPC Disconneted
1595
                        lstAcc.Add(0.5);            
1596

    
1597
                    if (Status.Contains(Rule4)) //Missing ItemTag or Description
1598
                        lstAcc.Add(0.65);           
1599
                    //else if (Status.Contains(Rule5))
1600
                    //    lstAcc.Add(0.6);
1601
                }
1602

    
1603
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
1604
                if (PSNAccuracy == "100")
1605
                    PSNAccuracy = "1";
1606

    
1607
                PSNAccuracy = Convert.ToString(Math.Round(Convert.ToDouble(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))), 2));
1608
                if (PSNAccuracy != "100")
1609
                {
1610
                    dataRow["IncludingVirtualData"] = "No";
1611
                    dataRow["PSNAccuracy"] = PSNAccuracy;
1612
                }
1613
            }
1614
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
1615
            foreach (DataRow dr in dt.Rows)
1616
            {
1617
                string oid = dr.Field<string>("OID");
1618
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
1619
                double totalDdr = 0;
1620
                foreach (DataRow ddr in select)
1621
                {
1622
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
1623
                    if (acc == 100) acc = 1;
1624
                    if (totalDdr == 0) totalDdr = acc;
1625
                    else totalDdr *= acc;
1626
                }
1627

    
1628
                totalDdr *= 100;
1629

    
1630
                if(totalDdr != 100)
1631
                {
1632
                    foreach (DataRow ddr in select)
1633
                    {
1634
                        ddr["IncludingVirtualData"] = "Yes";
1635
                        ddr["PSNAccuracy"] = totalDdr;
1636
                    }
1637
                }
1638
            }
1639

    
1640
        }
1641

    
1642
        private void UpdateErrorForPSN()
1643
        {
1644
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
1645
            bool bCheckRule5 = false;
1646
            foreach (DataRow dataRow in errorRows)
1647
            {
1648
                try
1649
                {
1650
                   
1651
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
1652
                    bool change = false;
1653
                    bCheckRule5 = false;
1654

    
1655
                    if (!PSNItem.EnableType(PSNItem.StartType))
1656
                    {
1657
                        change = true;
1658
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));                       
1659
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
1660

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

    
1664
                        Item item = PSNItem.Groups.First().Items.First();
1665
                        try
1666
                        {
1667
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
1668
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
1669
                                loopRow["FROM_DATA"] = FROM_DATA;
1670
                            tieInPointIndex++;
1671

    
1672

    
1673
                            if (item.ItemType == ItemType.Line)
1674
                            {
1675
                                //createTerminatorRow - Rule 5번
1676
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
1677
                                SequenceData.Rows.InsertAt(createSequenceTerminatorRow(pathItemRows.First(), insertSeqIndex), insertSeqIndex);
1678

    
1679
                                bCheckRule5 = true;
1680
                            }
1681
                            else
1682
                            {
1683
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
1684
                                SequenceData.Rows.InsertAt(createSequenceTerminatorRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First(), insertSeqIndex), insertSeqIndex);
1685
                                //createTerminatorRow - Rule 5번
1686
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
1687
                                SequenceData.Rows.InsertAt(createSequenceTerminatorRow(pathItemRows.First(), insertSeqIndex), insertSeqIndex);
1688

    
1689
                                bCheckRule5 = true;
1690
                            }
1691

    
1692
                            PSNItem.StartType = PSNType.Equipment;
1693
                        }
1694
                        catch (Exception ex)
1695
                        {
1696
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
1697
                            return;
1698
                        }
1699
                    }
1700

    
1701

    
1702
                    if (!PSNItem.EnableType(PSNItem.EndType))
1703
                    {
1704
                        change = true;
1705
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
1706
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.Last());
1707

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

    
1711
                        Item item = PSNItem.Groups.Last().Items.Last();
1712
                        try
1713
                        {
1714
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
1715

    
1716
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
1717
                                loopRow["TO_DATA"] = TO_DATA;
1718
                            tieInPointIndex++;
1719

    
1720

    
1721
                            if (item.ItemType == ItemType.Line)
1722
                            {
1723
                                //createTerminatorRow - Rule 5번
1724
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
1725
                                SequenceData.Rows.InsertAt(createSequenceTerminatorRow(pathItemRows.Last(), insertSeqIndex + 1), insertSeqIndex + 1);
1726

    
1727
                                bCheckRule5 = true;
1728
                            }
1729
                            else
1730
                            {
1731
                                //createTerminatorRow - Rule 5번
1732
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
1733
                                SequenceData.Rows.InsertAt(createSequenceTerminatorRow(pathItemRows.Last(), insertSeqIndex + 1), insertSeqIndex + 1);
1734
                                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);
1735
                                SequenceData.Rows.InsertAt(createSequenceTerminatorRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last(), insertSeqIndex + 1), insertSeqIndex + 1);
1736
                                bCheckRule5 = true;
1737
                            }
1738

    
1739
                            PSNItem.EndType = PSNType.Equipment;
1740
                        }
1741
                        catch(Exception ex)
1742
                        {
1743
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
1744
                            return;
1745
                        }
1746
                    }
1747

    
1748
                    dataRow["Type"] = PSNItem.GetPSNType();
1749
                    if (change)
1750
                    {
1751
                        int rowIndex = 0;
1752
                        for (int i = 0; i < PathItems.Rows.Count; i++)
1753
                        {
1754
                            DataRow row = PathItems.Rows[i];
1755
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
1756
                                continue;
1757
                            string sequenceData = row["SequenceData_OID"].ToString();
1758
                            string[] split = sequenceData.Split(new char[] { '_' });
1759

    
1760
                            StringBuilder sb = new StringBuilder();
1761
                            for (int j = 0; j < split.Length - 1; j++)
1762
                                sb.Append(split[j] + "_");
1763
                            sb.Append(rowIndex++);
1764
                            row["SequenceData_OID"] = sb.ToString();
1765
                        }
1766

    
1767
                        rowIndex = 0;
1768
                        for (int i = 0; i < SequenceData.Rows.Count; i++)
1769
                        {
1770
                            DataRow row = SequenceData.Rows[i];
1771
                            if (row["PathItem_OID"].ToString() != dataRow["OID"].ToString())
1772
                                continue;
1773
                            string sequenceData = row["SequenceData_OID"].ToString();
1774
                            string[] split = sequenceData.Split(new char[] { '_' });
1775

    
1776
                            row["SERIALNUMBER"] = rowIndex++;
1777
                        }
1778
                    }
1779

    
1780
                    if (bCheckRule5)
1781
                    {                       
1782
                        string PSNAccuracy = "0.6";
1783
                        dataRow["IncludingVirtualData"] = "Yes";
1784
                        dataRow["PSNAccuracy"] = PSNAccuracy;
1785
                       
1786
                    }
1787

    
1788
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
1789
                    {
1790
                        DataRow newRow = PathItems.NewRow();
1791
                        newRow["OID"] = Guid.NewGuid().ToString();
1792
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
1793
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
1794
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
1795
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];                        
1796
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
1797
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
1798
                        newRow["DESCRIPTION"] = DATA; 
1799
                        newRow["Class"] = "End of line terminator";
1800
                        newRow["SubClass"] = "End of line terminator";
1801
                        newRow["TYPE"] = "End";
1802
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
1803
                        newRow["NPD"] = itemRow["NPD"];
1804
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
1805
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
1806
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
1807

    
1808
                        
1809

    
1810
                        return newRow;
1811
                    }
1812

    
1813
                    DataRow createSequenceTerminatorRow(DataRow itemRow, int insertIndex)
1814
                    {
1815
                        DataRow newRow = SequenceData.NewRow();
1816
                        newRow["OID"] = Guid.NewGuid().ToString(); 
1817
                        newRow["SERIALNUMBER"] = string.Format("{0}", insertIndex);
1818
                        newRow["PathItem_OID"] = itemRow["OID"];
1819
                        newRow["TopologySet_OID_Key"] = itemRow["TopologySet_OID"];
1820

    
1821
                        return newRow;
1822
                    }
1823

    
1824
                    DataRow createLineRow(DataRow itemRow)
1825
                    {
1826
                        DataRow newRow = PathItems.NewRow();
1827
                        newRow["OID"] = Guid.NewGuid().ToString();
1828
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
1829
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
1830
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
1831
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
1832
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
1833
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
1834
                        newRow["Class"] = itemRow["Class"];
1835
                        newRow["SubClass"] = itemRow["SubClass"];
1836
                        newRow["TYPE"] = itemRow["TYPE"];
1837
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
1838
                        newRow["NPD"] = itemRow["NPD"];
1839
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
1840
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
1841
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
1842

    
1843
                        return newRow;
1844
                    }
1845
                }
1846
                catch(Exception ex)
1847
                {
1848

    
1849
                }
1850
            }
1851
        }
1852
    }
1853

    
1854
    public class PSNItem
1855
    {
1856
        public PSNItem(int count, int Revision)
1857
        {
1858
            Groups = new List<Group>();
1859
            Topologies = new List<Topology>();
1860

    
1861
            Index = count + 1;
1862
            this.Revision = Revision;
1863
        }
1864

    
1865
        private int Revision;
1866
        public string UID { get; set; }
1867
        public List<Group> Groups { get; set; }
1868
        public List<Topology> Topologies { get; set; }
1869
        public PSNType StartType { get; set; }
1870
        public PSNType EndType { get; set; }
1871
        public int Index { get; set; }
1872
        public string IsValid { get; set; }
1873
        public bool IsKeyword { get; set; }
1874
        public string Status { get; set; }
1875
        public string IncludingVirtualData { get; set; }
1876
        public string PSNAccuracy { get; set; }
1877
        public KeywordInfo KeywordInfos = new KeywordInfo();
1878
        public DataTable Nozzle = new DataTable();
1879

    
1880
        public string PSN_OID()
1881
        {
1882
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
1883
        }
1884
        public string GetPSNType()
1885
        {
1886
            string result = string.Empty;
1887

    
1888
            if (EnableType(StartType) && EnableType(EndType))
1889
            {
1890
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
1891
                    result = "E2E";
1892
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
1893
                    result = "B2B";
1894
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
1895
                    result = "HD2";
1896

    
1897
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
1898
                    result = "E2B";
1899
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
1900
                    result = "B2E";
1901

    
1902
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
1903
                    result = "HDB";
1904
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
1905
                    result = "HDB";
1906

    
1907
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
1908
                    result = "HDE";
1909
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
1910
                    result = "HDE";
1911
                else
1912
                    result = "Error";
1913
            }
1914
            else
1915
                result = "Error";
1916

    
1917
            return result;
1918

    
1919
            
1920
        }
1921
        public bool EnableType(PSNType type)
1922
        {
1923
            bool result = false;
1924

    
1925
            if (type == PSNType.Branch ||
1926
                type == PSNType.Equipment ||
1927
                type == PSNType.Header)
1928
            {
1929
                result = true;
1930
            }
1931

    
1932
            return result;
1933
        }
1934
        public bool IsBypass { get; set; }
1935

    
1936
        public string GetFromData()
1937
        {
1938
            string result = string.Empty;
1939
            if (IsKeyword)
1940
                IsKeyword = false;
1941
            try
1942
            {
1943
                if (StartType == PSNType.Header)
1944
                    result = "ENDOFHEADER";
1945
                else if (StartType == PSNType.Branch)
1946
                {
1947
                    Item item = Groups.First().Items.First();
1948
                    if (item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
1949
                        result = item.Relations.First().Item.LineNumber.Name;
1950
                    else
1951
                    {
1952
                        Status += ", Missing LineNumber";
1953
                        result = "Empty LineNumber";
1954
                    }
1955
                }
1956
                else if (StartType == PSNType.Equipment)
1957
                {
1958
                    result = Groups.First().Items.First().Equipment.ItemTag;
1959
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
1960

    
1961
                    if (drNozzle != null)
1962
                        result += " ["+ drNozzle.Field<string>("ITEMTAG") + "]";
1963
                }
1964
                
1965
                else
1966
                {
1967
                    IsValid = "Error";
1968
                    Item item = Groups.First().Items.First();
1969
                    if (item.ItemType == ItemType.Symbol)
1970
                    {
1971

    
1972
                        string keyword = string.Empty;
1973
                        keyword = GetFromKeywordData();
1974

    
1975
                        if (string.IsNullOrEmpty(keyword))
1976
                        {
1977
                            if (item.ID2DBType.Contains("OPC's"))
1978
                                Status += ", OPC Disconneted";
1979
                            else
1980
                                Status += ", Missing ItemTag or Description";
1981

    
1982
                            result = item.ID2DBName;
1983
                        }
1984
                        else
1985
                        {
1986
                            result = keyword;
1987
                            IsKeyword = true;
1988
                            IsValid = string.Empty;
1989
                        }
1990
                        
1991
                    }
1992
                    else if (item.ItemType == ItemType.Line)
1993
                    {
1994
                        Status += ", Line Disconnected";
1995
                        result = item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
1996
                    }
1997
                    else
1998
                        result = "Unknown";
1999
                }
2000
            }
2001
            catch(Exception ex)
2002
            {
2003

    
2004
            }
2005

    
2006
            return result;
2007
        }
2008

    
2009
        public string GetFromKeywordData()
2010
        {
2011
            string result = string.Empty;
2012
           
2013
            Item item = Groups.First().Items.First();
2014

    
2015
            foreach(KeywordItem keyitem in KeywordInfos.KeywordItems)
2016
            {
2017
                if(keyitem.Name.Equals(item.Name))
2018
                    result = keyitem.Keyword;
2019
            }
2020
          
2021
            return result;
2022
        }
2023

    
2024
        public string GetToKeywordData()
2025
        {
2026
            string result = string.Empty;
2027

    
2028
            Item item = Groups.Last().Items.Last();
2029
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2030
            {
2031
                if (keyitem.Name.Equals(item.Name))
2032
                    result = keyitem.Keyword;
2033
            }
2034
            return result;
2035
        }
2036

    
2037
        public string GetToData()
2038
        {
2039
            string result = string.Empty;
2040
            if (IsKeyword)
2041
                IsKeyword = false;
2042

    
2043
            if (EndType == PSNType.Header)
2044
                result = "ENDOFHEADER";
2045
            else if (EndType == PSNType.Branch)
2046
            {
2047
                Item item = Groups.Last().Items.Last();
2048
                if (item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
2049
                    result = item.Relations.Last().Item.LineNumber.Name;
2050
                else
2051
                {
2052
                    Status += ", Missing LineNumber";
2053
                    result = "Empty LineNumber";
2054
                }
2055
            }
2056
            else if (EndType == PSNType.Equipment)
2057
            {
2058
                result = Groups.Last().Items.Last().Equipment.ItemTag;
2059
                DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
2060

    
2061
                if (drNozzle != null)
2062
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
2063
            }
2064
            else
2065
            {
2066
                IsValid = "Error";
2067
                Item item = Groups.Last().Items.Last();
2068
                if (item.ItemType == ItemType.Symbol)
2069
                {
2070
                    string keyword = string.Empty;
2071
                    keyword = GetToKeywordData();
2072

    
2073
                    if (string.IsNullOrEmpty(keyword))
2074
                    {
2075
                        if (item.ID2DBType.Contains("OPC's"))
2076
                            Status += ", OPC Disconneted";
2077
                        else
2078
                            Status += ", Missing ItemTag or Description";
2079

    
2080
                        result = item.ID2DBName;
2081
                    }
2082
                    else
2083
                    {
2084
                        result = keyword;
2085
                        IsValid = string.Empty;
2086
                        IsKeyword = true;
2087
                    }
2088
                    
2089
                }
2090
                else if (item.ItemType == ItemType.Line)
2091
                {
2092
                    Status += ", Line Disconnected";
2093
                    result = item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2094
                }
2095
                else
2096
                    result = "Unknown";
2097
            }
2098
            return result;
2099
        }
2100

    
2101
        public string GetPBSData()
2102
        {
2103
            string result = string.Empty;
2104
            List<string> PBSList = new List<string>();
2105
            if (Settings.Default.PBSSetting.Equals("Line Number"))
2106
            {
2107
                string attrValue = Settings.Default.PBSSettingValue;
2108

    
2109
                foreach (Group group in Groups)
2110
                {
2111
                    List<LineNumber> lineNumbers = group.Items.Select(x =>x.LineNumber).Distinct().ToList();
2112
                    foreach (LineNumber lineNumber in lineNumbers)
2113
                    {
2114
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
2115
                        if (attribute != null)
2116
                        {
2117
                            string value = attribute.Value;
2118
                            if (!PBSList.Contains(value))
2119
                                PBSList.Add(value);
2120
                        }
2121
                    }
2122
                }
2123
            }
2124
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
2125
            {
2126
                string attrValue = Settings.Default.PBSSettingValue;
2127

    
2128
                foreach (Group group in Groups)
2129
                {
2130
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
2131
                    foreach (Item item in items)
2132
                    {
2133
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
2134
                        if (!PBSList.Contains(value))
2135
                            PBSList.Add(value);
2136
                    }
2137
                }
2138
            }
2139
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
2140
            {
2141
                string attrValue = Settings.Default.PBSSettingValue;
2142

    
2143
                foreach (Group group in Groups)
2144
                {
2145
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
2146
                    foreach (Document document in documents)
2147
                    {
2148
                        string name = document.DrawingName;
2149

    
2150
                        int startIndex = Settings.Default.PBSSettingStartValue;
2151
                        int endIndex = Settings.Default.PBSSettingEndValue;
2152

    
2153
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
2154
                        if (!PBSList.Contains(subStr))
2155
                            PBSList.Add(subStr);
2156
                    }
2157
                }
2158
            }
2159
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
2160
            {
2161
                foreach (Group group in Groups)
2162
                {
2163
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
2164
                    foreach (Document document in documents)
2165
                    {
2166
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
2167
                        foreach (TextInfo textInfo in textInfos)
2168
                        {
2169
                            if (!PBSList.Contains(textInfo.Value))
2170
                                PBSList.Add(textInfo.Value);
2171
                        }
2172
                    }
2173
                }
2174
            }
2175

    
2176
            foreach (var item in PBSList)
2177
            {
2178
                if (string.IsNullOrEmpty(result))
2179
                    result = item;
2180
                else
2181
                    result += ", " + item;
2182
            }
2183
            return result;
2184
        }
2185
    }
2186
}
클립보드 이미지 추가 (최대 크기: 500 MB)