프로젝트

일반

사용자정보

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

hytos / DTI_PID / ID2PSN / PSN.cs @ 08b33e44

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1345
                                    }
1346

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1479

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

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

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

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

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

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

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

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

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

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

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

    
1572
                                            }
1573

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

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

    
1593

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

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

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

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

    
1625
                                        if (PSNItem.StartType == PSNType.Equipment) //From은 Pump 제외
1626
                                        {
1627
                                          //  string itemName = From_item.Name;
1628
                                            Equipment Equipment = From_item.Equipment;
1629
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name && x.Type != "Pump(To)").FirstOrDefault();
1630
                                            if(nopocket != null)
1631
                                            {
1632
                                                Pocket = "Yes";
1633
                                            }
1634
                                        }
1635

    
1636
                                        if (PSNItem.EndType == PSNType.Equipment) //To는 전체
1637
                                        {
1638
                                           // string itemName = To_item.Name;
1639
                                            Equipment Equipment = To_item.Equipment;
1640
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name).FirstOrDefault();
1641
                                            if (nopocket != null)
1642
                                            {
1643
                                                Pocket = "Yes";
1644
                                            }
1645
                                        }
1646

    
1647
                                        newRow["Pocket"] = Pocket;
1648
                                        
1649
                                        pipeSystemNetworkDT.Rows.Add(newRow);
1650
                                    }
1651
                                }
1652

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

    
1674
                                return newRow;
1675
                            }
1676

    
1677
                        }
1678
                        catch (Exception ex)
1679
                        {
1680
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1681
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1682
                        }
1683

    
1684
                        //TopologySet 관련
1685
                        foreach (Topology topology in PSNItem.Topologies)
1686
                        {
1687
                            DataRow newRow = topologySetDT.NewRow();
1688
                            newRow["OID"] = topology.FullName;
1689
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
1690
                            if (bVentDrain)
1691
                                newRow["SubType"] = "Vent_Drain";
1692
                            else
1693
                                newRow["SubType"] = null;
1694
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
1695
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
1696
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
1697
                            newRow["TailItemSPID"] = topology.Items.First().UID;
1698
                            topologySetDT.Rows.Add(newRow);
1699
                        }
1700

    
1701
                    }
1702
                    catch (Exception ee)
1703
                    {
1704

    
1705
                    }
1706
                }
1707

    
1708

    
1709
                foreach (var item in startBranchDic)
1710
                {
1711
                    string uid = item.Key.UID;
1712
                    string topologyName = item.Value.Topology.FullName;
1713
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1714

    
1715
                    if (rows.Length == 1)
1716
                    {
1717
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1718
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1719
                    }
1720
                    else if (rows.Length > 1)
1721
                    {
1722
                        DataRow targetRow = null;
1723
                        int index = int.MaxValue;
1724
                        foreach (DataRow row in rows)
1725
                        {
1726
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1727
                            if (split.StartsWith("L"))
1728
                            {
1729
                                int num = Convert.ToInt32(split.Remove(0, 1));
1730
                                if (index > num)
1731
                                {
1732
                                    index = num;
1733
                                    targetRow = row;
1734
                                }
1735
                            }
1736
                        }
1737

    
1738
                        if (targetRow != null)
1739
                        {
1740
                            targetRow["BranchTopologySet_OID"] = topologyName;
1741
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1742
                        }
1743
                    }
1744
                }
1745

    
1746
                foreach (var item in endBranchDic)
1747
                {
1748
                    string uid = item.Key.UID;
1749
                    string topologyName = item.Value.Topology.FullName;
1750
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
1751
                    if (rows.Length == 1)
1752
                    {
1753
                        rows.First()["BranchTopologySet_OID"] = topologyName;
1754
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1755
                    }
1756
                    else if (rows.Length > 1)
1757
                    {
1758
                        DataRow targetRow = null;
1759
                        int index = int.MinValue;
1760
                        foreach (DataRow row in rows)
1761
                        {
1762
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
1763
                            if (split.StartsWith("L"))
1764
                            {
1765
                                int num = Convert.ToInt32(split.Remove(0, 1));
1766
                                if (index < num)
1767
                                {
1768
                                    index = num;
1769
                                    targetRow = row;
1770
                                }
1771
                            }
1772
                        }
1773

    
1774
                        if (targetRow != null)
1775
                        {
1776
                            targetRow["BranchTopologySet_OID"] = topologyName;
1777
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
1778
                        }
1779
                    }
1780
                }
