프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / ID2PSN / PSN.cs @ 91c75c0b

이력 | 보기 | 이력해설 | 다운로드 (135 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
        public DataTable PipeSystem { get; set; }
46

    
47
        public string Rule1 = "Missing LineNumber_1"; //Line Disconnected에서 변경
48
        public string Rule2 = "Missing LineNumber_2"; //Missing LineNumber에서 변경
49
        public string Rule3 = "OPC Disconnected";
50
        public string Rule4 = "Missing ItemTag or Description";
51
        public string Rule5 = "Line Disconnected";
52

    
53
        int tieInPointIndex = 1;
54

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

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

    
63
        ID2Info id2Info = ID2Info.GetInstance();
64

    
65

    
66

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

    
70
        public PSN()
71
        {
72

    
73
        }
74

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

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

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

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

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

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

    
232
            // Update Keyword
233
            UpdateKeywordForPSN();
234
            // Vent/Drain PSN 데이터 제거
235
            DeleteVentDrain();
236
            // Topology의 subtype을 update(bypass, Header, 등등) 
237
            UpdateSubType();
238
            // Update Error
239
            UpdateErrorForPSN();
240
            // Insert Tee
241
            InsertTeePSN();
242
            // 확도 계산
243
            UpdateAccuracy();
244
            // ValveGrouping
245
            UpdateValveGrouping();
246

    
247

    
248
            // PathItem 정렬
249
            //PathItemSort();
250
        }
251

    
252
        //private void PathItemSort()
253
        //{
254
        //    try
255
        //    {
256
        //        SequenceData.
257
        //    }
258
        //    catch (Exception ex)
259
        //    {
260
        //        MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
261
        //    }
262
        //    //}
263
        //}
264

    
265
        private void UpdateValveGrouping()
266
        {
267
            try
268
            {
269
                #region ValveGrouping Info
270
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
271
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
272
                foreach (DataRow row in dtValveGroupung.Rows)
273
                {
274
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
275
                    {
276
                        OID = row["OID"].ToString(),
277
                        GroupType = row["GroupType"].ToString(),
278
                        TagIdentifier = row["TagIdentifier"].ToString(),
279
                        AttributeName = row["AttributeName"].ToString(),
280
                        SppidSymbolName = row["SppidSymbolName"].ToString()
281
                    });
282
                }
283
                #endregion
284

    
285

    
286
                int vgTagNum = 1;
287
                DataRow[] tagpathItemRows = PathItems.Select(string.Format("GROUPTAG Like '%\\%'"));
288
                foreach (DataRow drPathitem in tagpathItemRows)
289
                {
290
                    string[] valvetag = drPathitem["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
291
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
292
                    ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
293
                    if (valveitem == null || valveitem.GroupType == "Scope Break")
294
                        continue;
295
                    Dictionary<int, List<DataRow>> keyValuePairs = new Dictionary<int, List<DataRow>>();
296
                    List<Item> valveGroupingItem = new List<Item>();
297
                    int bCnt = 0;
298

    
299
                    //bool bCheck = false;
300
                    List<DataRow> lstitem = new List<DataRow>();
301
                    foreach (DataRow dr in pathItemRows)
302
                    {
303
                        //if (!string.IsNullOrEmpty(dr["GROUPTAG"].ToString()))
304
                        //    break;
305

    
306
                       if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
307
                        {
308
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));
309
                            if (dr["GROUPTAG"].ToString() == "Scope Break")
310
                            {
311
                                dr["GROUPTAG"] = string.Empty;
312
                                break;
313
                            }
314

    
315
                            if (rows.First()["SubType"].ToString() != "Bypass" && rows.First()["SubType"].ToString() != "Vent_Drain")
316
                            {
317
                               // bCheck = true;
318
                                lstitem.Add(dr);
319
                                keyValuePairs.Add(bCnt, lstitem.ToList());
320
                                bCnt++;
321
                                lstitem.Clear();
322
                            }
323
                            else
324
                                lstitem.Add(dr);
325
                        }
326
                        else
327
                            lstitem.Add(dr);
328
                    }
329

    
330
                    if (lstitem.Count > 0)
331
                    {
332
                        keyValuePairs.Add(bCnt, lstitem);
333
                        //bCnt++;
334
                    }
335

    
336
                    if (keyValuePairs.Count() == 0)
337
                        continue;
338

    
339
                    string VGTag = string.Empty;
340
                    if (valveitem.AttributeName == "NoSelection")
341
                    {
342
                        VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
343
                        vgTagNum++;
344
                    }
345
                    else
346
                    {
347
                        VGTag = valveitem.TagIdentifier + "-" + valvetag[1];
348
                    }
349

    
350
                    foreach (KeyValuePair<int, List<DataRow>> keyValuePair in keyValuePairs)
351
                    {
352
                        if (keyValuePair.Value.Where(x => x.Field<string>("OID") == drPathitem.Field<string>("OID")).Count() > 0)
353
                        {
354
                            foreach (DataRow dr in keyValuePair.Value)
355
                            {
356
                                dr["GROUPTAG"] = VGTag;
357
                            }
358
                        }
359
                    }
360

    
361
                    if(valveitem.GroupType.Contains("PSV"))
362
                    {
363
                        DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
364
                        foreach (DataRow row in psnRows)
365
                            row["Pocket"] = "Yes";
366
                    }                    
367
                }
368
            }
369
            catch (Exception ex)
370
            {
371
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
372
            }
373
            //}
374
        }
375

    
376
        private void SetTopologyData()
377
        {
378
            // 13번 excel
379
            foreach (Group group in groups)
380
            {
381
                LineNumber prevLineNumber = null;
382
                for (int i = 0; i < group.Items.Count; i++)
383
                {
384
                    Item item = group.Items[i];
385
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
386
                    if (lineNumber == null)
387
                    {
388
                        if (prevLineNumber != null)
389
                        {
390
                            if (!prevLineNumber.IsCopy)
391
                            {
392
                                prevLineNumber = prevLineNumber.Copy();
393
                                item.Document.LineNumbers.Add(prevLineNumber);
394
                                item.MissingLineNumber1 = true;
395
                            }
396
                            item.Owner = prevLineNumber.UID;
397
                        }
398
                    }
399
                    else
400
                        prevLineNumber = lineNumber;
401
                }
402

    
403
                prevLineNumber = null;
404
                for (int i = group.Items.Count - 1; i > -1; i--)
405
                {
406
                    Item item = group.Items[i];
407
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
408
                    if (lineNumber == null)
409
                    {
410
                        if (prevLineNumber != null)
411
                        {
412
                            if (!prevLineNumber.IsCopy)
413
                            {
414
                                prevLineNumber = prevLineNumber.Copy();
415
                                item.Document.LineNumbers.Add(prevLineNumber);
416
                                item.MissingLineNumber1 = true;
417
                            }
418

    
419
                            item.Owner = prevLineNumber.UID;
420
                        }
421
                    }
422
                    else
423
                        prevLineNumber = lineNumber;
424
                }
425

    
426
                if (prevLineNumber == null)
427
                {
428
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
429
                    Random random = new Random();
430
                    int index = random.Next(lineNumbers.Count - 1);
431

    
432
                    // Copy
433
                    LineNumber cLineNumber = lineNumbers[index].Copy();
434
                    group.Document.LineNumbers.Add(cLineNumber);
435

    
436
                    foreach (Item item in group.Items)
437
                    {
438
                        item.Owner = cLineNumber.UID;
439
                        item.MissingLineNumber2 = true;
440
                    }
441
                }
442
            }
443

    
444
            foreach (Document document in Documents)
445
            {
446
                foreach (Item item in document.Items)
447
                {
448
                    item.TopologyData = string.Empty;
449
                    item.PSNPipeLineID = string.Empty;
450
                    List<string> pipeLineID = new List<string>();
451
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
452
                    if (lineNumber != null)
453
                    {
454
                        item.LineNumber = lineNumber;
455

    
456
                        foreach (DataRow row in topologyRuleDT.Rows)
457
                        {
458
                            string uid = row["UID"].ToString();
459
                            //if (uid == "-")
460
                            //    pipeLineID.Add(item.TopologyData);//item.TopologyData += "-"; 
461
                            if (uid != "-")
462
                            {
463
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
464

    
465
                                Attribute attribute = lineNumber.Attributes.Find(x => x.Name == uid);
466
                                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
467
                                    pipeLineID.Add(attribute.Value);//item.TopologyData += attribute.Value;
468
                            }
469
                        }
470

    
471
                        if (topologyRuleDT.Select(string.Format("UID = '{0}'", "InsulationPurpose")) == null)
472
                        {
473
                            Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
474
                            if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
475
                                pipeLineID.Add(insulAttr.Value); //item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
476
                                                                 //else
477
                                                                 //    item.PSNPipeLineID = item.TopologyData;
478
                        }
479

    
480
                        item.PSNPipeLineID = string.Join("-", pipeLineID);
481
                        item.TopologyData = string.Join("-", pipeLineID);
482

    
483
                    }
484
                    else
485
                    {
486
                        item.TopologyData = "Empty LineNumber";
487
                        item.LineNumber = new LineNumber();
488
                    }
489
                }
490
            }
491

    
492
            int emptyIndex = 1;
493
            foreach (Group group in groups)
494
            {
495
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
496
                if (groupItems.Count > 0)
497
                {
498
                    foreach (var item in groupItems)
499
                        item.TopologyData += string.Format("-{0}", emptyIndex);
500
                    emptyIndex++;
501
                }
502
            }
503

    
504
        }
505

    
506
        private void ConnectByOPC()
507
        {
508
            try
509
            {
510
                foreach (Group group in groups.FindAll(x => x.Items.Last().SubItemType == SubItemType.OPC))
511
                {
512
                    Item opcItem = group.Items.Last();
513
                    DataRow[] fromRows = opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID));
514
                    if (fromRows.Length.Equals(1))
515
                    {
516
                        DataRow opcRow = fromRows.First();
517
                        string toDrawing = opcRow["ToDrawing"].ToString();
518
                        string toOPCUID = opcRow["ToOPCUID"].ToString();
519

    
520
                        Document toDocument = Documents.Find(x => x.DrawingName == toDrawing);
521
                        if (toDocument != null)
522
                        {
523
                            Group toGroup = toDocument.Groups.Find(x => x.Items.Find(y => y.UID == toOPCUID) != null);
524
                            DataRow[] toRows = opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID));
525
                            //1대1 매칭이 아닐때 걸림 (2개 이상일 때) 2021.11.07 
526
                            if (toRows.Length > 1)
527
                            {
528
                                //throw new Exception("OPC error(multi connect)");
529
                                MessageBox.Show("OPC error(multi connect)", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
530
                                return;
531
                            }
532
                            group.EndGroup = toGroup;
533
                            toGroup.StartGroup = group;
534
                        }
535
                    }
536
                }
537
            }
538
            catch (Exception ex)
539
            {
540
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
541
                //MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
542
            }
543
        }
544

    
545
        private void SetPSNItem()
546
        {
547
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>();
548
            foreach (Group group in groups)
549
                groupDic.Add(group, Guid.NewGuid().ToString());
550

    
551
            foreach (Group group in groups)
552
            {
553
                string groupKey = groupDic[group];
554
                if (group.StartGroup != null)
555
                {
556
                    string otherKey = groupDic[group.StartGroup];
557
                    ChangeGroupID(otherKey, groupKey);
558
                }
559
            }
560

    
561
            // PSN 정리
562
            foreach (var item in groupDic)
563
            {
564
                Group group = item.Key;
565
                string uid = item.Value;
566
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
567
                if (PSNItem == null)
568
                {
569
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
570
                    PSNItems.Add(PSNItem);
571
                }
572
                PSNItem.Groups.Add(group);
573
                foreach (Item groupItem in group.Items)
574
                    groupItem.PSNItem = PSNItem;
575
            }
576

    
577
            // Sort PSN
578
            foreach (PSNItem PSNItem in PSNItems)
579
            {
580
                List<Group> _groups = new List<Group>();
581

    
582
                Stack<Group> stacks = new Stack<Group>();
583
                stacks.Push(PSNItem.Groups.First());
584
                while (stacks.Count > 0)
585
                {
586
                    Group stack = stacks.Pop();
587
                    if (_groups.Contains(stack))
588
                        continue;
589

    
590
                    if (_groups.Count == 0)
591
                        _groups.Add(stack);
592
                    else
593
                    {
594
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
595
                        {
596
                            int index = _groups.IndexOf(stack.StartGroup);
597
                            _groups.Insert(index + 1, stack);
598
                        }
599
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
600
                        {
601
                            int index = _groups.IndexOf(stack.EndGroup);
602
                            _groups.Insert(index, stack);
603
                        }
604
                    }
605

    
606
                    if (stack.StartGroup != null)
607
                        stacks.Push(stack.StartGroup);
608
                    if (stack.EndGroup != null)
609
                        stacks.Push(stack.EndGroup);
610
                }
611

    
612
                PSNItem.Groups.Clear();
613
                PSNItem.Groups.AddRange(_groups);
614
            }
615

    
616
            void ChangeGroupID(string from, string to)
617
            {
618
                if (from.Equals(to))
619
                    return;
620

    
621
                List<Group> changeItems = new List<Group>();
622
                foreach (var _item in groupDic)
623
                    if (_item.Value.Equals(from))
624
                        changeItems.Add(_item.Key);
625
                foreach (var _item in changeItems)
626
                    groupDic[_item] = to;
627
            }
628
        }
629

    
630
        private void SetPSNType()
631
        {
632
            foreach (PSNItem PSNItem in PSNItems)
633
            {
634
                Group firstGroup = PSNItem.Groups.First();
635
                Group lastGroup = PSNItem.Groups.Last();
636

    
637
                Item firstItem = firstGroup.Items.First();
638
                Item lastItem = lastGroup.Items.Last();
639

    
640
                PSNItem.StartType = GetPSNType(firstItem, true);
641
                PSNItem.EndType = GetPSNType(lastItem, false);
642
            }
643

    
644
            PSNType GetPSNType(Item item, bool bFirst = true)
645
            {
646
                PSNType type = PSNType.None;
647

    
648
                if (item.ItemType == ItemType.Line)
649
                {
650
                    Group group = groups.Find(x => x.Items.Contains(item));
651
                    if (bFirst && item.Relations[0].Item != null && !group.Items.Contains(item.Relations[0].Item))
652
                    {
653
                        Item connItem = item.Relations[0].Item;
654
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
655
                            type = PSNType.Branch;
656
                        else if (connItem.ItemType == ItemType.Symbol)
657
                            type = PSNType.Symbol;
658
                    }
659
                    else if (!bFirst && item.Relations[1].Item != null && !group.Items.Contains(item.Relations[1].Item))
660
                    {
661
                        Item connItem = item.Relations[1].Item;
662
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
663
                            type = PSNType.Branch;
664
                        else if (connItem.ItemType == ItemType.Symbol)
665
                            type = PSNType.Symbol;
666
                    }
667
                }
668
                else if (item.ItemType == ItemType.Symbol)
669
                {
670
                    if (item.SubItemType == SubItemType.Nozzle)
671
                        type = PSNType.Equipment;
672
                    else if (item.SubItemType == SubItemType.Header)
673
                        type = PSNType.Header;
674
                    else if (item.SubItemType == SubItemType.OPC)
675
                        type = PSNType.OPC;
676
                }
677

    
678
                return type;
679
            }
680
        }
681

    
682
        private void SetBranchInfo()
683
        {
684
            foreach (Document document in Documents)
685
            {
686
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
687
                foreach (Item line in lines)
688
                {
689
                    double[] point = line.Relations[0].Point;
690
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
691
                    connLines.Sort(SortBranchLine);
692
                    line.BranchItems.AddRange(connLines);
693

    
694
                    int SortBranchLine(Item a, Item b)
695
                    {
696
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
697
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
698

    
699
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
700
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
701

    
702
                        // 내림차순
703
                        return distanceA.CompareTo(distanceB);
704
                    }
705
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
706
                    {
707
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
708
                    }
709
                }
710
            }
711
        }
712

    
713
        private void SetTopology()
714
        {
715
            try
716
            {
717
                #region 기본 topology 정리
718
                foreach (PSNItem PSNItem in PSNItems)
719
                {
720
                    Topology topology = null;
721
                    foreach (Group group in PSNItem.Groups)
722
                    {
723
                        foreach (Item item in group.Items)
724
                        {
725
                            if (string.IsNullOrEmpty(item.TopologyData))
726
                                topology = null;
727
                            else
728
                            {
729
                                if (topology == null)
730
                                {
731
                                    topology = new Topology()
732
                                    {
733
                                        ID = item.TopologyData
734
                                    };
735
                                    Topologies.Add(topology);
736

    
737
                                    if (!PSNItem.Topologies.Contains(topology))
738
                                        PSNItem.Topologies.Add(topology);
739
                                }
740
                                else
741
                                {
742
                                    if (topology.ID != item.TopologyData)
743
                                    {
744
                                        topology = new Topology()
745
                                        {
746
                                            ID = item.TopologyData
747
                                        };
748
                                        Topologies.Add(topology);
749

    
750
                                        if (!PSNItem.Topologies.Contains(topology))
751
                                            PSNItem.Topologies.Add(topology);
752
                                    }
753
                                }
754

    
755
                                item.Topology = topology;
756
                                topology.Items.Add(item);
757
                            }
758
                        }
759
                    }
760
                }
761
                #endregion
762

    
763
                #region Type
764
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
765
                foreach (string id in ids)
766
                {
767
                    try
768
                    {
769

    
770

    
771
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
772

    
773
                        // Main
774
                        List<Topology> mainTopologies = FindMainTopology(topologies);
775
                        foreach (Topology topology in mainTopologies)
776
                            topology.Type = "M";
777

    
778
                        // Branch
779
                        List<Topology> branchToplogies = topologies.FindAll(x => string.IsNullOrEmpty(x.Type));
780
                        foreach (Topology topology in branchToplogies)
781
                            topology.Type = "B";
782
                    }
783
                    catch (Exception ex)
784
                    {
785
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
786
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
787
                    }
788
                }
789
                #endregion
790
            }
791
            catch (Exception ex)
792
            {
793
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
794
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
795
            }
796

    
797
        }
798

    
799
        private void SetTopologyIndex()
800
        {
801
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
802
            foreach (string id in ids)
803
            {
804
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
805

    
806
                // Main
807
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
808
                foreach (Topology topology in mainTopologies)
809
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
810

    
811
                // Branch
812
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
813
                foreach (Topology topology in branchToplogies)
814
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
815
            }
816
        }
817

    
818
        private void SetPSNBypass()
819
        {
820
            foreach (PSNItem PSNItem in PSNItems)
821
                PSNItem.IsBypass = IsBypass(PSNItem);
822
        }
823

    
824
        private List<Topology> FindMainTopology(List<Topology> data)
825
        {
826
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
827
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
828
            //2021.11.17 안쓰네 JY
829
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
830

    
831
            List<Topology> main = new List<Topology>();
832
            main.AddRange(data);
833
            //
834
            main = GetNozzleTopology(data);
835
            if (main.Count == 1)
836
                return main;
837
            else
838
            {
839
                if (main.Count > 0)
840
                    main = GetPMCTopology(main);
841
                else
842
                    main = GetPMCTopology(data);
843

    
844
                if (main.Count == 1)
845
                    return main;
846
                else
847
                {
848
                    if (main.Count > 0)
849
                        main = GetDiaTopology(main);
850
                    else
851
                        main = GetDiaTopology(data);
852

    
853

    
854
                    if (main.Count == 1)
855
                        return main;
856
                    else
857
                    {
858
                        if (main.Count > 0)
859
                            main = GetItemTopology(main);
860
                        else
861
                            main = GetItemTopology(data);
862
                    }
863
                }
864
            }
865

    
866
            List<Topology> GetNozzleTopology(List<Topology> topologies)
867
            {
868
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
869
            }
870

    
871
            List<Topology> GetPMCTopology(List<Topology> topologies)
872
            {
873
                List<Topology> result = new List<Topology>();
874
                foreach (DataRow row in PMCDT.Rows)
875
                {
876
                    string value = row["CODE"].ToString();
877
                    foreach (Topology topology in topologies)
878
                    {
879
                        foreach (Item item in topology.Items)
880
                        {
881
                            if (item.LineNumber == null)
882
                                continue;
883
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
884
                            if (attribute != null && value == attribute.Value)
885
                            {
886
                                result.Add(topology);
887
                                break;
888
                            }
889
                        }
890
                    }
891

    
892
                    if (result.Count > 0)
893
                        break;
894
                }
895

    
896
                return result;
897
            }
898

    
899
            List<Topology> GetDiaTopology(List<Topology> topologies)
900
            {
901
                List<Topology> result = new List<Topology>();
902
                foreach (DataRow row in nominalDiameterDT.Rows)
903
                {
904
                    string inchValue = row["InchStr"].ToString();
905
                    string metricValue = row["MetricStr"].ToString();
906
                    foreach (Topology topology in topologies)
907
                    {
908
                        foreach (Item item in topology.Items)
909
                        {
910
                            if (item.LineNumber == null)
911
                                continue;
912
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
913
                            if (attribute != null && (inchValue == attribute.Value || metricValue == attribute.Value))
914
                            {
915
                                result.Add(topology);
916
                                break;
917
                            }
918
                        }
919
                    }
920

    
921
                    if (result.Count > 0)
922
                        break;
923
                }
924

    
925
                return result;
926
            }
927

    
928
            List<Topology> GetItemTopology(List<Topology> topologies)
929
            {
930
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
931
            }
932

    
933
            return main;
934
        }
935

    
936
        private DataTable GetOPCInfo()