1781

    
1782
                PathItems = pathItemsDT;
1783
                SequenceData = sequenceDataDT;
1784
                PipeSystemNetwork = pipeSystemNetworkDT;
1785
                TopologySet = topologySetDT;
1786
                PipeLine = pipelineDT;
1787
                PipeSystem = pipesystemDT;
1788
            }
1789
            catch (Exception ex)
1790
            {
1791
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1792
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1793
            }
1794
        }
1795

    
1796
        private double AccuracyCalculation(List<double> lstAcc, double acc)
1797
        {
1798
            foreach (double lacc in lstAcc)
1799
            {
1800
                acc *= lacc;
1801
            }
1802
            return acc;
1803
        }
1804

    
1805
        private void UpdateSubType()
1806
        {
1807
            try
1808
            {
1809
                foreach (PSNItem PSNItem in PSNItems)
1810
                {
1811
                    if (PSNItem.IsBypass)
1812
                    {
1813
                        foreach (Topology topology in PSNItem.Topologies)
1814
                        {
1815
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1816
                            if (rows.Length.Equals(1))
1817
                                rows.First()["SubType"] = "Bypass";
1818
                        }
1819
                    }
1820

    
1821
                    if (PSNItem.StartType == PSNType.Header)
1822
                    {
1823
                        Topology topology = PSNItem.Topologies.First();
1824
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1825
                        if (rows.Length.Equals(1))
1826
                            rows.First()["SubType"] = "Header";
1827
                    }
1828
                    else if (PSNItem.EndType == PSNType.Header)
1829
                    {
1830
                        Topology topology = PSNItem.Topologies.Last();
1831
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1832
                        if (rows.Length.Equals(1))
1833
                            rows.First()["SubType"] = "Header";
1834
                    }
1835
                }
1836

    
1837

    
1838
                foreach (Topology topology in Topologies)
1839
                {
1840
                    try
1841
                    {
1842
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
1843

    
1844
                        if (rows.Count() > 0)
1845
                        {
1846
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
1847
                            {
1848
                                if (topology.Items == null)
1849
                                    continue;
1850

    
1851
                                Item firstItem = topology.Items.First();
1852
                                Item lastItem = topology.Items.Last();
1853

    
1854
                                List<Relation> relations = new List<Relation>();
1855

    
1856
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1857
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1858

    
1859
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
1860
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
1861

    
1862
                                if (relations.Count > 0)
1863
                                    rows.First()["SubType"] = "OtherSystem";
1864
                            }
1865
                        }
1866
                    }
1867
                    catch (Exception ex)
1868
                    {
1869

    
1870
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1871
                    }
1872
                }
1873

    
1874
                foreach (DataRow row in TopologySet.Rows)
1875
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
1876
                        row["SubType"] = "Normal";
1877
            }
1878
            catch (Exception ex)
1879
            {
1880
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1881
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1882
            }
1883
        }
1884

    
1885
        private bool IsBypass(PSNItem PSNItem)
1886
        {
1887
            bool bResult = false;
1888

    
1889
            if (PSNItem.GetPSNType() == "B2B")
1890
            {
1891
                Group firstGroup = PSNItem.Groups.First();
1892
                Group lastGroup = PSNItem.Groups.Last();
1893
                Item firstItem = firstGroup.Items.First();
1894
                Item lastItem = lastGroup.Items.Last();
1895

    
1896
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
1897
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
1898

    
1899
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
1900
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
1901
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
1902
                    bResult = true;
1903
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
1904
                    bResult = true;
1905
            }
1906

    
1907
            Item GetConnectedItemByPSN(Item item)
1908
            {
1909
                Item result = null;
1910

    
1911
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
1912
                if (relation != null)
1913
                    result = relation.Item;
1914

    
1915

    
1916
                return result;
1917
            }
1918

    
1919
            return bResult;
1920
        }
1921

    
1922
        private void DeleteVentDrain()
1923
        {
1924
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
1925

    
1926
            foreach (DataRow dataRow in ventdrainRows)
1927
            {
1928
                dataRow.Delete();
1929
            }
1930
        }
1931

    
1932
        private void UpdateAccuracy()
1933
        {
1934
            //DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
1935
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'");
1936
            List<double> lstAcc = null;
1937
            string Status = string.Empty;
1938

    
1939
            foreach (DataRow dataRow in statusRows)
1940
            {
1941
                lstAcc = new List<double>();
1942
                Status = dataRow.Field<string>("Status");
1943
                if (!string.IsNullOrEmpty(Status))
1944
                {
1945
                    string[] arrStatus = Status.Split(',');
1946
                    foreach (string arrstr in arrStatus)
1947
                    {
1948
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
1949
                            lstAcc.Add(0.75);
1950

    
1951
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
1952
                            lstAcc.Add(0.7);
1953

    
1954
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
1955
                            lstAcc.Add(0.5);
1956

    
1957
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
1958
                            lstAcc.Add(0.65);
1959

    
1960
                        if (arrstr.Contains(Rule5)) //Line Disconnected
1961
                            lstAcc.Add(0.6);
1962
                    }
1963
                }
1964

    
1965
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
1966
                if (PSNAccuracy == "100")
1967
                    PSNAccuracy = "1";
1968

    
1969
                PSNAccuracy = Convert.ToString(Convert.ToDecimal(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))));
1970
                //if (PSNAccuracy != "100")
1971
                //{
1972
                //    //dataRow["IncludingVirtualData"] = "No";
1973
                dataRow["PSNAccuracy"] = PSNAccuracy;
1974
                //}
1975
            }
1976
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
1977
            foreach (DataRow dr in dt.Rows)
1978
            {
1979
                string oid = dr.Field<string>("OID");
1980
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
1981
                double totalDdr = 0;
1982
                foreach (DataRow ddr in select)
1983
                {
1984
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
1985
                    if (acc == 100) acc = 1;
1986
                    if (totalDdr == 0) totalDdr = acc;
1987
                    else totalDdr *= acc;
1988
                }
1989

    
1990
                totalDdr *= 100;
1991

    
1992
                if (totalDdr != 100)
1993
                {
1994
                    foreach (DataRow ddr in select)
1995
                    {
1996
                        ddr["IncludingVirtualData"] = "Yes";
1997
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
1998
                    }
1999
                }
2000
                else
2001
                {
2002
                    foreach (DataRow ddr in select)
2003
                    {
2004
                        ddr["IncludingVirtualData"] = "No";
2005
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2006
                    }
2007
                }
2008
            }
2009

    
2010
        }
2011

    
2012
        private void UpdateKeywordForPSN()