937
        {
938
            DataTable opc = DB.SelectOPCRelations();
939
            DataTable drawing = DB.AllDrawings();
940

    
941
            DataTable dt = new DataTable();
942
            dt.Columns.Add("FromDrawing", typeof(string));
943
            dt.Columns.Add("FromDrawingUID", typeof(string));
944
            dt.Columns.Add("FromOPCUID", typeof(string));
945
            dt.Columns.Add("ToDrawing", typeof(string));
946
            dt.Columns.Add("ToDrawingUID", typeof(string));
947
            dt.Columns.Add("ToOPCUID", typeof(string));
948
            foreach (DataRow row in opc.Rows)
949
            {
950
                string fromDrawingUID = row["From_Drawings_UID"] == null ? string.Empty : row["From_Drawings_UID"].ToString();
951
                string fromOPCUID = row["From_OPC_UID"] == null ? string.Empty : row["From_OPC_UID"].ToString();
952
                string toDrawingUID = row["To_Drawings_UID"] == null ? string.Empty : row["To_Drawings_UID"].ToString();
953
                string toOPCUID = row["To_OPC_UID"] == null ? string.Empty : row["To_OPC_UID"].ToString();
954
                if (!string.IsNullOrEmpty(toOPCUID))
955
                {
956
                    DataRow[] fromRows = drawing.Select(string.Format("UID = '{0}'", fromDrawingUID));
957
                    DataRow[] toRows = drawing.Select(string.Format("UID = '{0}'", toDrawingUID));
958
                    if (fromRows.Length.Equals(1) && toRows.Length.Equals(1))
959
                    {
960
                        string fromDrawingName = Path.GetFileNameWithoutExtension(fromRows.First()["NAME"].ToString());
961
                        string toDrawingName = Path.GetFileNameWithoutExtension(toRows.First()["NAME"].ToString());
962

    
963
                        DataRow newRow = dt.NewRow();
964
                        newRow["FromDrawing"] = fromDrawingName;
965
                        newRow["FromDrawingUID"] = fromDrawingUID;
966
                        newRow["FromOPCUID"] = fromOPCUID;
967
                        newRow["ToDrawing"] = toDrawingName;
968
                        newRow["ToDrawingUID"] = toDrawingUID;
969
                        newRow["ToOPCUID"] = toOPCUID;
970

    
971
                        dt.Rows.Add(newRow);
972
                    }
973
                }
974
            }
975

    
976
            return dt;
977
        }
978

    
979
        private DataTable GetTopologyRule()
980
        {
981
            DataTable dt = DB.SelectTopologyRule();
982

    
983
            return dt;
984
        }
985

    
986
        private bool IsConnected(Item item1, Item item2)
987
        {
988
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
989
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
990
                return true;
991
            else
992
                return false;
993
        }
994

    
995
        private void SaveNozzleAndEquipment()
996
        {
997
            List<Item> nozzles = new List<Item>();
998
            List<Equipment> equipments = new List<Equipment>();
999
            foreach (Document document in Documents)
1000
            {
1001
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
1002
                equipments.AddRange(document.Equipments);
1003
            }
1004

    
1005

    
1006
            DataTable nozzleDT = new DataTable();
1007
            nozzleDT.Columns.Add("OID", typeof(string));
1008
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
1009
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
1010
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
1011
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
1012
            nozzleDT.Columns.Add("FLUID", typeof(string));
1013
            nozzleDT.Columns.Add("NPD", typeof(string));
1014
            nozzleDT.Columns.Add("PMC", typeof(string));
1015
            nozzleDT.Columns.Add("ROTATION", typeof(string));
1016
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
1017

    
1018
            foreach (Item item in nozzles)
1019
            {
1020
                DataRow row = nozzleDT.NewRow();
1021
                row["OID"] = item.UID;
1022

    
1023
                Relation relation = item.Relations.Find(x => equipments.Find(y => y.UID == x.UID) != null);
1024
                if (relation != null)
1025
                {
1026
                    Equipment equipment = equipments.Find(x => x.UID == relation.UID);
1027
                    equipment.Nozzles.Add(item);
1028
                    row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", equipment.Nozzles.Count + 100));
1029
                    row["Equipment_OID"] = equipment.UID;
1030
                    item.Equipment = equipment;
1031
                }
1032
                row["XCOORDS"] = (item.POINT[0] / DrawingWidth).ToString();
1033
                row["YCOORDS"] = (item.POINT[1] / DrawingHeight).ToString();
1034
                Attribute fluidAttr = item.LineNumber.Attributes.Find(x => x.Name == "FluidCode");
1035
                row["FLUID"] = fluidAttr != null ? fluidAttr.Value : string.Empty;
1036
                Attribute npdAttr = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1037
                row["NPD"] = npdAttr != null ? npdAttr.Value : string.Empty;
1038
                Attribute pmcAttr = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1039
                row["PMC"] = pmcAttr != null ? pmcAttr.Value : string.Empty;
1040

    
1041
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
1042
                if (angle >= Math.PI * 2)
1043
                    angle = angle - Math.PI * 2;
1044
                row["ROTATION"] = angle.ToString();
1045

    
1046
                if (item.Topology.Items.First().Equals(item))
1047
                    row["FlowDirection"] = "Outlet";
1048
                else if (item.Topology.Items.Last().Equals(item))
1049
                    row["FlowDirection"] = "Inlet";
1050
                else
1051
                    row["FlowDirection"] = string.Empty;
1052

    
1053
                nozzleDT.Rows.Add(row);
1054
            }
1055

    
1056
            DataTable equipDT = new DataTable();
1057
            equipDT.Columns.Add("OID", typeof(string));
1058
            equipDT.Columns.Add("ITEMTAG", typeof(string));
1059
            equipDT.Columns.Add("XCOORDS", typeof(string));
1060
            equipDT.Columns.Add("YCOORDS", typeof(string));
1061

    
1062
            foreach (Equipment equipment in equipments)
1063
            {
1064
                DataRow row = equipDT.NewRow();
1065
                row["OID"] = equipment.UID;
1066
                if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
1067
                {
1068
                    Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
1069
                    if (attribute != null)
1070
                        equipment.ItemTag = attribute.Value;
1071
                }
1072
                else
1073
                    equipment.ItemTag = equipment.Name;
1074

    
1075
                row["ITEMTAG"] = equipment.ItemTag;
1076
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
1077
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
1078

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

    
1082
                equipDT.Rows.Add(row);
1083
            }
1084

    
1085
            Equipment = equipDT;
1086
            Nozzle = nozzleDT;
1087
        }
1088

    
1089
        private void SavePSNData()
1090
        {
1091
            try
1092
            {
1093
                DataTable pathItemsDT = new DataTable();
1094
                pathItemsDT.Columns.Add("OID", typeof(string));
1095
                pathItemsDT.Columns.Add("SequenceData_OID", typeof(string));
1096
                pathItemsDT.Columns.Add("TopologySet_OID", typeof(string));
1097
                pathItemsDT.Columns.Add("BranchTopologySet_OID", typeof(string));
1098
                pathItemsDT.Columns.Add("PipeLine_OID", typeof(string));
1099
                pathItemsDT.Columns.Add("ITEMNAME", typeof(string));
1100
                pathItemsDT.Columns.Add("ITEMTAG", typeof(string));
1101
                pathItemsDT.Columns.Add("DESCRIPTION", typeof(string));
1102
                pathItemsDT.Columns.Add("Class", typeof(string));
1103
                pathItemsDT.Columns.Add("SubClass", typeof(string));
1104
                pathItemsDT.Columns.Add("TYPE", typeof(string));
1105
                pathItemsDT.Columns.Add("PIDNAME", typeof(string));
1106
                pathItemsDT.Columns.Add("Equipment_OID", typeof(string));
1107
                pathItemsDT.Columns.Add("NPD", typeof(string));
1108
                pathItemsDT.Columns.Add("GROUPTAG", typeof(string));
1109
                pathItemsDT.Columns.Add("PipeSystemNetwork_OID", typeof(string));
1110
                pathItemsDT.Columns.Add("ViewPipeSystemNetwork_OID", typeof(string));
1111
                pathItemsDT.Columns.Add("PipeRun_OID", typeof(string));
1112

    
1113
                DataTable sequenceDataDT = new DataTable();
1114
                sequenceDataDT.Columns.Add("OID", typeof(string));
1115
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
1116
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
1117
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1118

    
1119
                DataTable pipeSystemNetworkDT = new DataTable();
1120
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
1121
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
1122
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
1123
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
1124
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
1125
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
1126
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
1127
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
1128
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
1129
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
1130
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
1131
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
1132
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
1133
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
1134
                pipeSystemNetworkDT.Columns.Add("Pocket", typeof(string));
1135

    
1136
                DataTable topologySetDT = new DataTable();
1137
                topologySetDT.Columns.Add("OID", typeof(string));
1138
                topologySetDT.Columns.Add("Type", typeof(string));
1139
                topologySetDT.Columns.Add("SubType", typeof(string));
1140
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
1141
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
1142
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
1143
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
1144

    
1145
                DataTable pipelineDT = new DataTable();
1146
                pipelineDT.Columns.Add("OID", typeof(string));
1147
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
1148
                pipelineDT.Columns.Add("FLUID", typeof(string));
1149
                pipelineDT.Columns.Add("PMC", typeof(string));
1150
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
1151
                pipelineDT.Columns.Add("INSULATION", typeof(string));
1152
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
1153
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
1154
                pipelineDT.Columns.Add("Unit", typeof(string));
1155

    
1156
                DataTable pipesystemDT = new DataTable();
1157
                pipesystemDT.Columns.Add("OID", typeof(string));
1158
                pipesystemDT.Columns.Add("DESCRIPTION", typeof(string));
1159
                pipesystemDT.Columns.Add("FLUID", typeof(string));
1160
                pipesystemDT.Columns.Add("PMC", typeof(string));
1161
                pipesystemDT.Columns.Add("PipeLineQty", typeof(string));
1162
                pipesystemDT.Columns.Add("GroundLevel", typeof(string));
1163

    
1164
                // Set Vent/Drain Info
1165
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
1166
                DataTable dt = DB.SelectVentDrainSetting();
1167
                foreach (DataRow row in dt.Rows)
1168
                {
1169
                    string groupID = row["GROUP_ID"].ToString();
1170
                    string desc = row["DESCRIPTION"].ToString();
1171
                    int index = Convert.ToInt32(row["INDEX"]);
1172
                    string name = row["NAME"].ToString();
1173

    
1174
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
1175
                    if (ventDrainInfo == null)
1176
                    {
1177
                        ventDrainInfo = new VentDrainInfo(groupID);
1178
                        ventDrainInfo.Description = desc;
1179
                        VentDrainInfos.Add(ventDrainInfo);
1180
                    }
1181

    
1182
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
1183
                    {
1184
                        Index = index,
1185
                        Name = name
1186
                    });
1187
                }
1188
                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1189
                    ventDrainInfo.VentDrainItems = ventDrainInfo.VentDrainItems.OrderBy(x => x.Index).ToList();
1190

    
1191
                #region Keyword Info
1192
                KeywordInfo KeywordInfos = new KeywordInfo();
1193
                DataTable dtKeyword = DB.SelectKeywordsSetting();
1194
                foreach (DataRow row in dtKeyword.Rows)
1195
                {
1196
                    int index = Convert.ToInt32(row["INDEX"]);
1197
                    string name = row["NAME"].ToString();
1198
                    string keyword = row["KEYWORD"].ToString();
1199

    
1200
                    //KeywordInfo keywordInfo = new KeywordInfo();   
1201
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
1202
                    {
1203
                        Index = index,
1204
                        Name = name,
1205
                        Keyword = keyword
1206
                    });
1207
                }
1208
                #endregion
1209

    
1210
                #region ValveGrouping Info
1211
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
1212
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
1213
                foreach (DataRow row in dtValveGroupung.Rows)
1214
                {
1215
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
1216
                    {
1217
                        OID = row["OID"].ToString(),
1218
                        GroupType = row["GroupType"].ToString(),
1219
                        TagIdentifier = row["TagIdentifier"].ToString(),
1220
                        AttributeName = row["AttributeName"].ToString(),
1221
                        SppidSymbolName = row["SppidSymbolName"].ToString()
1222
                    });
1223
                }
1224
                #endregion
1225

    
1226
                #region EquipmentNoPocket Info
1227
                EquipmentNoPocketInfo EquipmentNoPocket = new EquipmentNoPocketInfo();
1228
                DataTable dtEquipmentNoPocket = DB.SelectEquipmentNoPocketSetting();
1229
                foreach (DataRow row in dtEquipmentNoPocket.Rows)
1230
                {
1231
                    EquipmentNoPocket.EquipmentNoPocketItem.Add(new EquipmentNoPocketItem()
1232
                    {
1233
                        Index = Convert.ToInt32(row["INDEX"]),
1234
                        Type = row["TYPE"].ToString(),
1235
                        Name = row["NAME"].ToString()
1236
                    });
1237
                }
1238
                #endregion
1239

    
1240
                // key = 미입력 branch
1241
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
1242
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
1243
                DataTable PSNFluidDT = DB.SelectPSNFluidCode();
1244
                DataTable PSNPMCDT = DB.SelectPSNPIPINGMATLCLASS();
1245
                foreach (PSNItem PSNItem in PSNItems)
1246
                {
1247
                    try
1248
                    {
1249
                        int psnOrder = 0;
1250
                        int index = 0;
1251
                        bool bPSNStart = true;
1252
                        string sPSNData = string.Empty;
1253
                        bool bVentDrain = false;
1254

    
1255
                        List<Group> Groups = PSNItem.Groups;
1256
                        Dictionary<string, List<Item>> keyValuePairs = new Dictionary<string, List<Item>>();
1257
                        List<Item> valveGroupingItem = new List<Item>();
1258

    
1259
                        //VentDrain 검사
1260
                        if (PSNItem.Groups.Count.Equals(1))
1261
                        {
1262
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
1263
                            for (int g = 0; g < Groups.Count; g++)
1264
                            {
1265
                                Group group = Groups[g];
1266
                                for (int i = 0; i < group.Items.Count; i++)
1267
                                {
1268
                                    Item item = group.Items[i];
1269
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1270
                                    {
1271
                                        if (endInfos.Contains(ventDrainInfo))
1272
                                            continue;
1273

    
1274
                                        if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1275
                                        {
1276
                                            endInfos.Add(ventDrainInfo);
1277
                                            continue;
1278
                                        }
1279

    
1280
                                        if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
1281
                                        {
1282
                                            bVentDrain = true;
1283
                                            break;
1284
                                        }
1285
                                    }
1286

    
1287
                                    if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
1288
                                        break;
1289
                                }
1290

    
1291
                                if (!bVentDrain)
1292
                                {
1293
                                    endInfos = new List<VentDrainInfo>();
1294
                                    for (int i = 0; i < group.Items.Count; i++)
1295
                                    {
1296
                                        Item item = group.Items[group.Items.Count - i - 1];
1297
                                        foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
1298
                                        {
1299
                                            if (endInfos.Contains(ventDrainInfo))
1300
                                                continue;
1301

    
1302
                                            if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
1303
                                            {
1304
                                                endInfos.Add(ventDrainInfo);
1305
                                                continue;
1306
                                            }
1307

    
1308
                                            if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
1309
                                            {
1310
                                                bVentDrain = true;
1311
                                                break;
1312
                                            }
1313
                                        }
1314

    
1315
                                        if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
1316
                                            break;
1317
                                    }
1318
                                }
1319
                            }
1320
                        }
1321

    
1322
                        try
1323
                        {
1324
                            foreach (Group group in PSNItem.Groups)
1325
                            {
1326
                                foreach (Item item in group.Items)
1327
                                {
1328
                                    string VgTag = string.Empty;
1329
                                    if (ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).Count() > 0)
1330
                                    {
1331
                                        ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).First();
1332
                                        string value = string.Empty;
1333

    
1334
                                        if (valveitem.GroupType == "Scope Break" || valveitem.AttributeName == "NoSelection")
1335
                                            value = "NoSelection";
1336
                                        else
1337
                                            value = item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
1338

    
1339
                                        if (valveitem.GroupType == "Scope Break")
1340
                                            VgTag = "Scope Break";
1341
                                        else
1342
                                            VgTag = valveitem.SppidSymbolName + "\\" + value;
1343

    
1344
                                    }
1345

    
1346
                                    string PathitemUID = string.Empty;
1347
                                    if (item.BranchItems.Count == 0)
1348
                                    {
1349
                                        PathitemUID = item.UID;
1350
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
1351
                                        CreateSequenceDataDataRow(PathitemUID);
1352
                                        index++;
1353
                                    }
1354
                                    else
1355
                                    {
1356
                                        PathitemUID = item.UID + "_L1";
1357
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
1358
                                        CreateSequenceDataDataRow(PathitemUID);
1359
                                        index++;
1360
                                        for (int i = 0; i < item.BranchItems.Count; i++)
1361
                                        {
1362
                                            CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", string.Empty, item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
1363
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
1364
                                            index++;
1365

    
1366
                                            CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
1367
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
1368
                                            index++;
1369

    
1370
                                            if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
1371
                                                startBranchDic.Add(item.BranchItems[i], item);
1372
                                            else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
1373
                                                endBranchDic.Add(item.BranchItems[i], item);
1374
                                        }
1375
                                    }
1376

    
1377
                                    if (bPSNStart)
1378
                                    {
1379
                                        CreatePipeSystemNetworkDataRow();
1380
                                        sPSNData = item.TopologyData;
1381
                                        psnOrder++;
1382
                                        bPSNStart = false;
1383
                                    }
1384
                                    else
1385
                                    {
1386
                                        if (item.TopologyData != sPSNData)
1387
                                        {
1388
                                            CreatePipeSystemNetworkDataRow();
1389
                                            sPSNData = item.TopologyData;
1390
                                            psnOrder++;
1391
                                        }
1392
                                    }
1393

    
1394
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string GROUPTAG = "", string branchTopologyName = "", Item branchItem = null)
1395
                                    {
1396
                                        DataRow newRow = pathItemsDT.NewRow();
1397

    
1398
                                        if (itemType == "Nozzles")
1399
                                        {
1400
                                            newRow["Equipment_OID"] = item.Equipment.UID;
1401
                                        }
1402

    
1403
                                        newRow["OID"] = itemOID;
1404
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1405
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
1406
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
1407
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
1408
                                        newRow["ITEMNAME"] = GetItemName(item, itemOID);
1409
                                        newRow["ITEMTAG"] = GetItemTag(item);
1410
                                        newRow["Class"] = GetClass(item, itemOID);
1411
                                        string subClass = GetSubClass(item, itemOID);
1412
                                        newRow["SubClass"] = subClass;
1413

    
1414
                                        if (item.ItemType == ItemType.Symbol)
1415
                                            newRow["TYPE"] = item.ID2DBName;
1416
                                        else if (item.ItemType == ItemType.Line)
1417
                                            newRow["TYPE"] = item.ID2DBType;
1418
                                        newRow["PIDNAME"] = group.Document.DrawingName;
1419

    
1420
                                        // NPD
1421
                                        if (item.LineNumber != null)
1422
                                        {
1423
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1424
                                            if (attribute != null)
1425
                                                newRow["NPD"] = attribute.Value;
1426
                                        }
1427
                                        else
1428
                                            newRow["NPD"] = null;
1429

    
1430
                                        newRow["GROUPTAG"] = GROUPTAG;
1431
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1432
                                        if (branchItem == null)
1433
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
1434
                                        else
1435
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
1436

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

    
1439
                                        pathItemsDT.Rows.Add(newRow);
1440
                                    }
1441
                                    void CreateSequenceDataDataRow(string itemOID)
1442
                                    {
1443
                                        DataRow newRow = sequenceDataDT.NewRow();
1444
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
1445
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
1446
                                        newRow["PathItem_OID"] = itemOID;
1447
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1448

    
1449
                                        sequenceDataDT.Rows.Add(newRow);
1450
                                    }
1451
                                    void CreatePipeSystemNetworkDataRow()
1452
                                    {
1453
                                        LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1454
                                        string FluidCode = string.Empty;
1455
                                        if (lineNumber != null)
1456
                                        {
1457
                                            List<Attribute> att = lineNumber.Attributes;
1458
                                            if (att != null)
1459
                                            {
1460
                                                List<string> oid = new List<string>();
1461
                                                FluidCode = att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault() != null ? att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault().Value : string.Empty;
1462
                                                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;
1463
                                                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;
1464
                                                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;
1465
                                                //InsulationPurpose
1466
                                                if (!string.IsNullOrEmpty(FluidCode)) oid.Add(FluidCode);
1467
                                                if (!string.IsNullOrEmpty(PMC)) oid.Add(PMC);
1468

    
1469
                                                string PipeSystem_OID = string.Join("-", oid);
1470

    
1471
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
1472
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
1473

    
1474
                                                string OID = string.Join("-", oid);
1475
                                                string FluidCodeGL = string.Empty;
1476
                                                string PMCGL = string.Empty;
1477

    
1478

    
1479
                                                if (pipelineDT.Select(string.Format("OID = '{0}'", OID)).Count() == 0)
1480
                                                {
1481
                                                    DataRow newPipelineRow = pipelineDT.NewRow();
1482
                                                    newPipelineRow["OID"] = OID;
1483
                                                    newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
1484
                                                    newPipelineRow["FLUID"] = FluidCode;
1485
                                                    newPipelineRow["PMC"] = PMC;
1486
                                                    newPipelineRow["SEQNUMBER"] = SEQNUMBER;
1487
                                                    newPipelineRow["INSULATION"] = INSULATION;
1488
                                                    newPipelineRow["FROM_DATA"] = string.Empty;
1489
                                                    newPipelineRow["TO_DATA"] = string.Empty;
1490
                                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
1491
                                                    pipelineDT.Rows.Add(newPipelineRow);
1492
                                                }
1493

    
1494
                                                if (pipesystemDT.Select(string.Format("OID = '{0}'", PipeSystem_OID)).Count() == 0)
1495
                                                {
1496
                                                    DataRow newPipesystemRow = pipesystemDT.NewRow();
1497
                                                    newPipesystemRow["OID"] = PipeSystem_OID;
1498
                                                    newPipesystemRow["DESCRIPTION"] = string.Empty;
1499
                                                    newPipesystemRow["FLUID"] = FluidCode;
1500
                                                    newPipesystemRow["PMC"] = PMC;
1501
                                                    newPipesystemRow["PipeLineQty"] = string.Empty;
1502
                                                    string GroundLevel = string.Empty;
1503
                                                    if (!string.IsNullOrEmpty(FluidCode) && !string.IsNullOrEmpty(PMC))
1504
                                                    {
1505
                                                        FluidCodeGL = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("GroundLevel");
1506
                                                        PMCGL = PSNPMCDT.Select(string.Format("Code= '{0}'", PMC)).FirstOrDefault().Field<string>("GroundLevel");
1507
                                                        if (FluidCodeGL == "AG" && PMCGL == "AG")
1508
                                                            GroundLevel = "AG";
1509
                                                        else if (FluidCodeGL == "UG" && PMCGL == "UG")
1510
                                                            GroundLevel = "UG";
1511
                                                        else
1512
                                                            GroundLevel = "AG_UG";
1513
                                                    }
1514
                                                    newPipesystemRow["GroundLevel"] = GroundLevel;
1515

    
1516
                                                    pipesystemDT.Rows.Add(newPipesystemRow);
1517
                                                }
1518
                                            }
1519
                                        }
1520

    
1521
                                        DataRow newRow = pipeSystemNetworkDT.NewRow();
1522
                                        newRow["OID"] = PSNItem.PSN_OID();
1523

    
1524
                                        newRow["OrderNumber"] = psnOrder;
1525
                                        newRow["Pipeline_OID"] = item.PSNPipeLineID;
1526
                                        PSNItem.KeywordInfos = KeywordInfos;
1527
                                        PSNItem.Nozzle = Nozzle;
1528

    
1529
                                        string FromType = string.Empty;
1530
                                        Item From_item = new Item();
1531

    
1532
                                        string FROM_DATA = PSNItem.GetFromData(ref FromType, ref From_item);
1533
                                        string status = string.Empty;
1534
                                        if (psnOrder == 0)
1535
                                        {
1536
                                            status = PSNItem.Status;
1537
                                        }
1538

    
1539
                                        if (PSNItem.IsKeyword)
1540
                                        {
1541
                                            PSNItem.StartType = PSNType.Equipment;
1542
                                        }
1543
                                        string ToType = string.Empty;
1544
                                        Item To_item = new Item();
1545
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item);
1546
                                        if (PSNItem.IsKeyword)
1547
                                        {
1548
                                            PSNItem.EndType = PSNType.Equipment;
1549
                                        }
1550

    
1551
                                        //if (Groups.Count == psnOrder + 1 && !string.IsNullOrEmpty(PSNItem.Status))
1552
                                        //{
1553
                                        if (!string.IsNullOrEmpty(PSNItem.Status))
1554
                                            status += PSNItem.Status;
1555
                                        //}
1556

    
1557
                                        newRow["FROM_DATA"] = FROM_DATA;
1558
                                        newRow["TO_DATA"] = TO_DATA;
1559
                                        newRow["Type"] = PSNItem.GetPSNType();
1560

    
1561
                                        if (psnOrder > 0)
1562
                                        {
1563
                                            DataRow dr = pipeSystemNetworkDT.Select(string.Format("OID = '{0}' AND OrderNumber = {1}", PSNItem.PSN_OID(), psnOrder - 1)).FirstOrDefault();
1564
                                            if (!string.IsNullOrEmpty(PSNItem.Status))
1565
                                            {//status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
1566
                                                if (dr["Status"].ToString().Contains(PSNItem.Status))
1567
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status, string.Empty);
1568
                                                else if (dr["Status"].ToString().Contains(PSNItem.Status.Remove(0, 2)))
1569
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status.Remove(0, 2), string.Empty);
1570

    
1571
                                            }
1572

    
1573
                                            if (dr != null)
1574
                                            {
1575
                                                newRow["FROM_DATA"] = dr.Field<string>("FROM_DATA");
1576
                                                newRow["TO_DATA"] = dr.Field<string>("TO_DATA");
1577
                                                newRow["Type"] = dr.Field<string>("Type");
1578
                                            }
1579
                                        }