2013
        {
2014
            #region Keyword Info
2015
            KeywordInfo KeywordInfos = new KeywordInfo();
2016
            DataTable dtKeyword = DB.SelectKeywordsSetting();
2017
            foreach (DataRow row in dtKeyword.Rows)
2018
            {
2019
                int index = Convert.ToInt32(row["INDEX"]);
2020
                string name = row["NAME"].ToString();
2021
                string keyword = row["KEYWORD"].ToString();
2022

    
2023
                //KeywordInfo keywordInfo = new KeywordInfo();   
2024
                KeywordInfos.KeywordItems.Add(new KeywordItem()
2025
                {
2026
                    Index = index,
2027
                    Name = name,
2028
                    Keyword = keyword
2029
                });
2030
            }
2031
            #endregion
2032

    
2033
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
2034
            foreach (DataRow dataRow in endofHeaderRows)
2035
            {
2036
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2037

    
2038
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
2039
                {
2040
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2041
                    DataRow dr = pathItemRows.First();
2042
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
2043
                    dr["TYPE"] = "End";
2044
                    dr["ITEMTAG"] = "ENDOFHEADER";
2045
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2046
                }
2047

    
2048
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
2049
                {
2050
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2051
                    DataRow dr = pathItemRows.Last();
2052
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
2053
                    dr["TYPE"] = "End";
2054
                    dr["ITEMTAG"] = "ENDOFHEADER";
2055
                    dr["DESCRIPTION"] = "ENDOFHEADER";
2056
                }
2057
            }
2058

    
2059
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2060
            {
2061
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
2062
                foreach (DataRow dataRow in keywordRows)
2063
                {
2064
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2065

    
2066
                    if (dataRow.Field<string>("From_Data") == keyitem.Keyword)
2067
                    {
2068
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2069

    
2070
                        //
2071
                        //if(.)
2072
                        if (PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
2073
                        {
2074
                            DataRow dr = pathItemRows.First();
2075
                            //dr["CLASS"] = ""; //Type
2076
                            dr["TYPE"] = "End";
2077
                            dr["ITEMTAG"] = keyitem.Keyword;
2078
                            dr["DESCRIPTION"] = keyitem.Keyword;
2079
                        }
2080

    
2081
                    }
2082

    
2083
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
2084
                    {
2085
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2086

    
2087
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
2088
                        {
2089
                            DataRow dr = pathItemRows.Last();
2090
                            //dr["CLASS"] = ""; //Type
2091
                            dr["TYPE"] = "End";
2092
                            dr["ITEMTAG"] = keyitem.Keyword;
2093
                            dr["DESCRIPTION"] = keyitem.Keyword;
2094
                            //dr.Field<string>("Type")
2095
                        }
2096

    
2097
                    }
2098
                }
2099
            }
2100
        }
2101

    
2102
        private void UpdateErrorForPSN()
2103
        {
2104
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
2105
            foreach (DataRow dataRow in errorRows)
2106
            {
2107
                try
2108
                {
2109
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2110
                    bool change = false;
2111
                    bool bCheck = false;
2112
                    int bCount = 0;
2113
                    if (!PSNItem.EnableType(PSNItem.StartType))
2114
                    {
2115
                        change = true;
2116
                        bCheck = change;
2117
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2118
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
2119

    
2120
                        Item item = PSNItem.Groups.First().Items.First();
2121
                        try
2122
                        {
2123
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2124

    
2125
                            tieInPointIndex++;
2126

    
2127

    
2128
                            if (item.ItemType == ItemType.Line)
2129
                            {
2130
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2131
                                bCount = 2;
2132

    
2133
                                foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2134
                                {
2135
                                    loopRow["FROM_DATA"] = FROM_DATA;
2136
                                    if (loopRow.Field<string>("OrderNumber") == "0")
2137
                                    {
2138
                                        string status = loopRow.Field<string>("Status");
2139
                                        //string isvali
2140
                                        if (string.IsNullOrEmpty(status))
2141
                                            status = "Line Disconnected";
2142
                                        else if (!status.Contains("Line Disconnected"))
2143
                                            status += ", Line Disconnected";
2144
                                        loopRow["Status"] = status;
2145
                                        if (!string.IsNullOrEmpty(status))
2146
                                            loopRow["IsValid"] = "Error";
2147
                                    }
2148
                                }
2149
                            }
2150
                            else
2151
                            {
2152
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
2153

    
2154
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
2155
                                bCount = 3;
2156
                            }
2157

    
2158
                            PSNItem.StartType = PSNType.Equipment;
2159
                        }
2160
                        catch (Exception ex)
2161
                        {
2162
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2163
                            return;
2164
                        }
2165
                    }
2166

    
2167
                    if (!PSNItem.EnableType(PSNItem.EndType))
2168
                    {
2169
                        change = true;
2170
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
2171
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
2172

    
2173
                        Item item = PSNItem.Groups.Last().Items.Last();
2174
                        try
2175
                        {
2176
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
2177

    
2178
                            if (item.ItemType == ItemType.Line)
2179
                            {
2180
                                foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
2181
                                {
2182
                                    loopRow["TO_DATA"] = TO_DATA;
2183
                                    if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
2184
                                    {
2185
                                        string status = loopRow.Field<string>("Status");
2186
                                        if (string.IsNullOrEmpty(status))
2187
                                            status = "Line Disconnected";
2188
                                        else if (!status.Contains("Line Disconnected"))
2189
                                            status += ", Line Disconnected";
2190
                                        loopRow["Status"] = status;
2191
                                        if (!string.IsNullOrEmpty(status))
2192
                                            loopRow["IsValid"] = "Error";
2193
                                    }
2194
                                }
2195
                            }
2196

    
2197
                            tieInPointIndex++;
2198

    
2199
                            if (!bCheck)
2200
                            {
2201
                                if (item.ItemType == ItemType.Line)
2202
                                {
2203
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
2204
                                }
2205
                                else
2206
                                {
2207
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex + 1);
2208
                                    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);
2209
                                }
2210
                            }
2211
                            else
2212
                            {
2213
                                if (item.ItemType == ItemType.Line)
2214
                                {
2215
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows[pathItemRows.Count() - bCount], TO_DATA), insertIndex + 1);
2216
                                }
2217
                                else
2218
                                {
2219
                                    PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows[pathItemRows.Count() - bCount], TO_DATA), insertIndex + 1);
2220
                                    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);
2221
                                }
2222
                            }
2223

    
2224

    
2225
                            PSNItem.EndType = PSNType.Equipment;
2226
                        }
2227
                        catch (Exception ex)
2228
                        {
2229
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2230
                            return;
2231
                        }
2232
                    }
2233

    
2234
                    dataRow["Type"] = PSNItem.GetPSNType();