1580

    
1581
                                        status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
1582
                                        if (group.Items.Count == 1 && !string.IsNullOrEmpty(status))
1583
                                        {
1584
                                            MatchCollection matches = Regex.Matches(status, "Missing LineNumber_1");
1585
                                            int cnt = matches.Count;
1586
                                            if (cnt > 1)
1587
                                                status.Replace(", Missing LineNumber_1", string.Empty);
1588
                                        }
1589
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
1590
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
1591

    
1592

    
1593
                                        newRow["IsValid"] = PSNItem.IsValid;
1594
                                        newRow["Status"] = status;
1595
                                        newRow["PBS"] = PSNItem.GetPBSData();
1596

    
1597
                                        List<string> drawingNames = new List<string>();
1598
                                        foreach (Group _group in PSNItem.Groups)
1599
                                        {
1600
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
1601
                                            {
1602
                                                if (drawingNames.Count == 0)
1603
                                                    newRow["Drawings"] = _group.Document.DrawingName;
1604
                                                else
1605
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
1606
                                                drawingNames.Add(_group.Document.DrawingName);
1607
                                            }
1608
                                        }
1609

    
1610
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
1611
                                        if (bVentDrain)
1612
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
1613
                                        else
1614
                                            newRow["IncludingVirtualData"] = "No";
1615
                                        //    return;
1616
                                        //newRow["IncludingVirtualData"] = "No";
1617
                                        newRow["PSNAccuracy"] = "100";
1618

    
1619
                                        string Pocket = "No";
1620
                                        string Condition = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("Condition");
1621
                                        if (Condition.Equals("Flare"))
1622
                                            Pocket = "Yes";
1623

    
1624
                                        if (item.ID2DBType == "Nozzles" && PSNItem.StartType == PSNType.Equipment) 
1625
                                        {
1626
                                          //  string itemName = From_item.Name;
1627
                                            Equipment Equipment = From_item.Equipment;
1628
                                      
1629
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name && x.Type != "Pump").FirstOrDefault();
1630
                                          
1631

    
1632
                                            if (nopocket != null)
1633
                                            {
1634
                                                DataRow bNozzle = null;
1635
                                                if (nopocket.Type.Equals("Vertical Vessel"))
1636
                                                {
1637
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, From_item.UID)).FirstOrDefault();
1638
                                                    if (drNozzle != null)
1639
                                                    {
1640
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
1641
                                                        {
1642
                                                            bNozzle = drNozzle;
1643
                                                        }
1644

    
1645
                                                        if (bNozzle == null)
1646
                                                        {
1647
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
1648

    
1649
                                                            if (drNozzle != null)
1650
                                                            {
1651
                                                                bNozzle = drNozzle;
1652
                                                                foreach (DataRow it in nozzleRows)
1653
                                                                {
1654
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
1655
                                                                    {
1656
                                                                        bNozzle = null;
1657
                                                                        break;
1658
                                                                    }
1659
                                                                }
1660
                                                            }
1661
                                                        }
1662
                                                    }
1663

    
1664
                                                    if (bNozzle != null)
1665
                                                        Pocket = "Yes";
1666
                                                }
1667
                                                else
1668
                                                    Pocket = "Yes";
1669
                                            }
1670
                                        }
1671
                                        
1672
                                        if (item.ID2DBType == "Nozzles" && PSNItem.EndType == PSNType.Equipment) //To는 전체
1673
                                        {
1674
                                           // string itemName = To_item.Name;
1675
                                            Equipment Equipment = To_item.Equipment;
1676
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name).FirstOrDefault();
1677
                                            if (nopocket != null)
1678
                                            {
1679
                                                DataRow bNozzle = null;
1680
                                                if (nopocket.Type.Equals("Vertical Vessel"))
1681
                                                {
1682
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, To_item.UID)).FirstOrDefault();
1683
                                                    if(drNozzle != null)
1684
                                                    {
1685
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
1686
                                                        {
1687
                                                            bNozzle = drNozzle;
1688
                                                        }
1689

    
1690
                                                        if (bNozzle == null)
1691
                                                        {
1692
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
1693

    
1694
                                                            if (drNozzle != null)
1695
                                                            {
1696
                                                                bNozzle = drNozzle;
1697
                                                                foreach (DataRow it in nozzleRows)
1698
                                                                {
1699
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
1700
                                                                    {
1701
                                                                        bNozzle = null;
1702
                                                                        break;
1703
                                                                    }
1704
                                                                }
1705
                                                            }
1706
                                                        }
1707
                                                    }                                                   
1708

    
1709
                                                    if (bNozzle != null)
1710
                                                        Pocket = "Yes";
1711
                                                }
1712
                                                else
1713
                                                    Pocket = "Yes";
1714
                                            }
1715
                                        }
1716
                                        
1717
                                        newRow["Pocket"] = Pocket;
1718
                                        
1719
                                        pipeSystemNetworkDT.Rows.Add(newRow);
1720
                                    }
1721
                                }
1722

    
1723
                            }
1724
                        
1725

    
1726
                        }
1727
                        catch (Exception ex)
1728
                        {
1729
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1730
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1731
                        }
1732

    
1733
                        //TopologySet 관련
1734
                        foreach (Topology topology in PSNItem.Topologies)
1735
                        {
1736
                            DataRow newRow = topologySetDT.NewRow();
1737
                            newRow["OID"] = topology.FullName;
1738
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
1739
                            if (bVentDrain)
1740
                                newRow["SubType"] = "Vent_Drain";
1741
                            else
1742
                                newRow["SubType"] = null;
1743
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
1744
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
1745
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
1746
                            newRow["TailItemSPID"] = topology.Items.First().UID;
1747
                            topologySetDT.Rows.Add(newRow);
1748
                        }
1749

    
1750
                    }
1751
                    catch (Exception ee)
1752
                    {
1753

    
1754
                    }
1755
                }
1756

    
1757

    
1758
                foreach (var item in startBranchDic)