2235
                    if (change)
2236
                    {
2237
                        int rowIndex = 0;
2238
                        for (int i = 0; i < PathItems.Rows.Count; i++)
2239
                        {
2240
                            DataRow row = PathItems.Rows[i];
2241
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
2242
                                continue;
2243
                            string sequenceData = row["SequenceData_OID"].ToString();
2244
                            string[] split = sequenceData.Split(new char[] { '_' });
2245

    
2246
                            StringBuilder sb = new StringBuilder();
2247
                            for (int j = 0; j < split.Length - 1; j++)
2248
                                sb.Append(split[j] + "_");
2249
                            sb.Append(rowIndex++);
2250
                            row["SequenceData_OID"] = sb.ToString();
2251

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

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

    
2257
                            if (seqItemRows == null)
2258
                            {
2259
                                DataRow newRow = SequenceData.NewRow();
2260
                                newRow["OID"] = sb.ToString();
2261
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2262
                                newRow["PathItem_OID"] = row["OID"];
2263
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
2264
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
2265
                            }
2266
                            else
2267
                            {
2268
                                seqItemRows["OID"] = sb.ToString();
2269
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2270
                                seqItemRows["PathItem_OID"] = row["OID"];
2271
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
2272
                            }
2273
                        }
2274
                    }
2275

    
2276
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
2277
                    {
2278
                        DataRow newRow = PathItems.NewRow();
2279
                        newRow["OID"] = Guid.NewGuid().ToString();
2280
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2281
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2282
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2283
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2284
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
2285
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
2286
                        newRow["DESCRIPTION"] = DATA;
2287
                        newRow["Class"] = "End of line terminator";
2288
                        newRow["SubClass"] = "End of line terminator";
2289
                        newRow["TYPE"] = "End";
2290
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2291
                        newRow["NPD"] = itemRow["NPD"];
2292
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2293
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2294
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2295

    
2296
                        return newRow;
2297
                    }
2298

    
2299
                    DataRow createLineRow(DataRow itemRow)
2300
                    {
2301
                        DataRow newRow = PathItems.NewRow();
2302
                        newRow["OID"] = Guid.NewGuid().ToString();
2303
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2304
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2305
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2306
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2307
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
2308
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
2309
                        newRow["Class"] = itemRow["Class"];
2310
                        newRow["SubClass"] = itemRow["SubClass"];
2311
                        newRow["TYPE"] = itemRow["TYPE"];
2312
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2313
                        newRow["NPD"] = itemRow["NPD"];
2314
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2315
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2316
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2317

    
2318
                        return newRow;
2319
                    }
2320
                }
2321
                catch (Exception ex)
2322
                {
2323

    
2324
                }
2325
            }
2326
        }
2327

    
2328
        private void InsertTeePSN()
2329
        {
2330
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
2331
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
2332
            bool change = false;
2333
            foreach (DataRow dataRow in branchRows)
2334
            {
2335
                try
2336
                {
2337
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
2338
                    change = false;
2339

    
2340
                    if (PSNItem.StartType == PSNType.Branch)
2341
                    {
2342
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2343
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
2344
                        Item Teeitem = PSNItem.Groups.First().Items.First();
2345
                        try
2346
                        {
2347
                            if (Teeitem.ItemType == ItemType.Line)
2348
                            {
2349
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
2350
                                {
2351
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
2352
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
2353
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
2354
                                    change = true;
2355
                                }
2356

    
2357
                            }
2358
                        }
2359
                        catch (Exception ex)
2360
                        {
2361
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2362
                            return;
2363
                        }
2364
                    }
2365

    
2366
                    if (PSNItem.EndType == PSNType.Branch)
2367
                    {
2368
                        //change = true;
2369
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2370

    
2371
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
2372

    
2373
                        DataRow dr = pathItemRows.Last();
2374
                        if (change)
2375
                            dr = pathItemRows[pathItemRows.Count() - 2];
2376

    
2377
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
2378

    
2379
                        try
2380
                        {
2381
                            if (Teeitem.ItemType == ItemType.Line)
2382
                            {
2383
                                if (dr.Field<string>("SubClass") != "Tee")
2384
                                {
2385
                                    PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
2386
                                    change = true;
2387
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
2388
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
2389
                                }
2390

    
2391
                            }
2392
                        }
2393
                        catch (Exception ex)
2394
                        {
2395
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
2396
                            return;
2397
                        }
2398
                    }
2399

    
2400
                    if (change)
2401
                    {
2402
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
2403
                        int rowIndex = 0;
2404
                        for (int i = 0; i < PathItems.Rows.Count; i++)
2405
                        {
2406
                            DataRow row = PathItems.Rows[i];
2407
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
2408
                                continue;
2409
                            string sequenceData = row["SequenceData_OID"].ToString();
2410
                            string[] split = sequenceData.Split(new char[] { '_' });
2411

    
2412
                            StringBuilder sb = new StringBuilder();
2413
                            for (int j = 0; j < split.Length - 1; j++)
2414
                                sb.Append(split[j] + "_");
2415
                            sb.Append(rowIndex++);
2416
                            row["SequenceData_OID"] = sb.ToString();
2417

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

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

    
2423
                            if (seqItemRows == null)
2424
                            {
2425
                                DataRow newRow = SequenceData.NewRow();
2426
                                newRow["OID"] = sb.ToString();
2427
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2428
                                newRow["PathItem_OID"] = row["OID"];
2429
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
2430
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
2431
                            }
2432
                            else
2433
                            {
2434
                                seqItemRows["OID"] = sb.ToString();
2435
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
2436
                                seqItemRows["PathItem_OID"] = row["OID"];
2437
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
2438
                            }
2439
                        }
2440
                    }
2441

    
2442
                    DataRow createTeeRow(DataRow itemRow)
2443
                    {
2444
                        DataRow newRow = PathItems.NewRow();
2445
                        newRow["OID"] = Guid.NewGuid().ToString();
2446
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
2447
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
2448
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
2449
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
2450
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
2451
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
2452
                        newRow["DESCRIPTION"] = "";
2453
                        newRow["Class"] = "Branch";
2454
                        newRow["SubClass"] = "Tee";
2455
                        newRow["TYPE"] = itemRow["TYPE"];
2456
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
2457
                        newRow["NPD"] = itemRow["NPD"];
2458
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
2459
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
2460
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
2461

    
2462
                        return newRow;
2463
                    }
2464
                }
2465
                catch (Exception ex)
2466
                {
2467

    
2468
                }
2469
            }
2470
        }
2471
    }
2472

    
2473
    public class PSNItem