1759
                {
1760
                    string uid = item.Key.UID;
1761
                    string topologyName = item.Value.Topology.FullName;
1762
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1763

    
1764
                    if (rows.Length == 1)
1765
                    {
1766
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1767
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1768
                    }
1769
                    else if (rows.Length > 1)
1770
                    {
1771
                        DataRow targetRow = null;
1772
                        int index = int.MaxValue;
1773
                        foreach (DataRow row in rows)
1774
                        {
1775
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1776
                            if (split.StartsWith("L"))
1777
                            {
1778
                                int num = Convert.ToInt32(split.Remove(0, 1));
1779
                                if (index > num)
1780
                                {
1781
                                    index = num;
1782
                                    targetRow = row;
1783
                                }
1784
                            }
1785
                        }
1786

    
1787
                        if (targetRow != null)
1788
                        {
1789
                            targetRow["BranchTopologySet_OID"] = topologyName;
1790
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1791
                        }
1792
                    }
1793
                }
1794

    
1795
                foreach (var item in endBranchDic)
1796
                {
1797
                    string uid = item.Key.UID;
1798
                    string topologyName = item.Value.Topology.FullName;
1799
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1800
                    if (rows.Length == 1)
1801
                    {
1802
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1803
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1804
                    }
1805
                    else if (rows.Length > 1)
1806
                    {
1807
                        DataRow targetRow = null;
1808
                        int index = int.MinValue;
1809
                        foreach (DataRow row in rows)
1810
                        {
1811
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1812
                            if (split.StartsWith("L"))
1813
                            {
1814
                                int num = Convert.ToInt32(split.Remove(0, 1));
1815
                                if (index < num)
1816
                                {
1817
                                    index = num;
1818
                                    targetRow = row;
1819
                                }
1820
                            }
1821
                        }
1822

    
1823
                        if (targetRow != null)
1824
                        {
1825
                            targetRow["BranchTopologySet_OID"] = topologyName;
1826
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1827
                        }
1828
                    }
1829
                }
1830

    
1831
                PathItems = pathItemsDT;
1832
                SequenceData = sequenceDataDT;
1833
                PipeSystemNetwork = pipeSystemNetworkDT;
1834
                TopologySet = topologySetDT;
1835
                PipeLine = pipelineDT;
1836
                PipeSystem = pipesystemDT;
1837
            }
1838
            catch (Exception ex)
1839
            {
1840
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1841
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1842
            }
1843
        }
1844

    
1845
        private double AccuracyCalculation(List<double> lstAcc, double acc)
1846
        {
1847
            foreach (double lacc in lstAcc)
1848
            {
1849
                acc *= lacc;
1850
            }
1851
            return acc;
1852
        }
1853

    
1854
        private void UpdateSubType()
1855
        {
1856
            try
1857
            {
1858
                foreach (PSNItem PSNItem in PSNItems)
1859
                {
1860
                    if (PSNItem.IsBypass)
1861
                    {
1862
                        foreach (Topology topology in PSNItem.Topologies)
1863
                        {
1864
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1865
                            if (rows.Length.Equals(1))
1866
                                rows.First()["SubType"] = "Bypass";
1867
                        }
1868
                    }
1869

    
1870
                    if (PSNItem.StartType == PSNType.Header)
1871
                    {
1872
                        Topology topology = PSNItem.Topologies.First();
1873
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1874
                        if (rows.Length.Equals(1))
1875
                            rows.First()["SubType"] = "Header";
1876
                    }
1877
                    else if (PSNItem.EndType == PSNType.Header)
1878
                    {
1879
                        Topology topology = PSNItem.Topologies.Last();
1880
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1881
                        if (rows.Length.Equals(1))
1882
                            rows.First()["SubType"] = "Header";
1883
                    }
1884
                }
1885

    
1886

    
1887
                foreach (Topology topology in Topologies)
1888
                {
1889
                    try
1890
                    {
1891
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1892

    
1893
                        if (rows.Count() > 0)
1894
                        {
1895
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
1896
                            {
1897
                                if (topology.Items == null)
1898
                                    continue;
1899

    
1900
                                Item firstItem = topology.Items.First();
1901
                                Item lastItem = topology.Items.Last();
1902

    
1903
                                List<Relation> relations = new List<Relation>();
1904

    
1905
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1906
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1907

    
1908
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1909
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1910

    
1911
                                if (relations.Count > 0)
1912
                                    rows.First()["SubType"] = "OtherSystem";
1913
                            }
1914
                        }
1915
                    }
1916
                    catch (Exception ex)
1917
                    {
1918

    
1919
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1920
                    }
1921
                }
1922

    
1923
                foreach (DataRow row in TopologySet.Rows)
1924
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
1925
                        row["SubType"] = "Normal";
1926
            }
1927
            catch (Exception ex)
1928
            {
1929
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1930
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1931
            }
1932
        }
1933

    
1934
        private bool IsBypass(PSNItem PSNItem)
1935
        {
1936
            bool bResult = false;
1937

    
1938
            if (PSNItem.GetPSNType() == "B2B")
1939
            {
1940
                Group firstGroup = PSNItem.Groups.First();
1941
                Group lastGroup = PSNItem.Groups.Last();
1942
                Item firstItem = firstGroup.Items.First();
1943
                Item lastItem = lastGroup.Items.Last();
1944

    
1945
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
1946
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
1947

    
1948
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
1949
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
1950
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
1951
                    bResult = true;
1952
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
1953
                    bResult = true;
1954
            }
1955

    
1956
            Item GetConnectedItemByPSN(Item item)
1957
            {
1958
                Item result = null;
1959

    
1960
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
1961
                if (relation != null)
1962
                    result = relation.Item;
1963

    
1964

    
1965
                return result;
1966
            }
1967

    
1968
            return bResult;
1969
        }
1970

    
1971
        private void DeleteVentDrain()
1972
        {
1973
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
1974

    
1975
            foreach (DataRow dataRow in ventdrainRows)
1976
            {
1977
                dataRow.Delete();
1978
            }
1979
        }
1980

    
1981
        private void UpdateAccuracy()
1982
        {
1983
            //DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
1984
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'");
1985
            List<double> lstAcc = null;
1986
            string Status = string.Empty;
1987

    
1988
            foreach (DataRow dataRow in statusRows)
1989
            {
1990
                lstAcc = new List<double>();
1991
                Status = dataRow.Field<string>("Status");
1992
                if (!string.IsNullOrEmpty(Status))
1993
                {
1994
                    string[] arrStatus = Status.Split(',');
1995
                    foreach (string arrstr in arrStatus)
1996
                    {
1997
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
1998
                            lstAcc.Add(0.75);
1999

    
2000
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
2001
                            lstAcc.Add(0.7);
2002

    
2003
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
2004
                            lstAcc.Add(0.5);
2005

    
2006
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
2007
                            lstAcc.Add(0.65);
2008

    
2009
                        if (arrstr.Contains(Rule5)) //Line Disconnected
2010
                            lstAcc.Add(0.6);
2011
                    }
2012
                }
2013

    
2014
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
2015
                if (PSNAccuracy == "100")
2016
                    PSNAccuracy = "1";
2017

    
2018
                PSNAccuracy = Convert.ToString(Convert.ToDecimal(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))));
2019
                //if (PSNAccuracy != "100")
2020
                //{
2021
                //    //dataRow["IncludingVirtualData"] = "No";
2022
                dataRow["PSNAccuracy"] = PSNAccuracy;
2023
                //}
2024
            }
2025
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
2026
            foreach (DataRow dr in dt.Rows)
2027
            {
2028
                string oid = dr.Field<string>("OID");
2029
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
2030
                double totalDdr = 0;
2031
                foreach (DataRow ddr in select)
2032
                {
2033
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
2034
                    if (acc == 100) acc = 1;
2035
                    if (totalDdr == 0) totalDdr = acc;
2036
                    else totalDdr *= acc;
2037
                }
2038

    
2039
                totalDdr *= 100;
2040

    
2041
                if (totalDdr != 100)
2042
                {
2043
                    foreach (DataRow ddr in select)
2044
                    {
2045
                        ddr["IncludingVirtualData"] = "Yes";
2046
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2047
                    }
2048
                }
2049
                else
2050
                {
2051
                    foreach (DataRow ddr in select)
2052
                    {
2053
                        ddr["IncludingVirtualData"] = "No";
2054
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2055
                    }
2056
                }
2057
            }
2058

    
2059
        }
2060

    
2061
        private void UpdateKeywordForPSN()