2474
    {
2475
        public PSNItem(int count, int Revision)
2476
        {
2477
            Groups = new List<Group>();
2478
            Topologies = new List<Topology>();
2479

    
2480
            Index = count + 1;
2481
            this.Revision = Revision;
2482
        }
2483

    
2484
        private int Revision;
2485
        public string UID { get; set; }
2486
        public List<Group> Groups { get; set; }
2487
        public List<Topology> Topologies { get; set; }
2488
        public PSNType StartType { get; set; }
2489
        public PSNType EndType { get; set; }
2490
        public int Index { get; set; }
2491
        public string IsValid { get; set; }
2492
        public bool IsKeyword { get; set; }
2493
        public string Status { get; set; }
2494
        public string IncludingVirtualData { get; set; }
2495
        public string PSNAccuracy { get; set; }
2496
        public KeywordInfo KeywordInfos = new KeywordInfo();
2497
        public DataTable Nozzle = new DataTable();
2498

    
2499
        public string PSN_OID()
2500
        {
2501
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
2502
        }
2503

    
2504
        public string GetPSNType()
2505
        {
2506
            string result = string.Empty;
2507

    
2508
            if (EnableType(StartType) && EnableType(EndType))
2509
            {
2510
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
2511
                    result = "E2E";
2512
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
2513
                    result = "B2B";
2514
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
2515
                    result = "HD2";
2516

    
2517
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
2518
                    result = "E2B";
2519
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
2520
                    result = "B2E";
2521

    
2522
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
2523
                    result = "HDB";
2524
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
2525
                    result = "HDB";
2526

    
2527
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
2528
                    result = "HDE";
2529
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
2530
                    result = "HDE";
2531
                else
2532
                    result = "Error";
2533
            }
2534
            else
2535
                result = "Error";
2536

    
2537
            return result;
2538

    
2539

    
2540
        }
2541

    
2542
        public bool EnableType(PSNType type)
2543
        {
2544
            bool result = false;
2545

    
2546
            if (type == PSNType.Branch ||
2547
                type == PSNType.Equipment ||
2548
                type == PSNType.Header)
2549
            {
2550
                result = true;
2551
            }
2552

    
2553
            return result;
2554
        }
2555

    
2556
        public bool IsBypass { get; set; }
2557

    
2558
        public string GetFromData(ref string Type, ref Item item)
2559
        {
2560
            Status = string.Empty;
2561
            string result = string.Empty;
2562
            if (IsKeyword)
2563
                IsKeyword = false;
2564
            try
2565
            {
2566
                item = Groups.First().Items.First();
2567

    
2568
                if (StartType == PSNType.Header)
2569
                    result = "ENDOFHEADER";
2570
                else if (StartType == PSNType.Branch)
2571
                {
2572
                    //if (!item.MissingLineNumber && item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
2573
                    if (!item.MissingLineNumber2)
2574
                        result = item.Relations.First().Item.LineNumber.Name;
2575
                    else
2576
                    {
2577
                        IsValid = "Error";
2578
                        Status += ", Missing LineNumber_2";
2579
                        result = "Empty LineNumber";
2580
                    }
2581

    
2582
                    //if (item.MissingLineNumber1)
2583
                    //{
2584
                    //    Status += ", Missing LineNumber_1";
2585
                    //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2586

    
2587
                    //}
2588
                }
2589
                else if (StartType == PSNType.Equipment)
2590
                {
2591
                    if (Groups.First().Items.First().Equipment != null)
2592
                        result = Groups.First().Items.First().Equipment.ItemTag;
2593
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
2594

    
2595
                    if (drNozzle != null)
2596
                        result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
2597
                }
2598
                else
2599
                {
2600
                    IsValid = "Error";
2601
                    item = Groups.First().Items.First();
2602
                    if (item.ItemType == ItemType.Symbol)
2603
                    {
2604

    
2605
                        string keyword = string.Empty;
2606
                        keyword = GetFromKeywordData(ref Type, item);
2607

    
2608
                        if (string.IsNullOrEmpty(keyword))
2609
                        {
2610
                            if (item.ID2DBType.Contains("OPC's"))
2611
                                Status += ", OPC Disconnected";
2612
                            else
2613
                                Status += ", Missing ItemTag or Description";
2614

    
2615
                            result = item.ID2DBName;
2616
                        }
2617
                        else
2618
                        {
2619
                            result = keyword;
2620
                            IsKeyword = true;
2621
                            IsValid = string.Empty;
2622
                        }
2623

    
2624
                    }
2625
                    else if (item.ItemType == ItemType.Line)
2626
                    {
2627

    
2628
                        if (item.MissingLineNumber1)
2629
                        {
2630
                            IsValid = "Error";
2631
                            Status += ", Missing LineNumber_1";
2632
                            result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2633
                        }
2634
                    }
2635
                    else
2636
                        result = "Unknown";
2637

    
2638
                }
2639
            }
2640
            catch (Exception ex)
2641
            {
2642

    
2643
            }
2644

    
2645
            return result;
2646
        }
2647

    
2648
        public string GetFromKeywordData(ref string Type, Item item)
2649
        {
2650
            string result = string.Empty;
2651

    
2652
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2653
            {
2654
                if (keyitem.Name.Equals(item.Name))
2655
                {
2656
                    result = keyitem.Keyword;
2657
                    Type = item.ID2DBType;
2658
                    break;
2659
                }
2660
            }
2661

    
2662
            return result;
2663
        }
2664

    
2665
        public string GetToKeywordData(ref string Type, Item item)
2666
        {
2667
            string result = string.Empty;
2668

    
2669
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
2670
            {
2671
                if (keyitem.Name.Equals(item.Name))
2672
                {
2673
                    result = keyitem.Keyword;
2674
                    Type = item.ID2DBType;
2675
                    break;
2676
                }
2677
            }
2678
            return result;
2679
        }
2680

    
2681
        public string GetToData(ref string ToType, ref Item item)
2682
        {
2683
            string result = string.Empty;
2684
            Status = string.Empty;
2685

    
2686
            if (IsKeyword)
2687
                IsKeyword = false;
2688

    
2689
            item = Groups.Last().Items.Last();
2690

    
2691
            if (EndType == PSNType.Header)
2692
                result = "ENDOFHEADER";
2693
            else if (EndType == PSNType.Branch)
2694
            {
2695

    
2696
                
2697
                //if (!item.MissingLineNumber && item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
2698
                if (!item.MissingLineNumber2)
2699
                    result = item.Relations.Last().Item.LineNumber.Name;
2700
                else
2701
                {
2702
                    IsValid = "Error";
2703
                    Status += ", Missing LineNumber_2";
2704
                    result = "Empty LineNumber";
2705
                }
2706

    
2707
                //if (item.MissingLineNumber1)
2708
                //{
2709
                //    Status += ", Missing LineNumber_1";
2710
                //    result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2711

    
2712
                //}
2713
            }
2714
            else if (EndType == PSNType.Equipment)
2715
            {
2716
                if (Groups.Last().Items.Last().Equipment != null)
2717
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
2718

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

    
2721
                if (drNozzle != null)
2722
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
2723
            }
2724
            else
2725
            {
2726
                IsValid = "Error";
2727
                item = Groups.Last().Items.Last();
2728
                if (item.ItemType == ItemType.Symbol)
2729
                {
2730
                    string keyword = string.Empty;
2731
                    keyword = GetToKeywordData(ref ToType, item);
2732

    
2733
                    if (string.IsNullOrEmpty(keyword))
2734
                    {
2735
                        if (item.ID2DBType.Contains("OPC's"))
2736
                            Status += ", OPC Disconnected";
2737
                        else
2738
                            Status += ", Missing ItemTag or Description";
2739

    
2740
                        result = item.ID2DBName;
2741
                    }
2742
                    else
2743
                    {
2744
                        result = keyword;
2745
                        IsValid = string.Empty;
2746
                        IsKeyword = true;
2747
                    }
2748

    
2749
                }
2750
                else if (item.ItemType == ItemType.Line)
2751
                {
2752
                    if (item.MissingLineNumber1)
2753
                    {
2754
                        IsValid = "Error";
2755
                        Status += ", Missing LineNumber_1";
2756
                        result = item.MissingLineNumber1 && item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name) ? item.LineNumber.Name : "Empty LineNumber";
2757
                    }
2758
                }
2759
                else
2760
                    result = "Unknown";
2761

    
2762

    
2763
            }
2764

    
2765

    
2766

    
2767
            return result;
2768
        }