2062
        {
2063
            #region Keyword Info
2064
            KeywordInfo KeywordInfos = new KeywordInfo();
2065
            DataTable dtKeyword = DB.SelectKeywordsSetting();
2066
            foreach (DataRow row in dtKeyword.Rows)
2067
            {
2068
                int index = Convert.ToInt32(row["INDEX"]);
2069
                string name = row["NAME"].ToString();
2070
                string keyword = row["KEYWORD"].ToString();
2071

    
2072
                //KeywordInfo keywordInfo = new KeywordInfo();   
2073
                KeywordInfos.KeywordItems.Add(new KeywordItem()
2074
                {
2075
                    Index = index,
2076
                    Name = name,
2077
                    Keyword = keyword
2078
                });
2079
            }
2080
            #endregion
2081

    
2082
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
2083
            foreach (DataRow dataRow in endofHeaderRows)
2084
            {
2085
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2086

    
2087
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
2088
                {
2089
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2090
                    DataRow dr = pathItemRows.First();
2091
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
2092
                    dr["TYPE"] = "End";
2093
                    dr["ITEMTAG"] = "ENDOFHEADER";
2094
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2095
                }
2096

    
2097
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
2098
                {
2099
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2100
                    DataRow dr = pathItemRows.Last();
2101
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
2102
                    dr["TYPE"] = "End";
2103
                    dr["ITEMTAG"] = "ENDOFHEADER";
2104
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2105
                }
2106
            }
2107

    
2108
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2109
            {
2110
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
2111
                foreach (DataRow dataRow in keywordRows)
2112
                {
2113
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2114

    
2115
                    if (dataRow.Field<string>("From_Data") == keyitem.Keyword)
2116
                    {
2117
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2118

    
2119
                        //
2120
                        //if(.)
2121
                        if (PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
2122
                        {
2123
                            DataRow dr = pathItemRows.First();
2124
                            //dr["CLASS"] = ""; //Type
2125
                            dr["TYPE"] = "End";
2126
                            dr["ITEMTAG"] = keyitem.Keyword;
2127
                            dr["DESCRIPTION"] = keyitem.Keyword;
2128
                        }
2129

    
2130
                    }
2131

    
2132
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
2133
                    {
2134
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2135

    
2136
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
2137
                        {
2138
                            DataRow dr = pathItemRows.Last();
2139
                            //dr["CLASS"] = ""; //Type
2140
                            dr["TYPE"] = "End";
2141
                            dr["ITEMTAG"] = keyitem.Keyword;
2142
                            dr["DESCRIPTION"] = keyitem.Keyword;
2143
                            //dr.Field<string>("Type")
2144
                        }
2145

    
2146
                    }
2147
                }
2148
            }
2149
        }
2150

    
2151
        private void UpdateErrorForPSN()
2152
        {
2153
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
2154
            foreach (DataRow dataRow in errorRows)
2155
            {
2156
                try
2157
                {
2158
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2159
                    bool change = false;
2160
                    bool bCheck = false;
2161
                    int bCount = 0;
2162
                    if (!PSNItem.EnableType(PSNItem.StartType))
2163
                    {
2164
                        change = true;
2165
                        bCheck = change;
2166
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2167
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
2168

    
2169
                        Item item = PSNItem.Groups.First().Items.First();
2170
                        try
2171
                        {
2172
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2173

    
2174
                            tieInPointIndex++;
2175

    
2176

    
2177
                            if (item.ItemType == ItemType.Line)
2178
                            {
2179
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2180
                                bCount = 2;
2181

    
2182
                                foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2183
                                {
2184
                                    loopRow["FROM_DATA"] = FROM_DATA;
2185
                                    if (loopRow.Field<string>("OrderNumber") == "0")
2186
                                    {
2187
                                        string status = loopRow.Field<string>("Status");
2188
                                        //string isvali
2189
                                        if (string.IsNullOrEmpty(status))
2190
                                            status = "Line Disconnected";
2191
                                        else if (!status.Contains("Line Disconnected"))
2192
                                            status += ", Line Disconnected";
2193
                                        loopRow["Status"] = status;
2194
                                        if (!string.IsNullOrEmpty(status))
2195
                                            loopRow["IsValid"] = "Error";
2196
                                    }
2197
                                }
2198
                            }
2199
                            else
2200
                            {
2201
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
2202

    
2203
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2204
                                bCount = 3;
2205
                            }
2206

    
2207
                            PSNItem.StartType = PSNType.Equipment;
2208
                        }
2209
                        catch (Exception ex)
2210
                        {
2211
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2212
                            return;
2213
                        }
2214
                    }
2215

    
2216
                    if (!PSNItem.EnableType(PSNItem.EndType))
2217
                    {
2218
                        change = true;
2219
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2220
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
2221

    
2222
                        Item item = PSNItem.Groups.Last().Items.Last();
2223
                        try
2224
                        {
2225
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2226

    
2227
                            if (item.ItemType == ItemType.Line)
2228
                            {
2229
                                foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2230
                                {
2231
                                    loopRow["TO_DATA"] = TO_DATA;
2232
                                    if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
2233
                                    {
2234
                                        string status = loopRow.Field<string>("Status");
2235
                                        if (string.IsNullOrEmpty(status))
2236
                                            status = "Line Disconnected";
2237
                                        else if (!status.Contains("Line Disconnected"))
2238
                                            status += ", Line Disconnected";
2239
                                        loopRow["Status"] = status;
2240
                                        if (!string.IsNullOrEmpty(status))
2241
                                            loopRow["IsValid"] = "Error";
2242
                                    }
2243
                                }
2244
                            }
2245

    
2246
                            tieInPointIndex++;
2247

    
2248
                            if (!bCheck)
2249
                            {
2250
                                if (item.ItemType == ItemType.Line)
2251
                                {
2252
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
2253
                                }
2254
                                else
2255
                                {
2256
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
2257
                                    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);
2258
                                }
2259
                            }
2260
                            else
2261
                            {
2262
                                if (item.ItemType == ItemType.Line)
2263
                                {
2264
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows[pathItemRows.Count() - bCount], TO_DATA), insertIndex + 1);
2265
                                }
2266
                                else
2267
                                {
2268
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows[pathItemRows.Count() - bCount], TO_DATA), insertIndex + 1);
2269
                                    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);
2270
                                }
2271
                            }
2272

    
2273

    
2274
                            PSNItem.EndType = PSNType.Equipment;
2275
                        }
2276
                        catch (Exception ex)
2277
                        {
2278
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2279
                            return;
2280
                        }
2281
                    }
2282

    
2283
                    dataRow["Type"] = PSNItem.GetPSNType();
2284
                    if (change)
2285
                    {
2286
                        int rowIndex = 0;
2287
                        for (int i = 0; i < PathItems.Rows.Count; i++)
2288
                        {
2289
                            DataRow row = PathItems.Rows[i];
2290
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
2291
                                continue;
2292
                            string sequenceData = row["SequenceData_OID"].ToString();
2293
                            string[] split = sequenceData.Split(new char[] { '_' });
2294

    
2295
                            StringBuilder sb = new StringBuilder();
2296
                            for (int j = 0; j < split.Length - 1; j++)
2297
                                sb.Append(split[j] + "_");
2298
                            sb.Append(rowIndex++);
2299
                            row["SequenceData_OID"] = sb.ToString();
2300

    
2301
                            DataRow seqItemRows = SequenceData.Select(string.Format("PathItem_OID = '{0}'", row["OID"])).FirstOrDefault();
2302
                            int insertSeqIndex = SequenceData.Rows.IndexOf(seqItemRows);
2303

    
2304
                            string[] splitseq = sb.ToString().Split(new char[] { '_' });
2305

    
2306
                            if (seqItemRows == null)
2307
                            {
2308
                                DataRow newRow = SequenceData.NewRow();
2309
                                newRow["OID"] = sb.ToString();
2310
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2311
                                newRow["PathItem_OID"] = row["OID"];
2312
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
2313
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
2314
                            }
2315
                            else
2316
                            {
2317
                                seqItemRows["OID"] = sb.ToString();
2318
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2319
                                seqItemRows["PathItem_OID"] = row["OID"];
2320
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
2321
                            }
2322
                        }
2323
                    }
2324

    
2325
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
2326
                    {
2327
                        DataRow newRow = PathItems.NewRow();
2328
                        newRow["OID"] = Guid.NewGuid().ToString();
2329
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2330
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2331
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2332
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2333
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
2334
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
2335
                        newRow["DESCRIPTION"] = DATA;
2336
                        newRow["Class"] = "End of line terminator";
2337
                        newRow["SubClass"] = "End of line terminator";
2338
                        newRow["TYPE"] = "End";
2339
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2340
                        newRow["NPD"] = itemRow["NPD"];
2341
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2342
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2343
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2344

    
2345
                        return newRow;
2346
                    }
2347

    
2348
                    DataRow createLineRow(DataRow itemRow)
2349
                    {
2350
                        DataRow newRow = PathItems.NewRow();
2351
                        newRow["OID"] = Guid.NewGuid().ToString();
2352
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2353
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2354
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2355
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2356
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
2357
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
2358
                        newRow["Class"] = itemRow["Class"];
2359
                        newRow["SubClass"] = itemRow["SubClass"];
2360
                        newRow["TYPE"] = itemRow["TYPE"];
2361
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2362
                        newRow["NPD"] = itemRow["NPD"];
2363
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2364
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2365
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2366

    
2367
                        return newRow;
2368
                    }
2369
                }
2370
                catch (Exception ex)
2371
                {
2372

    
2373
                }
2374
            }
2375
        }
2376

    
2377
        private void InsertTeePSN()
2378
        {
2379
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
2380
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
2381
            bool change = false;
2382
            foreach (DataRow dataRow in branchRows)
2383
            {
2384
                try
2385
                {
2386
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2387
                    change = false;
2388

    
2389
                    if (PSNItem.StartType == PSNType.Branch)
2390
                    {
2391
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2392
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
2393
                        Item Teeitem = PSNItem.Groups.First().Items.First();
2394
                        try
2395
                        {
2396
                            if (Teeitem.ItemType == ItemType.Line)
2397
                            {
2398
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
2399
                                {
2400
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
2401
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
2402
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
2403
                                    change = true;
2404
                                }
2405

    
2406
                            }
2407
                        }
2408
                        catch (Exception ex)
2409
                        {
2410
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2411
                            return;
2412
                        }
2413
                    }
2414

    
2415
                    if (PSNItem.EndType == PSNType.Branch)
2416
                    {
2417
                        //change = true;
2418
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2419

    
2420
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
2421

    
2422
                        DataRow dr = pathItemRows.Last();
2423
                        if (change)
2424
                            dr = pathItemRows[pathItemRows.Count() - 2];
2425

    
2426
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
2427

    
2428
                        try
2429
                        {
2430
                            if (Teeitem.ItemType == ItemType.Line)
2431
                            {
2432
                                if (dr.Field<string>("SubClass") != "Tee")
2433
                                {
2434
                                    PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
2435
                                    change = true;
2436
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
2437
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
2438
                                }
2439

    
2440
                            }
2441
                        }
2442
                        catch (Exception ex)
2443
                        {
2444
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2445
                            return;
2446
                        }
2447
                    }
2448

    
2449
                    if (change)
2450
                    {
2451
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2452
                        int rowIndex = 0;
2453
                        for (int i = 0; i < PathItems.Rows.Count; i++)
2454
                        {
2455
                            DataRow row = PathItems.Rows[i];
2456
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
2457
                                continue;
2458
                            string sequenceData = row["SequenceData_OID"].ToString();
2459
                            string[] split = sequenceData.Split(new char[] { '_' });
2460

    
2461
                            StringBuilder sb = new StringBuilder();
2462
                            for (int j = 0; j < split.Length - 1; j++)
2463
                                sb.Append(split[j] + "_");
2464
                            sb.Append(rowIndex++);
2465
                            row["SequenceData_OID"] = sb.ToString();
2466

    
2467
                            DataRow seqItemRows = SequenceData.Select(string.Format("PathItem_OID = '{0}'", row["OID"])).FirstOrDefault();
2468
                            int insertSeqIndex = SequenceData.Rows.IndexOf(seqItemRows);
2469

    
2470
                            string[] splitseq = sb.ToString().Split(new char[] { '_' });
2471

    
2472
                            if (seqItemRows == null)
2473
                            {
2474
                                DataRow newRow = SequenceData.NewRow();
2475
                                newRow["OID"] = sb.ToString();
2476
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2477
                                newRow["PathItem_OID"] = row["OID"];
2478
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
2479
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
2480
                            }
2481
                            else
2482
                            {
2483
                                seqItemRows["OID"] = sb.ToString();
2484
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2485
                                seqItemRows["PathItem_OID"] = row["OID"];
2486
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
2487
                            }
2488
                        }
2489
                    }
2490

    
2491
                    DataRow createTeeRow(DataRow itemRow)
2492
                    {
2493
                        DataRow newRow = PathItems.NewRow();
2494
                        newRow["OID"] = Guid.NewGuid().ToString();
2495
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2496
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2497
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2498
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2499
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
2500
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
2501
                        newRow["DESCRIPTION"] = "";
2502
                        newRow["Class"] = "Branch";
2503
                        newRow["SubClass"] = "Tee";
2504
                        newRow["TYPE"] = itemRow["TYPE"];
2505
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2506
                        newRow["NPD"] = itemRow["NPD"];
2507
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2508
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2509
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2510

    
2511
                        return newRow;
2512
                    }
2513
                }
2514
                catch (Exception ex)
2515
                {
2516

    
2517
                }
2518
            }
2519
        }
2520
    }
2521

    
2522
    public class PSNItem