2769

    
2770
        public string GetPBSData()
2771
        {
2772
            string result = string.Empty;
2773
            List<string> PBSList = new List<string>();
2774
            if (Settings.Default.PBSSetting.Equals("Line Number"))
2775
            {
2776
                string attrValue = Settings.Default.PBSSettingValue;
2777

    
2778
                foreach (Group group in Groups)
2779
                {
2780
                    List<LineNumber> lineNumbers = group.Items.Select(x => x.LineNumber).Distinct().ToList();
2781
                    foreach (LineNumber lineNumber in lineNumbers)
2782
                    {
2783
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
2784
                        if (attribute != null)
2785
                        {
2786
                            string value = attribute.Value;
2787
                            if (!PBSList.Contains(value))
2788
                                PBSList.Add(value);
2789
                        }
2790
                    }
2791
                }
2792
            }
2793
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
2794
            {
2795
                string attrValue = Settings.Default.PBSSettingValue;
2796

    
2797
                foreach (Group group in Groups)
2798
                {
2799
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
2800
                    foreach (Item item in items)
2801
                    {
2802
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
2803
                        if (!PBSList.Contains(value))
2804
                            PBSList.Add(value);
2805
                    }
2806
                }
2807
            }
2808
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
2809
            {
2810
                string attrValue = Settings.Default.PBSSettingValue;
2811

    
2812
                foreach (Group group in Groups)
2813
                {
2814
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
2815
                    foreach (Document document in documents)
2816
                    {
2817
                        string name = document.DrawingName;
2818

    
2819
                        int startIndex = Settings.Default.PBSSettingStartValue;
2820
                        int endIndex = Settings.Default.PBSSettingEndValue;
2821

    
2822
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
2823
                        if (!PBSList.Contains(subStr))
2824
                            PBSList.Add(subStr);
2825
                    }
2826
                }
2827
            }
2828
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
2829
            {
2830
                foreach (Group group in Groups)
2831
                {
2832
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
2833
                    foreach (Document document in documents)
2834
                    {
2835
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
2836
                        foreach (TextInfo textInfo in textInfos)
2837
                        {
2838
                            if (!PBSList.Contains(textInfo.Value))
2839
                                PBSList.Add(textInfo.Value);
2840
                        }
2841
                    }
2842
                }
2843
            }
2844

    
2845
            foreach (var item in PBSList)
2846
            {
2847
                if (string.IsNullOrEmpty(result))
2848
                    result = item;
2849
                else
2850
                    result += ", " + item;
2851
            }
2852
            return result;
2853
        }
2854
    }
2855
}
클립보드 이미지 추가 (최대 크기: 500 MB)