2523
    {
2524
        public PSNItem(int count, int Revision)
2525
        {
2526
            Groups = new List<Group>();
2527
            Topologies = new List<Topology>();
2528

    
2529
            Index = count + 1;
2530
            this.Revision = Revision;
2531
        }
2532

    
2533
        private int Revision;
2534
        public string UID { get; set; }
2535
        public List<Group> Groups { get; set; }
2536
        public List<Topology> Topologies { get; set; }
2537
        public PSNType StartType { get; set; }
2538
        public PSNType EndType { get; set; }
2539
        public int Index { get; set; }
2540
        public string IsValid { get; set; }
2541
        public bool IsKeyword { get; set; }
2542
        public string Status { get; set; }
2543
        public string IncludingVirtualData { get; set; }
2544
        public string PSNAccuracy { get; set; }
2545
        public KeywordInfo KeywordInfos = new KeywordInfo();
2546
        public DataTable Nozzle = new DataTable();
2547

    
2548
        public string PSN_OID()
2549
        {
2550
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
2551
        }
2552

    
2553
        public string GetPSNType()
2554
        {
2555
            string result = string.Empty;
2556

    
2557
            if (EnableType(StartType) && EnableType(EndType))
2558
            {
2559
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
2560
                    result = "E2E";
2561
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
2562
                    result = "B2B";
2563
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
2564
                    result = "HD2";
2565

    
2566
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
2567
                    result = "E2B";
2568
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
2569
                    result = "B2E";
2570

    
2571
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
2572
                    result = "HDB";
2573
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
2574
                    result = "HDB";
2575

    
2576
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
2577
                    result = "HDE";
2578
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
2579
                    result = "HDE";
2580
                else
2581
                    result = "Error";
2582
            }
2583
            else
2584
                result = "Error";
2585

    
2586
            return result;
2587

    
2588

    
2589
        }
2590

    
2591
        public bool EnableType(PSNType type)
2592
        {
2593
            bool result = false;
2594

    
2595
            if (type == PSNType.Branch ||
2596
                type == PSNType.Equipment ||
2597
                type == PSNType.Header)
2598
            {
2599
                result = true;
2600
            }
2601

    
2602
            return result;
2603
        }
2604

    
2605
        public bool IsBypass { get; set; }
2606

    
2607
        public string GetFromData(ref string Type, ref Item item)
2608
        {
2609
            Status = string.Empty;
2610
            string result = string.Empty;
2611
            if (IsKeyword)
2612
                IsKeyword = false;
2613
            try
2614
            {
2615
                item = Groups.First().Items.First();
2616

    
2617
                if (StartType == PSNType.Header)
2618
                    result = "ENDOFHEADER";
2619
                else if (StartType == PSNType.Branch)
2620
                {
2621
                    //if (!item.MissingLineNumber && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
2622
                    if (!item.MissingLineNumber2 && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
2623
                        result = item.Relations.First().Item.LineNumber.Name;
2624
                    else
2625
                    {
2626
                        IsValid = "Error";
2627
                        Status += ", Missing LineNumber_2";
2628
                        result = "Empty LineNumber";
2629
                    }
2630

    
2631
                    //if (item.MissingLineNumber1)
2632
                    //{
2633
                    //    Status += ", Missing LineNumber_1";
2634
                    //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2635

    
2636
                    //}
2637
                }
2638
                else if (StartType == PSNType.Equipment)
2639
                {
2640
                    if (Groups.First().Items.First().Equipment != null)
2641
                        result = Groups.First().Items.First().Equipment.ItemTag;
2642
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
2643

    
2644
                    if (drNozzle != null)
2645
                        result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
2646
                }
2647
                else
2648
                {
2649
                    IsValid = "Error";
2650
                    item = Groups.First().Items.First();
2651
                    if (item.ItemType == ItemType.Symbol)
2652
                    {
2653

    
2654
                        string keyword = string.Empty;
2655
                        keyword = GetFromKeywordData(ref Type, item);
2656

    
2657
                        if (string.IsNullOrEmpty(keyword))
2658
                        {
2659
                            if (item.ID2DBType.Contains("OPC's"))
2660
                                Status += ", OPC Disconnected";
2661
                            else
2662
                                Status += ", Missing ItemTag or Description";
2663

    
2664
                            result = item.ID2DBName;
2665
                        }
2666
                        else
2667
                        {
2668
                            result = keyword;
2669
                            IsKeyword = true;
2670
                            IsValid = string.Empty;
2671
                        }
2672

    
2673
                    }
2674
                    else if (item.ItemType == ItemType.Line)
2675
                    {
2676

    
2677
                        if (item.MissingLineNumber1)
2678
                        {
2679
                            IsValid = "Error";
2680
                            Status += ", Missing LineNumber_1";
2681
                            result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2682
                        }
2683
                    }
2684
                    else
2685
                        result = "Unknown";
2686

    
2687
                }
2688
            }
2689
            catch (Exception ex)
2690
            {
2691

    
2692
            }
2693

    
2694
            return result;
2695
        }
2696

    
2697
        public string GetFromKeywordData(ref string Type, Item item)
2698
        {
2699
            string result = string.Empty;
2700

    
2701
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2702
            {
2703
                if (keyitem.Name.Equals(item.Name))
2704
                {
2705
                    result = keyitem.Keyword;
2706
                    Type = item.ID2DBType;
2707
                    break;
2708
                }
2709
            }
2710

    
2711
            return result;
2712
        }
2713

    
2714
        public string GetToKeywordData(ref string Type, Item item)
2715
        {
2716
            string result = string.Empty;
2717

    
2718
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2719
            {
2720
                if (keyitem.Name.Equals(item.Name))
2721
                {
2722
                    result = keyitem.Keyword;
2723
                    Type = item.ID2DBType;
2724
                    break;
2725
                }
2726
            }
2727
            return result;
2728
        }
2729

    
2730
        public string GetToData(ref string ToType, ref Item item)
2731
        {
2732
            string result = string.Empty;
2733
            Status = string.Empty;
2734

    
2735
            if (IsKeyword)
2736
                IsKeyword = false;
2737

    
2738
            item = Groups.Last().Items.Last();
2739

    
2740
            if (EndType == PSNType.Header)
2741
                result = "ENDOFHEADER";
2742
            else if (EndType == PSNType.Branch)
2743
            {
2744

    
2745
                
2746
                //if (!item.MissingLineNumber && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
2747
                if (!item.MissingLineNumber2 && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
2748
                    result = item.Relations.Last().Item.LineNumber.Name;
2749
                else
2750
                {
2751
                    IsValid = "Error";
2752
                    Status += ", Missing LineNumber_2";
2753
                    result = "Empty LineNumber";
2754
                }
2755

    
2756
                //if (item.MissingLineNumber1)
2757
                //{
2758
                //    Status += ", Missing LineNumber_1";
2759
                //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2760

    
2761
                //}
2762
            }
2763
            else if (EndType == PSNType.Equipment)
2764
            {
2765
                if (Groups.Last().Items.Last().Equipment != null)
2766
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
2767

    
2768
                DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.Last().Items.Last().UID)).FirstOrDefault();
2769

    
2770
                if (drNozzle != null)
2771
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
2772
            }
2773
            else
2774
            {
2775
                IsValid = "Error";
2776
                item = Groups.Last().Items.Last();
2777
                if (item.ItemType == ItemType.Symbol)
2778
                {
2779
                    string keyword = string.Empty;
2780
                    keyword = GetToKeywordData(ref ToType, item);
2781

    
2782
                    if (string.IsNullOrEmpty(keyword))
2783
                    {
2784
                        if (item.ID2DBType.Contains("OPC's"))
2785
                            Status += ", OPC Disconnected";
2786
                        else
2787
                            Status += ", Missing ItemTag or Description";
2788

    
2789
                        result = item.ID2DBName;
2790
                    }
2791
                    else
2792
                    {
2793
                        result = keyword;
2794
                        IsValid = string.Empty;
2795
                        IsKeyword = true;
2796
                    }
2797

    
2798
                }
2799
                else if (item.ItemType == ItemType.Line)
2800
                {
2801
                    if (item.MissingLineNumber1)
2802
                    {
2803
                        IsValid = "Error";
2804
                        Status += ", Missing LineNumber_1";
2805
                        result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2806
                    }
2807
                }
2808
                else
2809
                    result = "Unknown";
2810

    
2811

    
2812
            }
2813

    
2814

    
2815

    
2816
            return result;
2817
        }
2818

    
2819
        public string GetPBSData()
2820
        {
2821
            string result = string.Empty;
2822
            List<string> PBSList = new List<string>();
2823
            if (Settings.Default.PBSSetting.Equals("Line Number"))
2824
            {
2825
                string attrValue = Settings.Default.PBSSettingValue;
2826

    
2827
                foreach (Group group in Groups)
2828
                {
2829
                    List<LineNumber> lineNumbers = group.Items.Select(x => x.LineNumber).Distinct().ToList();
2830
                    foreach (LineNumber lineNumber in lineNumbers)
2831
                    {
2832
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
2833
                        if (attribute != null)
2834
                        {
2835
                            string value = attribute.Value;
2836
                            if (!PBSList.Contains(value))
2837
                                PBSList.Add(value);
2838
                        }
2839
                    }
2840
                }
2841
            }
2842
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
2843
            {
2844
                string attrValue = Settings.Default.PBSSettingValue;
2845

    
2846
                foreach (Group group in Groups)
2847
                {
2848
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
2849
                    foreach (Item item in items)
2850
                    {
2851
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
2852
                        if (!PBSList.Contains(value))
2853
                            PBSList.Add(value);
2854
                    }
2855
                }
2856
            }
2857
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
2858
            {
2859
                string attrValue = Settings.Default.PBSSettingValue;
2860

    
2861
                foreach (Group group in Groups)
2862
                {
2863
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
2864
                    foreach (Document document in documents)
2865
                    {
2866
                        string name = document.DrawingName;
2867

    
2868
                        int startIndex = Settings.Default.PBSSettingStartValue;
2869
                        int endIndex = Settings.Default.PBSSettingEndValue;
2870

    
2871
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
2872
                        if (!PBSList.Contains(subStr))
2873
                            PBSList.Add(subStr);
2874
                    }
2875
                }
2876
            }
2877
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
2878
            {
2879
                foreach (Group group in Groups)
2880
                {
2881
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
2882
                    foreach (Document document in documents)
2883
                    {
2884
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
2885
                        foreach (TextInfo textInfo in textInfos)
2886
                        {
2887
                            if (!PBSList.Contains(textInfo.Value))
2888
                                PBSList.Add(textInfo.Value);
2889
                        }
2890
                    }
2891
                }
2892
            }
2893

    
2894
            foreach (var item in PBSList)
2895
            {
2896
                if (string.IsNullOrEmpty(result))
2897
                    result = item;
2898
                else
2899
                    result += ", " + item;
2900
            }
2901
            return result;
2902
        }
2903
    }
2904
}
클립보드 이미지 추가 (최대 크기: 500 MB)