프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / ID2PSN / PSN.cs @ a89e25a0

이력 | 보기 | 이력해설 | 다운로드 (189 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
using DevExpress.XtraSplashScreen;
12

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

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

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

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

    
54
        int tieInPointIndex = 1;
55

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

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

    
64
        ID2Info id2Info = ID2Info.GetInstance();
65

    
66

    
67

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

    
71
        public PSN()
72
        {
73

    
74
        }
75

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

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

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

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

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

    
208
        public void SetPSNData(SplashScreenManager splashScreenManager1)
209
        {
210
            // Item들의 속성으로 Topology Data를 생성한다.
211
            // Topology Data는 Topology Rule Setting을 기준으로 생성한다.
212
            int i = 1;
213
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetTopologyData ( 3 % )");
214
            SetTopologyData();
215
            // ID2의 OPC연결 Data 기반으로 Group(도면단위 PSN)을 연결한다.
216
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  ConnectByOPC ( 5 % )");
217
            ConnectByOPC();
218
            // 실제 PSN 생성 로직
219
            // 연결된 Group을 하나의 PSN으로 만든다.
220
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetPSNItem ( 10 % )");
221
            SetPSNItem();
222
            // 생성된 PSN의 Type을 설정한다.
223
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetPSNType ( 15 % )");
224
            SetPSNType();
225
            // ID2에는 Branch 정보가 없어서 Branch 정보를 생성한다.
226
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetBranchInfo ( 20 % )");
227
            SetBranchInfo();
228
            // 생성된 Topology Data들을 정리하며 Main, Branch를 판단한다.
229
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetTopology ( 25 % )");
230
            SetTopology();
231
            // PSN이 Bypass인지 검사 
232
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetPSNBypass ( 30 % )");
233
            SetPSNBypass();
234
            // Topology들에게 Index를 부여한다
235
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetTopologyIndex ( 35 % )");
236
            SetTopologyIndex();
237
            // Nozzle, Equipment의 정보를 저장
238
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SaveNozzleAndEquipment ( 40 % )");
239
            SaveNozzleAndEquipment();
240
            // PSN의 정보를 저장
241
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  SetPSNData ( 45 % )");
242
            SavePSNData();
243
            // Update Keyword
244
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateKeywordForPSN ( 55 % )");
245
            UpdateKeywordForPSN();
246
          
247
            // Topology의 subtype을 update(bypass, Header, 등등) 
248
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateSubType ( 60 % )");
249
            UpdateSubType();
250

    
251
            // Vent/Drain PSN 데이터 제거
252
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  DeleteVentDrain ( 65 % )");
253
            DeleteVentDrain();
254

    
255
            // Update Error
256
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateErrorForPSN ( 70 % )");
257
            PathItemSorting();
258
            UpdateErrorForPSN();
259
            // Insert Tee
260
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  InsertTeePSN ( 75 % )");
261
            InsertTeePSN();
262

    
263
            // ValveGrouping
264
            PathItemSorting(); //test
265
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateValveGrouping ( 80 % )");
266
            UpdateValveGrouping();
267

    
268
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  PathItemSorting ( 85 % )");
269
            PathItemSorting();
270

    
271
            // AirFinCooler 
272
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateAirFinCooler ( 90 % )");
273
            UpdateAirFinCooler();
274

    
275
            // 확도 계산
276
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateAccuracy ( 95 % )");
277
            UpdateAccuracy();
278

    
279
            //UpdatePSNType();
280

    
281
        }
282

    
283
        private void UpdatePSNType()
284
        {
285
            try
286
            {
287
                foreach (PSNItem PSNItem in PSNItems)
288
                {    
289
                    foreach (Group group in PSNItem.Groups)
290
                    {
291
                        foreach (Item item in group.Items)
292
                        {
293
                            DataRow[] pipeSystems = PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID()));
294
                           // PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
295

    
296
                            foreach(DataRow dr in pipeSystems)
297
                            {
298
                                dr["Type"] = PSNItem.GetPSNType();
299
                            }                            
300
                        }
301
                    }                
302
                }
303
            }
304
            catch (Exception ex)
305
            {
306
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
307
            }
308
        }
309

    
310
        private void PathItemSorting()
311
        {
312
            try
313
            {
314
                DataTable dtPathItems = PathItems.Clone();
315
                DataTable dtPipeSystemNetwork = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
316

    
317
                foreach (DataRow drpipe in dtPipeSystemNetwork.Rows)
318
                {
319
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drpipe["OID"].ToString()));
320
                    DataTable dtSequenceItems = SequenceData.Clone();
321
                    foreach (DataRow drpath in pathItemRows)
322
                    {
323
                        DataRow sequenceRows = SequenceData.Select(string.Format("PathItem_OID = '{0}'", drpath.Field<string>("OID"))).First();
324

    
325
                        DataRow newRow = dtSequenceItems.NewRow();
326
                        foreach (DataColumn column in SequenceData.Columns)
327
                            if (dtSequenceItems.Columns[column.ColumnName] != null)
328
                                newRow[column.ColumnName] = sequenceRows[column.ColumnName];
329

    
330
                        dtSequenceItems.Rows.Add(newRow);
331
                    }
332

    
333
                    foreach (DataRow sqrow in dtSequenceItems.Select().OrderBy(x => Convert.ToInt32(x.Field<string>("SERIALNUMBER"))))
334
                    {
335
                        DataRow newRow = dtPathItems.NewRow();
336
                        DataRow row = PathItems.Select(string.Format("OID = '{0}'", sqrow["PathItem_OID"])).First();
337

    
338
                        foreach (DataColumn column in PathItems.Columns)
339
                            if (dtPathItems.Columns[column.ColumnName] != null)
340
                                newRow[column.ColumnName] = row[column.ColumnName];
341

    
342
                        dtPathItems.Rows.Add(newRow);
343
                    }
344
                }
345

    
346
                PathItems.Clear();
347
                PathItems = dtPathItems.Copy();
348
            }
349
            catch (Exception ex)
350
            {
351
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
352
            }
353
        }
354
        
355
        private void UpdateAirFinCooler()
356
        {
357
            try
358
            {
359
                
360
                int pumpTagNum = 0;
361
                #region EquipmentAirFinCooler Info
362
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
363
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
364
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
365
                {
366
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
367
                    {
368
                        Type = row["Type"].ToString(),
369
                        TagIdentifier = row["TagIdentifier"].ToString(),
370
                        AttributeName = row["AttributeName"].ToString(),
371
                        Name = row["Name"].ToString()
372
                    });
373
                }
374
                #endregion
375

    
376
                
377
                DataRow[] pumpRows = PipeSystemNetwork.Select("PUMP = 'PUMP'");
378
                Dictionary<string, string> eqkeyValuePairs = new Dictionary<string, string>();
379
                // 1, 2번
380
                foreach (DataRow dataRow in pumpRows) 
381
                {                  
382
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
383

    
384
                    string EGTAG = "EGTAG";
385
                    string ItemTag = "ItemTag";
386
                    string EGFlowDirection = string.Empty;
387
                    string Prefix = string.Empty;
388
                    
389

    
390
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
391
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
392
                    {
393
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
394
                        {
395
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
396
                            if (!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
397
                                EGTAG = PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null
398
                                   ? string.Empty : PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
399

    
400
                            ItemTag = PSNItem.Groups.First().Items.First().Equipment.ItemTag;
401
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;                            
402
                            EGFlowDirection = "O";
403
                        }                        
404
                    } 
405
                    else if(PSNItem.Groups.Last().Items.Last().Equipment != null)
406
                    {
407
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
408
                        {
409
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
410
                            if (!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
411
                                EGTAG = PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null
412
                                    ? string.Empty : PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
413

    
414
                            ItemTag = PSNItem.Groups.Last().Items.Last().Equipment.ItemTag;
415
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;                            
416
                            EGFlowDirection = "I";
417
                        }
418
                    }
419

    
420
                    //Attribute가 세팅되어있지 않다면
421
                    if (EGTAG.Equals("EGTAG"))
422
                    {
423
                        if (!eqkeyValuePairs.ContainsKey(ItemTag))
424
                        {
425
                            pumpTagNum++;
426
                            EGTAG = Prefix + string.Format("-{0}", string.Format("{0:D5}", pumpTagNum));
427
                            eqkeyValuePairs.Add(ItemTag, EGTAG);
428
                        }
429
                        else
430
                        {
431
                            EGTAG = eqkeyValuePairs[ItemTag];
432
                        }
433
                    }
434
                    else
435
                    {
436
                        EGTAG = Prefix + "-" + EGTAG;
437
                    }
438

    
439
                    foreach (DataRow dr in pathItemRows)
440
                    {
441
                        dr["EqpGroupTag"] = EGTAG;
442
                        dr["EGFlowDirection"] = EGFlowDirection;
443
                    }
444
                }
445

    
446
                // 3, 4번
447
                foreach (DataRow dataRow in pumpRows) 
448
                {
449

    
450
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
451
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
452
                    string EGFlowDirection = string.Empty;
453

    
454
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
455
                    {
456
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
457
                        {
458
                            EGFlowDirection = "O";
459
                        }
460
                    }
461
                    else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
462
                    {
463
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
464
                        {
465
                            EGFlowDirection = "I";
466
                        }
467
                    }
468

    
469

    
470
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
471

    
472
                    foreach (DataRow dr in pathItemRows)
473
                    {
474
                        if(dr.Field<string>("ViewPipeSystemNetwork_OID") != dataRow["OID"].ToString())
475
                        {
476
                            string viewEGFlowDirection = string.Empty;
477
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}'", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
478
                            {
479
                                PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));                               
480

    
481
                                if (viewPSNItem.Groups.First().Items.First().Equipment != null)
482
                                {
483
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
484
                                    {
485
                                        viewEGFlowDirection = "O";
486
                                    }
487
                                }
488
                                else if (viewPSNItem.Groups.Last().Items.Last().Equipment != null)
489
                                {
490
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
491
                                    {
492
                                        viewEGFlowDirection = "I";
493
                                    }
494
                                }
495

    
496
                                if (EGFlowDirection.Equals(viewEGFlowDirection) && !lstViewPipeSystemNetwork_OID.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
497
                                    lstViewPipeSystemNetwork_OID.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
498
                            }
499
                            else
500
                            {
501
                            }
502
                        }
503
                    }
504

    
505
                    string selectViewOID = string.Empty;
506

    
507
                    if (EGFlowDirection == "O") //From 이면 시작점에서 제일 먼 값
508
                    {
509
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
510
                        {
511
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
512
                            {                                
513
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
514
                            }
515
                        }
516
                    }
517
                    else if (EGFlowDirection == "I") //To 이면 시작점에서 제일 가까운 값
518
                    {
519
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
520
                        {
521
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
522
                            {
523
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
524
                                break;
525
                            }
526
                        }
527
                    }
528

    
529
                    if (!string.IsNullOrEmpty(selectViewOID)) //selectViewOID 가 있으면
530
                    {              
531
                        string EqpGroupTag = string.Empty;                       
532

    
533
                        if((EGFlowDirection == "O" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.Last().Field<string>("ViewPipeSystemNetwork_OID"))) ||
534
                            (EGFlowDirection == "I" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID"))))
535
                        { 
536
                            DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID")));
537

    
538
                            foreach (DataRow row in viewpathItemRows)
539
                            {
540
                                if (!string.IsNullOrEmpty(row.Field<string>("EqpGroupTag")))
541
                                {
542
                                    EqpGroupTag = row.Field<string>("EqpGroupTag");
543
                                    break;
544
                                }
545
                            }
546

    
547
                            foreach (DataRow dr in pathItemRows)
548
                            {
549
                                dr["EqpGroupTag"] = EqpGroupTag;
550
                            }
551

    
552
                        }
553
                        else
554
                        {
555
                            bool bCheck = false;
556
                            if (EGFlowDirection == "I") //To 일때
557
                            {
558
                                foreach (DataRow dr in pathItemRows)
559
                                {
560
                                    if (selectViewOID == dr["OID"].ToString())
561
                                    {
562
                                        dr["EGTConnectedPoint"] = "1";
563
                                        bCheck = true;
564
                                    }
565

    
566
                                    if (!bCheck)
567
                                    {
568
                                        dr["EqpGroupTag"] = string.Empty;
569
                                        dr["MainLineTag"] = string.Empty;
570
                                        dr["EGTConnectedPoint"] = "0";
571
                                        dr["EGFlowDirection"] = string.Empty;
572
                                    }
573
                                    else
574
                                    {
575
                                        dr["MainLineTag"] = "M";
576
                                    }
577
                                    
578
                                }
579

    
580
                            }
581
                            else if (EGFlowDirection == "O") //From 일 때
582
                            {
583
                                foreach (DataRow dr in pathItemRows)
584
                                {
585
                                    if (bCheck)
586
                                    {
587
                                        
588
                                        dr["EqpGroupTag"] = string.Empty;
589
                                        dr["MainLineTag"] = string.Empty;
590
                                        dr["EGTConnectedPoint"] = "0";
591
                                        dr["EGFlowDirection"] = string.Empty;
592
                                    }
593
                                    else
594
                                    {
595
                                        dr["MainLineTag"] = "M";
596
                                    }
597

    
598
                                    if (selectViewOID == dr["OID"].ToString())
599
                                    {
600
                                        dr["EGTConnectedPoint"] = "1";
601
                                        bCheck = true;
602
                                    }
603
                                }
604
                            }
605
                        }
606
                    }
607
                    else
608
                    {
609
                        foreach (DataRow dr in pathItemRows)
610
                        {
611
                            dr["EqpGroupTag"] = string.Empty;
612
                            dr["EGFlowDirection"] = string.Empty;
613
                        }
614
                    }
615
                }
616
                                
617
                // 5번
618
                foreach (DataRow dataRow in pumpRows)
619
                {
620
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
621

    
622
                    bool bCheck = false;
623
                    string EqpGroupTag = string.Empty;
624

    
625
                    string EGFlowDirection = string.Empty;                   
626

    
627
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow.Field<string>("OID"));
628

    
629
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
630
                    {
631
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
632
                        {
633
                            EGFlowDirection = "O";
634
                        }
635
                    }
636
                    else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
637
                    {
638
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
639
                        {
640
                            EGFlowDirection = "I";
641
                        }
642
                    }
643

    
644
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
645
                    List<string> lstEqTagRows = new List<string>();
646
                    if (EGFlowDirection.Equals("I"))
647
                    {
648
                        foreach (DataRow dr in pathItemRows)
649
                        {                            
650
                            if (!string.IsNullOrEmpty(dr.Field<string>("MainLineTag")) && dr.Field<string>("MainLineTag").Equals("M") && !string.IsNullOrEmpty(dr.Field<string>("EqpGroupTag")))
651
                            {
652
                                bCheck = true;
653
                                EqpGroupTag = dr.Field<string>("EqpGroupTag");
654
                                if(!lstEqTagRows.Contains(EqpGroupTag))
655
                                    lstEqTagRows.Add(EqpGroupTag);
656

    
657
                                if(dataRow["OID"].ToString() != dr.Field<string>("ViewPipeSystemNetwork_OID"))
658
                                {
659
                                    PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));
660
                                    if (viewPSNItem.Groups.Last().Items.Last().Equipment == null)
661
                                        continue;
662

    
663
                                    if (!lstEqTagRows.Contains(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag))
664
                                        lstEqTagRows.Add(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag);
665
                                }
666
                                
667
                            }
668

    
669
                        }
670
                        if(bCheck)
671
                        {
672
                            foreach (DataRow row in pumpRows)
673
                            {
674
                                if (row.Field<string>("OID").Equals(dataRow["OID"].ToString()))
675
                                    continue;
676

    
677
                                PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == row["OID"].ToString());
678

    
679
                                if (viewPSNItem.Groups.First().Items.First().Equipment == null)
680
                                    continue;
681
                                
682
                                if (lstEqTagRows.Contains(viewPSNItem.Groups.First().Items.First().Equipment.ItemTag) && !lstViewPipeSystemNetwork_OID.Contains(row.Field<string>("OID")))
683
                                    lstViewPipeSystemNetwork_OID.Add(row.Field<string>("OID"));
684
                            }
685

    
686
                                
687

    
688
                            if (lstViewPipeSystemNetwork_OID.Count() > 0)
689
                            {
690
                                foreach (string viewPipesystem in lstViewPipeSystemNetwork_OID)
691
                                {
692
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewPipesystem));
693
                                    foreach (DataRow viewdr in viewpathItemRows)
694
                                    {
695
                                        if (!string.IsNullOrEmpty(viewdr["EqpGroupTag"].ToString()))
696
                                            viewdr["EqpGroupTag"] = EqpGroupTag;
697
                                    }
698
                                }
699
                            }
700
                        }                        
701
                    }                   
702
                }
703
                
704
                int afcTagNum = 0;
705
                DataRow[] airFinCoolerRows = PipeSystemNetwork.Select("AFC Like 'P1%'");
706
                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
707
                foreach (DataRow dataRow in airFinCoolerRows)
708
                {
709
                    string EGFlowDirection = string.Empty;
710
                    string EGTAG = "EGTAG";
711
                    string Prefix = string.Empty;
712
                    //item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
713
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
714
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
715
                    {
716
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
717
                        {
718
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
719
                            if(!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
720
                                EGTAG = PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null 
721
                                    ? string.Empty : PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
722

    
723
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;
724
                            EGFlowDirection = "O";
725
                        }
726
                    }
727
                    else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
728
                    {
729
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
730
                        {
731
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
732
                            if (!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
733
                                EGTAG = PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null 
734
                                    ? string.Empty : PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
735

    
736
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;
737
                            EGFlowDirection = "I";
738
                        }
739
                    }
740

    
741
                    if(!string.IsNullOrEmpty(EGFlowDirection))
742
                    {
743
                        string[] afcTag = dataRow.Field<string>("AFC").Split(new string[] { "\\" }, StringSplitOptions.None);
744

    
745
                        //Attribute가 세팅되어있지 않다면
746
                        if (EGTAG.Equals("EGTAG"))
747
                        {
748
                            if (!keyValuePairs.ContainsKey(afcTag[1]))
749
                            {
750
                                afcTagNum++;
751
                                EGTAG = Prefix + string.Format("-{0}", string.Format("{0:D5}", afcTagNum));
752
                                keyValuePairs.Add(afcTag[1], EGTAG);
753
                            }
754
                            else
755
                            {
756
                                EGTAG = keyValuePairs[afcTag[1]];
757
                            }
758
                        }
759
                        else
760
                        {
761
                            EGTAG = Prefix + "-" + EGTAG;
762
                        }
763

    
764
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
765
                        foreach (DataRow dr in pathItemRows)
766
                        {
767
                            dr["EqpGroupTag"] = EGTAG;
768
                            dr["EGFlowDirection"] = EGFlowDirection;
769
                        }
770
                    }
771
                    
772
                }
773

    
774
                List<string> changePSN = new List<string>();
775
                foreach (DataRow dataRow in airFinCoolerRows)
776
                {
777
                    if (changePSN.Contains(dataRow["OID"].ToString()))
778
                        continue;
779

    
780
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
781
                    string AFCTag = string.Empty;
782
                    if (pathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).Count() > 0)
783
                        AFCTag = pathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).First().Field<string>("EqpGroupTag");
784

    
785
                    List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
786

    
787
                    if (dataRow["Type"].ToString() == "E2E")
788
                    {
789
                        foreach (DataRow dr in pathItemRows)
790
                        {
791
                            dr["MainLineTag"] = "M";
792
                        }
793
                        dataRow["AFC"] = "P3";
794
                    }
795
                    else if (dataRow["Type"].ToString() == "E2B" || dataRow["Type"].ToString() == "B2E")
796
                    {
797
                        foreach (string lstoid in lstViewPipeSystemNetwork_OID)
798
                        {
799
                            DataRow[] p2psn = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", lstoid));
800

    
801
                            if (p2psn.Count() > 0)
802
                            {
803
                                DataRow[] viewPathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstoid));
804
                                List<string> lstview = viewPathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
805
                                lstview.Remove(dataRow["OID"].ToString()); // P1인 자신 제거
806
                                lstview.Remove(lstoid); // P2 자신 제거
807

    
808
                                List<string> lstnewpipe = new List<string>();
809
                                foreach (string lstvw in lstview) //자신 외 P1이 있는지 확인
810
                                {
811
                                    if (airFinCoolerRows.Where(x => x.Field<string>("OID").Equals(lstvw)).Count() > 0) //P1이면 리스트에 추가
812
                                        lstnewpipe.Add(lstvw);
813
                                }
814

    
815
                                if (lstnewpipe.Count() == 0)
816
                                {
817
                                    foreach (DataRow dr in pathItemRows)
818
                                    {
819
                                        dr["MainLineTag"] = "M";
820
                                    }
821
                                    dataRow["AFC"] = "P3";
822
                                }
823
                                else
824
                                {
825
                                    // P2에 ML값 AGT값 지정
826
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstoid));
827
                                    DataRow[] pipesystemRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", lstoid));
828
                                    foreach (DataRow viewdr in pipesystemRows)
829
                                    {
830
                                        viewdr["AFC"] = "P4";
831
                                    }
832

    
833
                                    foreach (DataRow viewdr in viewpathItemRows)
834
                                    {
835
                                        viewdr["EqpGroupTag"] = AFCTag;
836
                                        viewdr["MainLineTag"] = "M";
837
                                    }
838
                                    // 연결된 모든 P1들의 AGT값 치환
839
                                    foreach (string pipe in lstnewpipe)
840
                                    {
841
                                        viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipe));
842
                                        foreach (DataRow viewdr in viewpathItemRows)
843
                                        {
844
                                            viewdr["EqpGroupTag"] = AFCTag;
845
                                        }
846
                                    }
847
                                }
848
                            }                               
849
                        }   
850
                    }
851
                }
852
                
853
                //P3을 제외한 P1
854
                airFinCoolerRows = PipeSystemNetwork.Select("AFC Like 'P1%'");
855
                foreach (DataRow dataRow in airFinCoolerRows)
856
                {
857
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
858
                    
859
                    if (pathItemRows.Count() > 0)
860
                    {
861
                        List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
862
                        List<string> lstpsn = new List<string>();
863
                        List<string> lstAll = new List<string>();
864
                        string EqpGroupTag = string.Empty;
865
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
866
                        {
867
                            if (dataRow["OID"].ToString() == viewOID)
868
                            {
869
                                lstAll.Add(viewOID);
870
                                continue;
871
                            }
872

    
873
                            //P3이면
874
                            DataRow viewPSN = null;
875
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).Count() > 0)
876
                                viewPSN = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).First();
877
                            
878
                            if (viewPSN != null)
879
                            {
880
                                //P3의 AGT를 가져와 P1에 입력
881
                                if(string.IsNullOrEmpty(EqpGroupTag))
882
                                    EqpGroupTag = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID)).First().Field<string>("EqpGroupTag");
883

    
884
                                foreach (DataRow dr in pathItemRows)
885
                                {
886

    
887
                                    dr["EqpGroupTag"] = EqpGroupTag;
888

    
889
                                    //P1의 AGT와 같은 모든 AGT를 P3의 AGT로 변경하기위해 
890
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
891
                                    {
892
                                        //AND MainLineTag = ''
893
                                        if (PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' ", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
894
                                        {
895
                                            lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
896
                                            lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
897
                                        }
898
                                    }
899
                                }
900
                            }
901
                            
902
                        }
903

    
904
                        while (lstpsn.Count() != 0)
905
                        {                            
906
                            DataRow[] rule4pathItems = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstpsn[0]));
907
                            foreach (DataRow dr in rule4pathItems)
908
                            {
909
                                if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstAll.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
910
                                {
911
                                    DataRow viewPSN = null;
912

    
913
                                    if (airFinCoolerRows.Where(x => x.Field<string>("OID") == dr.Field<string>("ViewPipeSystemNetwork_OID")).Count() > 0)
914
                                        viewPSN = airFinCoolerRows.Where(x => x.Field<string>("OID") == dr.Field<string>("ViewPipeSystemNetwork_OID")).First();
915
                                                                        
916
                                    if (viewPSN != null)
917
                                    {
918
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
919
                                        lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
920
                                    }
921
                                }                                
922

    
923
                                dr["EqpGroupTag"] = EqpGroupTag;
924

    
925
                            }
926
                            lstpsn.Remove(lstpsn[0]);
927
                        }
928
                    }
929
                    
930
                }
931

    
932
                foreach(DataRow dr in PipeSystemNetwork.Rows)
933
                {
934
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = 'M'", dr["OID"].ToString()));
935
                    if(pathItemRows.Count() > 0)
936
                    {
937
                        if(dr["Type"].ToString() == "HD2")
938
                        {
939
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
940
                            foreach(string viewpsn in lstViewPipeSystemNetwork_OID)
941
                            {                              
942
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", viewpsn)).Count() > 0)
943
                                {
944
                                    foreach(DataRow dataRow in pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewpsn))
945
                                    {
946
                                        dataRow["EGTConnectedPoint"] = "1";
947
                                    }
948
                                }
949
                            }
950
                        }
951
                        else if(dr["Type"].ToString() == "E2B" || dr["Type"].ToString() == "B2E" || dr["Type"].ToString() == "E2E")
952
                        {
953
                            PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dr["OID"].ToString());
954
                            string EGFlowDirection = string.Empty;
955
                            if (PSNItem.Groups.First().Items.First().Equipment != null)
956
                            {
957
                                if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
958
                                {
959
                                    EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
960
                                    if (equipmentAirFinCoolerItem != null)
961
                                        EGFlowDirection = "O";
962
                                }
963
                            }
964
                            else if (PSNItem.Groups.Last().Items.Last().Equipment != null)
965
                            {
966
                                if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
967
                                {
968
                                    EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
969
                                    if(equipmentAirFinCoolerItem != null)
970
                                        EGFlowDirection = "I";
971
                                }
972
                            }
973

    
974
                            if (!string.IsNullOrEmpty(EGFlowDirection))
975
                            {
976
                                List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
977
                                string lastP1 = string.Empty;
978

    
979
                                foreach (string viewpsn in lstViewPipeSystemNetwork_OID)
980
                                {
981
                                    if (viewpsn == dr["OID"].ToString())
982
                                        continue;
983

    
984
                                    if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC Like 'P1%'", viewpsn)).Length == 0)
985
                                        continue;
986

    
987
                                    DataRow rows = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC Like 'P1%'", viewpsn)).First();
988

    
989
                                    if (rows != null)
990
                                    {
991
                                        lastP1 = viewpsn;
992
                                        if (EGFlowDirection.Equals("I")) // To         
993
                                            break;
994
                                    }
995
                                }
996

    
997
                                if (!string.IsNullOrEmpty(lastP1))
998
                                {
999
                                    bool bCheck = false;
1000
                                    if (EGFlowDirection.Equals("O")) // From
1001
                                    {
1002
                                        foreach (DataRow dataRow in pathItemRows)
1003
                                        {
1004
                                            if (bCheck)
1005
                                                dataRow["EqpGroupTag"] = string.Empty;
1006

    
1007
                                            if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
1008
                                            {
1009
                                                bCheck = true;
1010
                                                dataRow["EGTConnectedPoint"] = 1;
1011
                                            }
1012
                                        }
1013
                                    }
1014
                                    else
1015
                                    {
1016
                                        foreach (DataRow dataRow in pathItemRows)
1017
                                        {
1018
                                            if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
1019
                                            {
1020
                                                dataRow["EGTConnectedPoint"] = 1;
1021
                                                break;
1022
                                            }
1023
                                            
1024
                                            dataRow["EqpGroupTag"] = string.Empty;                                           
1025
                                        }
1026
                                    }
1027
                                }
1028
                            }                          
1029
                        }
1030
                    }
1031
                }
1032

    
1033
                //psn data 정리
1034
                foreach(DataRow pipesystem in PipeSystemNetwork.Rows)
1035
                {
1036
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipesystem["OID"].ToString()));
1037
                    string EGTag = string.Empty;
1038
                    string HasMLTags = "False";
1039

    
1040
                    foreach (DataRow dataRow in pathItemRows)
1041
                    {
1042
                        if (string.IsNullOrEmpty(EGTag) && !string.IsNullOrEmpty(dataRow.Field<string>("EqpGroupTag")))
1043
                            EGTag = dataRow.Field<string>("EqpGroupTag");
1044

    
1045
                        if (HasMLTags.Equals("False") && !string.IsNullOrEmpty(dataRow.Field<string>("MainLineTag")) && dataRow.Field<string>("MainLineTag").Equals("M"))
1046
                            HasMLTags = "True";
1047

    
1048
                        if (!string.IsNullOrEmpty(EGTag) && HasMLTags == "True")
1049
                            break;
1050
                    }
1051

    
1052
                    pipesystem["EGTag"] = EGTag;
1053
                    pipesystem["HasMLTags"] = HasMLTags;
1054
                }
1055
            }
1056
            catch (Exception ex)
1057
            {
1058
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
1059
            }
1060
            //}
1061
        }
1062

    
1063
        private void UpdateValveGrouping()
1064
        {
1065
            try
1066
            {
1067
                #region ValveGrouping Info
1068
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
1069
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
1070
                foreach (DataRow row in dtValveGroupung.Rows)
1071
                {
1072
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
1073
                    {
1074
                        OID = row["OID"].ToString(),
1075
                        GroupType = row["GroupType"].ToString(),
1076
                        TagIdentifier = row["TagIdentifier"].ToString(),
1077
                        AttributeName = row["AttributeName"].ToString(),
1078
                        SppidSymbolName = row["SppidSymbolName"].ToString()
1079
                    });
1080
                }
1081
                #endregion
1082

    
1083

    
1084
                int vgTagNum = 1;
1085
                DataRow[] tagpathItemRows = PathItems.Select(string.Format("GROUPTAG Like '%\\%'"));
1086
                foreach (DataRow drPathitem in tagpathItemRows)
1087
                {
1088
                    string[] valvetag = drPathitem["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
1089
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1090
                    ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
1091
                    if (valveitem == null || valveitem.GroupType == "Scope Break")
1092
                        continue;
1093
                    Dictionary<int, List<DataRow>> keyValuePairs = new Dictionary<int, List<DataRow>>();
1094
                    List<Item> valveGroupingItem = new List<Item>();
1095
                    int bCnt = 0;
1096

    
1097
                    
1098
                    List<DataRow> lstitem = new List<DataRow>();
1099
                    foreach (DataRow dr in pathItemRows)
1100
                    {
1101
                        if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1102
                        {
1103
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));
1104
                            if (dr["GROUPTAG"].ToString() == "Scope Break")
1105
                            {
1106
                                dr["GROUPTAG"] = string.Empty;
1107
                                keyValuePairs.Add(bCnt, lstitem.ToList());
1108
                                bCnt++;
1109
                                lstitem.Clear();
1110
                            }
1111
                            else
1112
                            {
1113
                                if (rows.First()["SubType"].ToString() != "Bypass" && rows.First()["SubType"].ToString() != "Vent_Drain")
1114
                                {
1115
                                    if (lstitem.ToList().Where(x => !string.IsNullOrEmpty(x.Field<string>("GROUPTAG"))).Count() > 0)
1116
                                    {
1117
                                        lstitem.Add(dr);
1118
                                        keyValuePairs.Add(bCnt, lstitem.ToList());
1119
                                        lstitem.Clear();
1120
                                    }
1121
                                    else
1122
                                    {
1123
                                        keyValuePairs.Add(bCnt, lstitem.ToList());
1124
                                        lstitem.Clear();
1125
                                        lstitem.Add(dr);
1126
                                    }
1127
                                    bCnt++;
1128

    
1129
                                }
1130
                                else
1131
                                    lstitem.Add(dr);
1132
                            }
1133
                        }
1134
                        else
1135
                            lstitem.Add(dr);
1136
                    }
1137

    
1138
                    if (lstitem.Count > 0)
1139
                    {
1140
                        keyValuePairs.Add(bCnt, lstitem);
1141
                    }
1142

    
1143
                    if (keyValuePairs.Count() == 0)
1144
                        continue;
1145

    
1146
                    string VGTag = string.Empty;
1147
                    if (valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
1148
                    {
1149
                        VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1150
                        vgTagNum++;
1151
                    }
1152
                    else
1153
                    {
1154
                        //if(string.IsNullOrEmpty(valvetag[1]))
1155
                        //    VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1156
                        //else
1157
                        VGTag = valveitem.TagIdentifier + "-" + valvetag[1];
1158
                    }
1159

    
1160
                    foreach (KeyValuePair<int, List<DataRow>> keyValuePair in keyValuePairs)
1161
                    {
1162
                        if (keyValuePair.Value.Where(x => x.Field<string>("OID") == drPathitem.Field<string>("OID")).Count() > 0)
1163
                        {
1164
                            foreach (DataRow dr in keyValuePair.Value)
1165
                            {
1166
                                dr["GROUPTAG"] = VGTag;
1167

    
1168
                                if(!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1169
                                {
1170
                                    if(TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString())).First().Field<string>("SubType") == "Bypass")
1171
                                    {
1172
                                        DataRow[] rows = keyValuePair.Value.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID").Equals(dr["ViewPipeSystemNetwork_OID"].ToString())).ToArray();
1173
                                        foreach(DataRow path in rows)
1174
                                        {
1175
                                            DataRow topology = TopologySet.Select(string.Format("OID = '{0}'", path["BranchTopologySet_OID"].ToString())).First();
1176
                                            if (topology.Field<string>("SubType").Equals("Bypass"))
1177
                                            {
1178
                                                DataRow[] drPathItem = PathItems.Select(string.Format("TopologySet_OID = '{0}'", topology.Field<string>("OID")));
1179
                                                foreach(DataRow pathitem in drPathItem)
1180
                                                {
1181
                                                    pathitem["GROUPTAG"] = VGTag;
1182
                                                }
1183
                                            }
1184
                                        }
1185
                                    }
1186
                                }
1187
                            }
1188
                        }
1189
                    }
1190
                    if(valveitem.GroupType.Contains("PSV"))
1191
                    {
1192
                        DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1193
                        foreach (DataRow row in psnRows)
1194
                            row["Pocket"] = "Yes";
1195
                    }                    
1196
                }
1197
            }
1198
            catch (Exception ex)
1199
            {
1200
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
1201
            }
1202
        }
1203

    
1204
        private void SetTopologyData()
1205
        {
1206
            // 13번 excel
1207
            foreach (Group group in groups)
1208
            {
1209
                LineNumber prevLineNumber = null;
1210
                for (int i = 0; i < group.Items.Count; i++)
1211
                {
1212
                    Item item = group.Items[i];
1213
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1214
                    if (lineNumber == null)
1215
                    {
1216
                        if (prevLineNumber != null)
1217
                        {
1218
                            if (!prevLineNumber.IsCopy)
1219
                            {
1220
                                prevLineNumber = prevLineNumber.Copy();
1221
                                item.Document.LineNumbers.Add(prevLineNumber);
1222
                                item.Document.MissingLineNumber1 = true;
1223
                            }
1224
                            item.Owner = prevLineNumber.UID;
1225
                        }
1226
                    }
1227
                    else
1228
                        prevLineNumber = lineNumber;
1229
                }
1230

    
1231
                prevLineNumber = null;
1232
                for (int i = group.Items.Count - 1; i > -1; i--)
1233
                {
1234
                    Item item = group.Items[i];
1235
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1236
                    if (lineNumber == null)
1237
                    {
1238
                        if (prevLineNumber != null)
1239
                        {
1240
                            if (!prevLineNumber.IsCopy)
1241
                            {
1242
                                prevLineNumber = prevLineNumber.Copy();
1243
                                item.Document.LineNumbers.Add(prevLineNumber);
1244
                                item.Document.MissingLineNumber1 = true;
1245
                            }
1246

    
1247
                            item.Owner = prevLineNumber.UID;
1248
                        }
1249
                    }
1250
                    else
1251
                        prevLineNumber = lineNumber;
1252
                }
1253

    
1254
                if (prevLineNumber == null)
1255
                {
1256
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
1257
                    Random random = new Random();
1258

    
1259
                    LineNumber cLineNumber = null;
1260

    
1261
                    if (lineNumbers.Count == 0)
1262
                    {
1263
                        var _groups = groups.Where(w => w != group).ToList();
1264
                        while (cLineNumber == null)
1265
                        {
1266
                            int _index = random.Next(_groups.Count - 1);
1267
                            List<LineNumber> _lineNumbers = groups[_index].Document.LineNumbers.FindAll(x => !x.IsCopy);
1268
                            if (_lineNumbers.Count != 0)
1269
                            {
1270
                                _index = random.Next(_lineNumbers.Count - 1);
1271

    
1272
                                // Copy
1273
                                cLineNumber = _lineNumbers[_index].Copy();
1274
                            }
1275
                        }
1276
                    }
1277
                    else
1278
                    {
1279
                        int index = random.Next(lineNumbers.Count - 1);
1280

    
1281
                        // Copy
1282
                        cLineNumber = lineNumbers[index].Copy();
1283
                    }
1284

    
1285
                    group.Document.LineNumbers.Add(cLineNumber);
1286

    
1287
                    foreach (Item item in group.Items)
1288
                    {
1289
                        item.Owner = cLineNumber.UID;
1290
                        item.MissingLineNumber2 = true;
1291
                    }
1292
                }
1293

    
1294
                //if (prevLineNumber == null)
1295
                //{
1296
                //    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
1297
                //    Random random = new Random();
1298
                //    int index = random.Next(lineNumbers.Count - 1);
1299

    
1300
                //    // Copy
1301
                //    LineNumber cLineNumber = lineNumbers[index].Copy();
1302
                //    group.Document.LineNumbers.Add(cLineNumber);
1303

    
1304
                //    foreach (Item item in group.Items)
1305
                //    {
1306
                //        item.Owner = cLineNumber.UID;
1307
                //        item.Document.MissingLineNumber2 = true;
1308
                //    }
1309
                //}
1310
            }
1311

    
1312
            foreach (Document document in Documents)
1313
            {
1314
                foreach (Item item in document.Items)
1315
                {
1316
                    item.TopologyData = string.Empty;
1317
                    item.PSNPipeLineID = string.Empty;
1318
                    List<string> pipeLineID = new List<string>();
1319
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
1320
                    
1321
                    if (lineNumber != null)
1322
                    {
1323
                        item.LineNumber = lineNumber;
1324

    
1325
                        foreach (DataRow row in topologyRuleDT.Rows)
1326
                        {
1327
                            string uid = row["UID"].ToString();
1328
                            //if (uid == "-")
1329
                            //    pipeLineID.Add(item.TopologyData);//item.TopologyData += "-"; 
1330
                            if (uid != "-")
1331
                            {
1332
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
1333

    
1334
                                Attribute attribute = lineNumber.Attributes.Find(x => x.DisplayName == uid);
1335
                                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
1336
                                {
1337
                                    pipeLineID.Add(attribute.Value);//item.TopologyData += attribute.Value;
1338
                                    if (uid.Equals("Tag Seq No") && attribute.Value.ToString().Substring(attribute.Value.ToString().Length - 1, 1).Equals("V"))
1339
                                    {
1340
                                        if (item.Document.MissingLineNumber1)
1341
                                            item.MissingLineNumber1 = true;
1342
                                        else if (item.Document.MissingLineNumber2)
1343
                                            item.MissingLineNumber2 = true;
1344
                                    }
1345
                                }
1346
                            }
1347
                        }
1348
                        
1349
                        if (topologyRuleDT.Select(string.Format("UID = '{0}'", "InsulationPurpose")) == null)
1350
                        {
1351
                            Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
1352
                            if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
1353
                                pipeLineID.Add(insulAttr.Value); //item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
1354
                                                                 //else
1355
                                                                 //    item.PSNPipeLineID = item.TopologyData;
1356
                        }
1357

    
1358
                        item.PSNPipeLineID = string.Join("-", pipeLineID);
1359
                        item.TopologyData = string.Join("-", pipeLineID);
1360
                        
1361
                    }
1362
                    else
1363
                    {
1364
                        item.TopologyData = "Empty LineNumber";
1365
                        item.LineNumber = new LineNumber();
1366
                    }
1367
                }
1368
            }
1369

    
1370
            int emptyIndex = 1;
1371
            foreach (Group group in groups)
1372
            {
1373
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
1374
                if (groupItems.Count > 0)
1375
                {
1376
                    foreach (var item in groupItems)
1377
                        item.TopologyData += string.Format("-{0}", emptyIndex);
1378
                    emptyIndex++;
1379
                }
1380
            }
1381

    
1382
        }
1383

    
1384
        private void ConnectByOPC()
1385
        {
1386
            try
1387
            {
1388
                foreach (Group group in groups.FindAll(x => x.Items.Last().SubItemType == SubItemType.OPC))
1389
                {
1390
                    Item opcItem = group.Items.Last();
1391
                    DataRow[] fromRows = opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID));
1392
                    if (fromRows.Length.Equals(1))
1393
                    {
1394
                        DataRow opcRow = fromRows.First();
1395
                        string toDrawing = opcRow["ToDrawing"].ToString();
1396
                        string toOPCUID = opcRow["ToOPCUID"].ToString();
1397

    
1398
                        Document toDocument = Documents.Find(x => x.DrawingName == toDrawing);
1399
                        if (toDocument != null)
1400
                        {
1401
                            Group toGroup = toDocument.Groups.Find(x => x.Items.Find(y => y.UID == toOPCUID) != null);
1402
                            DataRow[] toRows = opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID));
1403
                            //1대1 매칭이 아닐때 걸림 (2개 이상일 때) 2021.11.07 
1404
                            if (toRows.Length > 1)
1405
                            {
1406
                                //throw new Exception("OPC error(multi connect)");
1407
                                MessageBox.Show("OPC error(multi connect)", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1408
                                return;
1409
                            }
1410
                            group.EndGroup = toGroup;
1411
                            toGroup.StartGroup = group;
1412
                        }
1413
                    }
1414
                }
1415
            }
1416
            catch (Exception ex)
1417
            {
1418
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1419
                //MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1420
            }
1421
        }
1422

    
1423
        private void SetPSNItem()
1424
        {
1425
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>();
1426
            foreach (Group group in groups)
1427
                groupDic.Add(group, Guid.NewGuid().ToString());
1428

    
1429
            foreach (Group group in groups)
1430
            {
1431
                string groupKey = groupDic[group];
1432
                if (group.StartGroup != null)
1433
                {
1434
                    string otherKey = groupDic[group.StartGroup];
1435
                    ChangeGroupID(otherKey, groupKey);
1436
                }
1437
            }
1438

    
1439
            // PSN 정리
1440
            foreach (var item in groupDic)
1441
            {
1442
                Group group = item.Key;
1443
                string uid = item.Value;
1444
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
1445
                if (PSNItem == null)
1446
                {
1447
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
1448
                    PSNItems.Add(PSNItem);
1449
                }
1450
                PSNItem.Groups.Add(group);
1451
                foreach (Item groupItem in group.Items)
1452
                    groupItem.PSNItem = PSNItem;
1453
            }
1454

    
1455
            // Sort PSN
1456
            foreach (PSNItem PSNItem in PSNItems)
1457
            {
1458
                List<Group> _groups = new List<Group>();
1459

    
1460
                Stack<Group> stacks = new Stack<Group>();
1461
                stacks.Push(PSNItem.Groups.First());
1462
                while (stacks.Count > 0)
1463
                {
1464
                    Group stack = stacks.Pop();
1465
                    if (_groups.Contains(stack))
1466
                        continue;
1467

    
1468
                    if (_groups.Count == 0)
1469
                        _groups.Add(stack);
1470
                    else
1471
                    {
1472
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
1473
                        {
1474
                            int index = _groups.IndexOf(stack.StartGroup);
1475
                            _groups.Insert(index + 1, stack);
1476
                        }
1477
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
1478
                        {
1479
                            int index = _groups.IndexOf(stack.EndGroup);
1480
                            _groups.Insert(index, stack);
1481
                        }
1482
                    }
1483

    
1484
                    if (stack.StartGroup != null)
1485
                        stacks.Push(stack.StartGroup);
1486
                    if (stack.EndGroup != null)
1487
                        stacks.Push(stack.EndGroup);
1488
                }
1489

    
1490
                PSNItem.Groups.Clear();
1491
                PSNItem.Groups.AddRange(_groups);
1492
            }
1493

    
1494
            void ChangeGroupID(string from, string to)
1495
            {
1496
                if (from.Equals(to))
1497
                    return;
1498

    
1499
                List<Group> changeItems = new List<Group>();
1500
                foreach (var _item in groupDic)
1501
                    if (_item.Value.Equals(from))
1502
                        changeItems.Add(_item.Key);
1503
                foreach (var _item in changeItems)
1504
                    groupDic[_item] = to;
1505
            }
1506
        }
1507

    
1508
        private void SetPSNType()
1509
        {
1510
            foreach (PSNItem PSNItem in PSNItems)
1511
            {
1512
                Group firstGroup = PSNItem.Groups.First();
1513
                Group lastGroup = PSNItem.Groups.Last();
1514

    
1515
                Item firstItem = firstGroup.Items.First();
1516
                Item lastItem = lastGroup.Items.Last();
1517

    
1518
                PSNItem.StartType = GetPSNType(firstItem, true);
1519
                PSNItem.EndType = GetPSNType(lastItem, false);
1520

    
1521
            }
1522

    
1523
            PSNType GetPSNType(Item item, bool bFirst = true)
1524
            {
1525
                PSNType type = PSNType.None;
1526

    
1527
                if (item.ItemType == ItemType.Line)
1528
                {
1529
                    Group group = groups.Find(x => x.Items.Contains(item));
1530
                    if (bFirst && item.Relations[0].Item != null && !group.Items.Contains(item.Relations[0].Item))
1531
                    {
1532
                        Item connItem = item.Relations[0].Item;
1533
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1534
                            type = PSNType.Branch;
1535
                        else if (connItem.ItemType == ItemType.Symbol)
1536
                            type = PSNType.Symbol;
1537
                    }
1538
                    else if (!bFirst && item.Relations[1].Item != null && !group.Items.Contains(item.Relations[1].Item))
1539
                    {
1540
                        Item connItem = item.Relations[1].Item;
1541
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1542
                            type = PSNType.Branch;
1543
                        else if (connItem.ItemType == ItemType.Symbol)
1544
                            type = PSNType.Symbol;
1545
                    }
1546
                }
1547
                else if (item.ItemType == ItemType.Symbol)
1548
                {
1549
                    if (item.SubItemType == SubItemType.Nozzle)
1550
                        type = PSNType.Equipment;
1551
                    else if (item.SubItemType == SubItemType.Header)
1552
                        type = PSNType.Header;
1553
                    else if (item.SubItemType == SubItemType.OPC)
1554
                        type = PSNType.OPC;
1555
                }
1556

    
1557
                return type;
1558
            }
1559
        }
1560

    
1561
        private void SetBranchInfo()
1562
        {
1563
            foreach (Document document in Documents)
1564
            {
1565
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
1566
                foreach (Item line in lines)
1567
                {
1568
                    double[] point = line.Relations[0].Point;
1569
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
1570
                    connLines.Sort(SortBranchLine);
1571
                    line.BranchItems.AddRange(connLines);
1572

    
1573
                    int SortBranchLine(Item a, Item b)
1574
                    {
1575
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
1576
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
1577

    
1578
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
1579
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
1580

    
1581
                        // 내림차순
1582
                        return distanceA.CompareTo(distanceB);
1583
                    }
1584
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
1585
                    {
1586
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
1587
                    }
1588
                }
1589
            }
1590
        }
1591

    
1592
        private void SetTopology()
1593
        {
1594
            try
1595
            {
1596
                #region 기본 topology 정리
1597
                foreach (PSNItem PSNItem in PSNItems)
1598
                {
1599
                    Topology topology = null;
1600
                    foreach (Group group in PSNItem.Groups)
1601
                    {
1602
                        foreach (Item item in group.Items)
1603
                        {
1604
                            if (string.IsNullOrEmpty(item.TopologyData))
1605
                                topology = null;
1606
                            else
1607
                            {
1608
                                if (topology == null)
1609
                                {
1610
                                    topology = new Topology()
1611
                                    {
1612
                                        ID = item.TopologyData
1613
                                    };
1614
                                    Topologies.Add(topology);
1615

    
1616
                                    if (!PSNItem.Topologies.Contains(topology))
1617
                                        PSNItem.Topologies.Add(topology);
1618
                                }
1619
                                else
1620
                                {
1621
                                    if (topology.ID != item.TopologyData)
1622
                                    {
1623
                                        topology = new Topology()
1624
                                        {
1625
                                            ID = item.TopologyData
1626
                                        };
1627
                                        Topologies.Add(topology);
1628

    
1629
                                        if (!PSNItem.Topologies.Contains(topology))
1630
                                            PSNItem.Topologies.Add(topology);
1631
                                    }
1632
                                }
1633

    
1634
                                item.Topology = topology;
1635
                                topology.Items.Add(item);
1636
                            }
1637
                        }
1638
                    }
1639
                }
1640
                #endregion
1641

    
1642
                #region Type
1643
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1644
                foreach (string id in ids)
1645
                {
1646
                    try
1647
                    {
1648

    
1649

    
1650
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1651

    
1652
                        // Main
1653
                        List<Topology> mainTopologies = FindMainTopology(topologies);
1654
                        foreach (Topology topology in mainTopologies)
1655
                            topology.Type = "M";
1656

    
1657
                        // Branch
1658
                        List<Topology> branchToplogies = topologies.FindAll(x => string.IsNullOrEmpty(x.Type));
1659
                        foreach (Topology topology in branchToplogies)
1660
                            topology.Type = "B";
1661
                    }
1662
                    catch (Exception ex)
1663
                    {
1664
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1665
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1666
                    }
1667
                }
1668
                #endregion
1669
            }
1670
            catch (Exception ex)
1671
            {
1672
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1673
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1674
            }
1675

    
1676
        }
1677

    
1678
        private void SetTopologyIndex()
1679
        {
1680
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1681
            foreach (string id in ids)
1682
            {
1683
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1684

    
1685
                // Main
1686
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
1687
                foreach (Topology topology in mainTopologies)
1688
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
1689

    
1690
                // Branch
1691
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
1692
                foreach (Topology topology in branchToplogies)
1693
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
1694
            }
1695
        }
1696

    
1697
        private void SetPSNBypass()
1698
        {
1699
            foreach (PSNItem PSNItem in PSNItems)
1700
                PSNItem.IsBypass = IsBypass(PSNItem);
1701
        }
1702

    
1703
        private List<Topology> FindMainTopology(List<Topology> data)
1704
        {
1705
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
1706
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
1707
            //2021.11.17 안쓰네 JY
1708
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
1709

    
1710
            List<Topology> main = new List<Topology>();
1711
            main.AddRange(data);
1712
            //
1713
            main = GetNozzleTopology(data);
1714
            if (main.Count == 1)
1715
                return main;
1716
            else
1717
            {
1718
                if (main.Count > 0)
1719
                    main = GetPMCTopology(main);
1720
                else
1721
                    main = GetPMCTopology(data);
1722

    
1723
                if (main.Count == 1)
1724
                    return main;
1725
                else
1726
                {
1727
                    if (main.Count > 0)
1728
                        main = GetDiaTopology(main);
1729
                    else
1730
                        main = GetDiaTopology(data);
1731

    
1732

    
1733
                    if (main.Count == 1)
1734
                        return main;
1735
                    else
1736
                    {
1737
                        if (main.Count > 0)
1738
                            main = GetItemTopology(main);
1739
                        else
1740
                            main = GetItemTopology(data);
1741
                    }
1742
                }
1743
            }
1744

    
1745
            List<Topology> GetNozzleTopology(List<Topology> topologies)
1746
            {
1747
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
1748
            }
1749

    
1750
            List<Topology> GetPMCTopology(List<Topology> topologies)
1751
            {
1752
                List<Topology> result = new List<Topology>();
1753
                foreach (DataRow row in PMCDT.Rows)
1754
                {
1755
                    string value = row["CODE"].ToString();
1756
                    foreach (Topology topology in topologies)
1757
                    {
1758
                        foreach (Item item in topology.Items)
1759
                        {
1760
                            if (item.LineNumber == null)
1761
                                continue;
1762
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1763
                            if (attribute != null && value == attribute.Value)
1764
                            {
1765
                                result.Add(topology);
1766
                                break;
1767
                            }
1768
                        }
1769
                    }
1770

    
1771
                    if (result.Count > 0)
1772
                        break;
1773
                }
1774

    
1775
                return result;
1776
            }
1777

    
1778
            List<Topology> GetDiaTopology(List<Topology> topologies)
1779
            {
1780
                List<Topology> result = new List<Topology>();
1781
                foreach (DataRow row in nominalDiameterDT.Rows)
1782
                {
1783
                    string inchValue = row["InchStr"].ToString();
1784
                    string metricValue = row["MetricStr"].ToString();
1785
                    foreach (Topology topology in topologies)
1786
                    {
1787
                        foreach (Item item in topology.Items)
1788
                        {
1789
                            if (item.LineNumber == null)
1790
                                continue;
1791
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1792
                            if (attribute != null && (inchValue == attribute.Value || metricValue == attribute.Value))
1793
                            {
1794
                                result.Add(topology);
1795
                                break;
1796
                            }
1797
                        }
1798
                    }
1799

    
1800
                    if (result.Count > 0)
1801
                        break;
1802
                }
1803

    
1804
                return result;
1805
            }
1806

    
1807
            List<Topology> GetItemTopology(List<Topology> topologies)
1808
            {
1809
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
1810
            }
1811

    
1812
            return main;
1813
        }
1814

    
1815
        private DataTable GetOPCInfo()
1816
        {
1817
            DataTable opc = DB.SelectOPCRelations();
1818
            DataTable drawing = DB.AllDrawings();
1819

    
1820
            DataTable dt = new DataTable();
1821
            dt.Columns.Add("FromDrawing", typeof(string));
1822
            dt.Columns.Add("FromDrawingUID", typeof(string));
1823
            dt.Columns.Add("FromOPCUID", typeof(string));
1824
            dt.Columns.Add("ToDrawing", typeof(string));
1825
            dt.Columns.Add("ToDrawingUID", typeof(string));
1826
            dt.Columns.Add("ToOPCUID", typeof(string));
1827
            foreach (DataRow row in opc.Rows)
1828
            {
1829
                string fromDrawingUID = row["From_Drawings_UID"] == null ? string.Empty : row["From_Drawings_UID"].ToString();
1830
                string fromOPCUID = row["From_OPC_UID"] == null ? string.Empty : row["From_OPC_UID"].ToString();
1831
                string toDrawingUID = row["To_Drawings_UID"] == null ? string.Empty : row["To_Drawings_UID"].ToString();
1832
                string toOPCUID = row["To_OPC_UID"] == null ? string.Empty : row["To_OPC_UID"].ToString();
1833
                if (!string.IsNullOrEmpty(toOPCUID))
1834
                {
1835
                    DataRow[] fromRows = drawing.Select(string.Format("UID = '{0}'", fromDrawingUID));
1836
                    DataRow[] toRows = drawing.Select(string.Format("UID = '{0}'", toDrawingUID));
1837
                    if (fromRows.Length.Equals(1) && toRows.Length.Equals(1))
1838
                    {
1839
                        string fromDrawingName = Path.GetFileNameWithoutExtension(fromRows.First()["NAME"].ToString());
1840
                        string toDrawingName = Path.GetFileNameWithoutExtension(toRows.First()["NAME"].ToString());
1841

    
1842
                        DataRow newRow = dt.NewRow();
1843
                        newRow["FromDrawing"] = fromDrawingName;
1844
                        newRow["FromDrawingUID"] = fromDrawingUID;
1845
                        newRow["FromOPCUID"] = fromOPCUID;
1846
                        newRow["ToDrawing"] = toDrawingName;
1847
                        newRow["ToDrawingUID"] = toDrawingUID;
1848
                        newRow["ToOPCUID"] = toOPCUID;
1849

    
1850
                        dt.Rows.Add(newRow);
1851
                    }
1852
                }
1853
            }
1854

    
1855
            return dt;
1856
        }
1857

    
1858
        private DataTable GetTopologyRule()
1859
        {
1860
            DataTable dt = DB.SelectTopologyRule();
1861

    
1862
            return dt;
1863
        }
1864

    
1865
        private bool IsConnected(Item item1, Item item2)
1866
        {
1867
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
1868
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
1869
                return true;
1870
            else
1871
                return false;
1872
        }
1873

    
1874
        private void SaveNozzleAndEquipment()
1875
        {
1876
            List<Item> nozzles = new List<Item>();
1877
            List<Equipment> equipments = new List<Equipment>();
1878
            foreach (Document document in Documents)
1879
            {
1880
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
1881
                equipments.AddRange(document.Equipments);
1882
            }
1883

    
1884

    
1885
            DataTable nozzleDT = new DataTable();
1886
            nozzleDT.Columns.Add("OID", typeof(string));
1887
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
1888
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
1889
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
1890
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
1891
            nozzleDT.Columns.Add("FLUID", typeof(string));
1892
            nozzleDT.Columns.Add("NPD", typeof(string));
1893
            nozzleDT.Columns.Add("PMC", typeof(string));
1894
            nozzleDT.Columns.Add("ROTATION", typeof(string));
1895
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
1896

    
1897
            foreach (Item item in nozzles)
1898
            {
1899
                DataRow row = nozzleDT.NewRow();
1900
                row["OID"] = item.UID;
1901

    
1902
                Relation relation = item.Relations.Find(x => equipments.Find(y => y.UID == x.UID) != null);
1903
                if (relation != null)
1904
                {
1905
                    Equipment equipment = equipments.Find(x => x.UID == relation.UID);
1906
                    equipment.Nozzles.Add(item);
1907
                    row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", equipment.Nozzles.Count + 100));
1908
                    row["Equipment_OID"] = equipment.UID;
1909
                    item.Equipment = equipment;
1910
                }
1911
                row["XCOORDS"] = (item.POINT[0] / DrawingWidth).ToString();
1912
                row["YCOORDS"] = (item.POINT[1] / DrawingHeight).ToString();
1913
                Attribute fluidAttr = item.LineNumber.Attributes.Find(x => x.Name == "FluidCode");
1914
                row["FLUID"] = fluidAttr != null ? fluidAttr.Value : string.Empty;
1915
                Attribute npdAttr = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1916
                row["NPD"] = npdAttr != null ? npdAttr.Value : string.Empty;
1917
                Attribute pmcAttr = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1918
                row["PMC"] = pmcAttr != null ? pmcAttr.Value : string.Empty;
1919

    
1920
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
1921
                if (angle >= Math.PI * 2)
1922
                    angle = angle - Math.PI * 2;
1923
                row["ROTATION"] = angle.ToString();
1924

    
1925
                if (item.Topology.Items.First().Equals(item))
1926
                    row["FlowDirection"] = "Outlet";
1927
                else if (item.Topology.Items.Last().Equals(item))
1928
                    row["FlowDirection"] = "Inlet";
1929
                else
1930
                    row["FlowDirection"] = string.Empty;
1931

    
1932
                nozzleDT.Rows.Add(row);
1933
            }
1934

    
1935
            DataTable equipDT = new DataTable();
1936
            equipDT.Columns.Add("OID", typeof(string));
1937
            equipDT.Columns.Add("ITEMTAG", typeof(string));
1938
            equipDT.Columns.Add("XCOORDS", typeof(string));
1939
            equipDT.Columns.Add("YCOORDS", typeof(string));
1940

    
1941
            foreach (Equipment equipment in equipments)
1942
            {
1943
                DataRow row = equipDT.NewRow();
1944
                row["OID"] = equipment.UID;
1945
                if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
1946
                {
1947
                    Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
1948
                    if (attribute != null)
1949
                        equipment.ItemTag = attribute.Value;
1950
                }
1951
                else
1952
                    equipment.ItemTag = equipment.Name;
1953

    
1954
                row["ITEMTAG"] = equipment.ItemTag;
1955
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
1956
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
1957

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

    
1961
                equipDT.Rows.Add(row);
1962
            }
1963

    
1964
            Equipment = equipDT;
1965
            Nozzle = nozzleDT;
1966
        }
1967

    
1968
        private void SavePSNData()
1969
        {
1970
            try
1971
            {
1972
                DataTable pathItemsDT = new DataTable();
1973
                pathItemsDT.Columns.Add("OID", typeof(string));
1974
                pathItemsDT.Columns.Add("SequenceData_OID", typeof(string));
1975
                pathItemsDT.Columns.Add("TopologySet_OID", typeof(string));
1976
                pathItemsDT.Columns.Add("BranchTopologySet_OID", typeof(string));
1977
                pathItemsDT.Columns.Add("PipeLine_OID", typeof(string));
1978
                pathItemsDT.Columns.Add("ITEMNAME", typeof(string));
1979
                pathItemsDT.Columns.Add("ITEMTAG", typeof(string));
1980
                pathItemsDT.Columns.Add("DESCRIPTION", typeof(string));
1981
                pathItemsDT.Columns.Add("Class", typeof(string));
1982
                pathItemsDT.Columns.Add("SubClass", typeof(string));
1983
                pathItemsDT.Columns.Add("TYPE", typeof(string));
1984
                pathItemsDT.Columns.Add("PIDNAME", typeof(string));
1985
                pathItemsDT.Columns.Add("Equipment_OID", typeof(string));
1986
                pathItemsDT.Columns.Add("NPD", typeof(string));
1987
                pathItemsDT.Columns.Add("GROUPTAG", typeof(string));
1988
                pathItemsDT.Columns.Add("PipeSystemNetwork_OID", typeof(string));
1989
                pathItemsDT.Columns.Add("ViewPipeSystemNetwork_OID", typeof(string));
1990
                pathItemsDT.Columns.Add("PipeRun_OID", typeof(string));
1991
                pathItemsDT.Columns.Add("EqpGroupTag", typeof(string));
1992
                pathItemsDT.Columns.Add("MainLineTag", typeof(string));
1993
                pathItemsDT.Columns.Add("EGTConnectedPoint", typeof(string));
1994
                pathItemsDT.Columns.Add("EGFlowDirection", typeof(string));
1995

    
1996
                DataTable sequenceDataDT = new DataTable();
1997
                sequenceDataDT.Columns.Add("OID", typeof(string));
1998
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
1999
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
2000
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
2001

    
2002
                DataTable pipeSystemNetworkDT = new DataTable();
2003
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
2004
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
2005
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
2006
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
2007
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
2008
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
2009
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
2010
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
2011
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
2012
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
2013
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
2014
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
2015
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
2016
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
2017
                pipeSystemNetworkDT.Columns.Add("Pocket", typeof(string));
2018
                pipeSystemNetworkDT.Columns.Add("EGTag", typeof(string));
2019
                pipeSystemNetworkDT.Columns.Add("HasMLTags", typeof(string));
2020
                pipeSystemNetworkDT.Columns.Add("AFC", typeof(string));
2021
                pipeSystemNetworkDT.Columns.Add("PUMP", typeof(string));
2022

    
2023
                DataTable topologySetDT = new DataTable();
2024
                topologySetDT.Columns.Add("OID", typeof(string));
2025
                topologySetDT.Columns.Add("Type", typeof(string));
2026
                topologySetDT.Columns.Add("SubType", typeof(string));
2027
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
2028
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
2029
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
2030
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
2031

    
2032
                DataTable pipelineDT = new DataTable();
2033
                pipelineDT.Columns.Add("OID", typeof(string));
2034
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
2035
                pipelineDT.Columns.Add("FLUID", typeof(string));
2036
                pipelineDT.Columns.Add("PMC", typeof(string));
2037
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
2038
                pipelineDT.Columns.Add("INSULATION", typeof(string));
2039
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
2040
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
2041
                pipelineDT.Columns.Add("Unit", typeof(string));
2042

    
2043
                DataTable pipesystemDT = new DataTable();
2044
                pipesystemDT.Columns.Add("OID", typeof(string));
2045
                pipesystemDT.Columns.Add("DESCRIPTION", typeof(string));
2046
                pipesystemDT.Columns.Add("FLUID", typeof(string));
2047
                pipesystemDT.Columns.Add("PMC", typeof(string));
2048
                pipesystemDT.Columns.Add("PipeLineQty", typeof(string));
2049
                pipesystemDT.Columns.Add("GroundLevel", typeof(string));
2050

    
2051
                // Set Vent/Drain Info
2052
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
2053
                DataTable dt = DB.SelectVentDrainSetting();
2054
                foreach (DataRow row in dt.Rows)
2055
                {
2056
                    string groupID = row["GROUP_ID"].ToString();
2057
                    string desc = row["DESCRIPTION"].ToString();
2058
                    int index = Convert.ToInt32(row["INDEX"]);
2059
                    string name = row["NAME"].ToString();
2060

    
2061
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
2062
                    if (ventDrainInfo == null)
2063
                    {
2064
                        ventDrainInfo = new VentDrainInfo(groupID);
2065
                        ventDrainInfo.Description = desc;
2066
                        VentDrainInfos.Add(ventDrainInfo);
2067
                    }
2068

    
2069
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
2070
                    {
2071
                        Index = index,
2072
                        Name = name
2073
                    });
2074
                }
2075
                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2076
                    ventDrainInfo.VentDrainItems = ventDrainInfo.VentDrainItems.OrderBy(x => x.Index).ToList();
2077

    
2078
                #region Keyword Info
2079
                KeywordInfo KeywordInfos = new KeywordInfo();
2080
                DataTable dtKeyword = DB.SelectKeywordsSetting();
2081
                foreach (DataRow row in dtKeyword.Rows)
2082
                {
2083
                    int index = Convert.ToInt32(row["INDEX"]);
2084
                    string name = row["NAME"].ToString();
2085
                    string keyword = row["KEYWORD"].ToString();
2086

    
2087
                    //KeywordInfo keywordInfo = new KeywordInfo();   
2088
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
2089
                    {
2090
                        Index = index,
2091
                        Name = name,
2092
                        Keyword = keyword
2093
                    });
2094
                }
2095
                #endregion
2096

    
2097
                #region ValveGrouping Info
2098
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
2099
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
2100
                foreach (DataRow row in dtValveGroupung.Rows)
2101
                {
2102
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
2103
                    {
2104
                        OID = row["OID"].ToString(),
2105
                        GroupType = row["GroupType"].ToString(),
2106
                        TagIdentifier = row["TagIdentifier"].ToString(),
2107
                        AttributeName = row["AttributeName"].ToString(),
2108
                        SppidSymbolName = row["SppidSymbolName"].ToString()
2109
                    });
2110
                }
2111
                #endregion
2112

    
2113
                #region EquipmentNoPocket Info
2114
                EquipmentNoPocketInfo EquipmentNoPocket = new EquipmentNoPocketInfo();
2115
                DataTable dtEquipmentNoPocket = DB.SelectEquipmentNoPocketSetting();
2116
                foreach (DataRow row in dtEquipmentNoPocket.Rows)
2117
                {
2118
                    EquipmentNoPocket.EquipmentNoPocketItem.Add(new EquipmentNoPocketItem()
2119
                    {
2120
                        Index = Convert.ToInt32(row["INDEX"]),
2121
                        Type = row["TYPE"].ToString(),
2122
                        Name = row["NAME"].ToString()
2123
                    });
2124
                }
2125
                #endregion
2126

    
2127
                #region EquipmentAirFinCooler Info
2128
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
2129
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
2130
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
2131
                {
2132
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
2133
                    {
2134
                        Type = row["Type"].ToString(),
2135
                        Name = row["Name"].ToString()
2136
                    });
2137
                }
2138
                #endregion
2139

    
2140
                // key = 미입력 branch
2141
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
2142
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
2143
                DataTable PSNFluidDT = DB.SelectPSNFluidCode();
2144
                DataTable PSNPMCDT = DB.SelectPSNPIPINGMATLCLASS();
2145
                foreach (PSNItem PSNItem in PSNItems)
2146
                {
2147
                    try
2148
                    {
2149
                        int psnOrder = 0;
2150
                        int index = 0;
2151
                        bool bPSNStart = true;
2152
                        string sPSNData = string.Empty;
2153
                        bool bVentDrain = false;
2154

    
2155
                        List<Group> Groups = PSNItem.Groups;
2156
                        Dictionary<string, List<Item>> keyValuePairs = new Dictionary<string, List<Item>>();
2157
                        List<Item> valveGroupingItem = new List<Item>();
2158

    
2159
                        //VentDrain 검사
2160
                        if (PSNItem.Groups.Count.Equals(1))
2161
                        {
2162
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
2163
                            for (int g = 0; g < Groups.Count; g++)
2164
                            {
2165
                                Group group = Groups[g];
2166
                                for (int i = 0; i < group.Items.Count; i++)
2167
                                {
2168
                                    Item item = group.Items[i];
2169
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2170
                                    {
2171
                                        if (endInfos.Contains(ventDrainInfo))
2172
                                            continue;
2173

    
2174
                                        if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
2175
                                        {
2176
                                            endInfos.Add(ventDrainInfo);
2177
                                            continue;
2178
                                        }
2179

    
2180
                                        if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
2181
                                        {
2182
                                            bVentDrain = true;
2183
                                            break;
2184
                                        }
2185
                                    }
2186

    
2187
                                    if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
2188
                                        break;
2189
                                }
2190

    
2191
                                if (!bVentDrain)
2192
                                {
2193
                                    endInfos = new List<VentDrainInfo>();
2194
                                    for (int i = 0; i < group.Items.Count; i++)
2195
                                    {
2196
                                        Item item = group.Items[group.Items.Count - i - 1];
2197
                                        foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2198
                                        {
2199
                                            if (endInfos.Contains(ventDrainInfo))
2200
                                                continue;
2201

    
2202
                                            if (!ventDrainInfo.VentDrainItems[i].Name.Equals(item.Name))
2203
                                            {
2204
                                                endInfos.Add(ventDrainInfo);
2205
                                                continue;
2206
                                            }
2207

    
2208
                                            if (ventDrainInfo.VentDrainItems.Count.Equals(i + 1))
2209
                                            {
2210
                                                bVentDrain = true;
2211
                                                break;
2212
                                            }
2213
                                        }
2214

    
2215
                                        if (bVentDrain || endInfos.Count.Equals(VentDrainInfos.Count))
2216
                                            break;
2217
                                    }
2218
                                }
2219
                            }
2220
                        }
2221

    
2222
                        try
2223
                        {
2224
                            foreach (Group group in PSNItem.Groups)
2225
                            {
2226
                                foreach (Item item in group.Items)
2227
                                {
2228
                                    string VgTag = string.Empty;
2229
                                    
2230
                                    if (ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).Count() > 0)
2231
                                    {
2232
                                        ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).First();
2233
                                        string value = string.Empty;
2234

    
2235
                                        if (valveitem.GroupType == "Scope Break" || valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
2236
                                            value = "NoSelection";
2237
                                        else
2238
                                        {
2239
                                            if(item.Attributes.Find(x => x.Name == valveitem.AttributeName) == null)
2240
                                                value = "NoSelection";
2241
                                            else
2242
                                                value = item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
2243
                                        }
2244

    
2245
                                        if (valveitem.GroupType == "Scope Break")
2246
                                            VgTag = "Scope Break";
2247
                                        else
2248
                                            VgTag = valveitem.SppidSymbolName + "\\" + value;
2249

    
2250
                                    }
2251

    
2252
                                    string PathitemUID = string.Empty;
2253
                                    if (item.BranchItems.Count == 0)
2254
                                    {
2255
                                        PathitemUID = item.UID;
2256
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2257
                                        CreateSequenceDataDataRow(PathitemUID);
2258
                                        index++;
2259
                                    }
2260
                                    else
2261
                                    {
2262
                                        PathitemUID = item.UID + "_L1";
2263
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2264
                                        CreateSequenceDataDataRow(PathitemUID);
2265
                                        index++;
2266
                                        for (int i = 0; i < item.BranchItems.Count; i++)
2267
                                        {
2268
                                            CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", string.Empty, item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
2269
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
2270
                                            index++;
2271

    
2272
                                            CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
2273
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
2274
                                            index++;
2275

    
2276
                                            if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
2277
                                                startBranchDic.Add(item.BranchItems[i], item);
2278
                                            else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
2279
                                                endBranchDic.Add(item.BranchItems[i], item);
2280
                                        }
2281
                                    }
2282

    
2283
                                    if (bPSNStart)
2284
                                    {
2285
                                        CreatePipeSystemNetworkDataRow();
2286
                                        sPSNData = item.TopologyData;
2287
                                        psnOrder++;
2288
                                        bPSNStart = false;
2289
                                    }
2290
                                    else
2291
                                    {
2292
                                        if (item.TopologyData != sPSNData)
2293
                                        {
2294
                                            CreatePipeSystemNetworkDataRow();
2295
                                            sPSNData = item.TopologyData;
2296
                                            psnOrder++;
2297
                                        }
2298
                                    }
2299

    
2300
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string GROUPTAG = "", string branchTopologyName = "", Item branchItem = null)
2301
                                    {
2302
                                        DataRow newRow = pathItemsDT.NewRow();
2303

    
2304
                                        if (itemType == "Nozzles")
2305
                                        {
2306
                                            newRow["Equipment_OID"] = item.Equipment != null ? item.Equipment.UID : "";
2307
                                        }
2308

    
2309
                                        newRow["OID"] = itemOID;
2310
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2311
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
2312
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
2313
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
2314
                                        newRow["ITEMNAME"] = GetItemName(item, itemOID);
2315
                                        newRow["ITEMTAG"] = GetItemTag(item);
2316
                                        newRow["Class"] = GetClass(item, itemOID);
2317
                                        string subClass = GetSubClass(item, itemOID);
2318
                                        newRow["SubClass"] = subClass;
2319

    
2320
                                        if (item.ItemType == ItemType.Symbol)
2321
                                            newRow["TYPE"] = item.ID2DBName;
2322
                                        else if (item.ItemType == ItemType.Line)
2323
                                            newRow["TYPE"] = item.ID2DBType;
2324
                                        newRow["PIDNAME"] = group.Document.DrawingName;
2325

    
2326
                                        // NPD
2327
                                        if (item.LineNumber != null)
2328
                                        {
2329
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
2330
                                            if (attribute != null)
2331
                                                newRow["NPD"] = attribute.Value;
2332
                                        }
2333
                                        else
2334
                                            newRow["NPD"] = null;
2335

    
2336
                                        newRow["GROUPTAG"] = GROUPTAG;
2337
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2338
                                        if (branchItem == null)
2339
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2340
                                        else
2341
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
2342

    
2343
                                        newRow["PipeRun_OID"] = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
2344
                                        newRow["EGTConnectedPoint"] = 0;
2345
                                        pathItemsDT.Rows.Add(newRow);
2346
                                    }
2347

    
2348

    
2349
                                    void CreateSequenceDataDataRow(string itemOID)
2350
                                    {
2351
                                        DataRow newRow = sequenceDataDT.NewRow();
2352
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2353
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
2354
                                        newRow["PathItem_OID"] = itemOID;
2355
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2356

    
2357
                                        sequenceDataDT.Rows.Add(newRow);
2358
                                    }
2359

    
2360
                                    void CreatePipeSystemNetworkDataRow()
2361
                                    {
2362
                                        LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
2363
                                        string FluidCode = string.Empty;
2364
                                        if (lineNumber != null)
2365
                                        {
2366
                                            List<Attribute> att = lineNumber.Attributes;
2367
                                            if (att != null)
2368
                                            {
2369
                                                List<string> oid = new List<string>();
2370
                                                FluidCode = att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault() != null ? att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault().Value : string.Empty;
2371
                                                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;
2372
                                                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;
2373
                                                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;
2374
                                                //InsulationPurpose
2375
                                                if (!string.IsNullOrEmpty(FluidCode)) oid.Add(FluidCode);
2376
                                                if (!string.IsNullOrEmpty(PMC)) oid.Add(PMC);
2377

    
2378
                                                string PipeSystem_OID = string.Join("-", oid);
2379

    
2380
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
2381
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
2382

    
2383
                                                string OID = string.Join("-", oid);
2384
                                                string FluidCodeGL = string.Empty;
2385
                                                string PMCGL = string.Empty;
2386

    
2387

    
2388
                                                if (pipelineDT.Select(string.Format("OID = '{0}'", OID)).Count() == 0)
2389
                                                {
2390
                                                    DataRow newPipelineRow = pipelineDT.NewRow();
2391
                                                    newPipelineRow["OID"] = OID;
2392
                                                    newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
2393
                                                    newPipelineRow["FLUID"] = FluidCode;
2394
                                                    newPipelineRow["PMC"] = PMC;
2395
                                                    newPipelineRow["SEQNUMBER"] = SEQNUMBER;
2396
                                                    newPipelineRow["INSULATION"] = INSULATION;
2397
                                                    newPipelineRow["FROM_DATA"] = string.Empty;
2398
                                                    newPipelineRow["TO_DATA"] = string.Empty;
2399
                                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
2400
                                                    pipelineDT.Rows.Add(newPipelineRow);
2401
                                                }
2402

    
2403
                                                if (pipesystemDT.Select(string.Format("OID = '{0}'", PipeSystem_OID)).Count() == 0)
2404
                                                {
2405
                                                    DataRow newPipesystemRow = pipesystemDT.NewRow();
2406
                                                    newPipesystemRow["OID"] = PipeSystem_OID;
2407
                                                    newPipesystemRow["DESCRIPTION"] = string.Empty;
2408
                                                    newPipesystemRow["FLUID"] = FluidCode;
2409
                                                    newPipesystemRow["PMC"] = PMC;
2410
                                                    newPipesystemRow["PipeLineQty"] = string.Empty;
2411
                                                    string GroundLevel = string.Empty;
2412
                                                    if (!string.IsNullOrEmpty(FluidCode) && !string.IsNullOrEmpty(PMC))
2413
                                                    {
2414
                                                        FluidCodeGL = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("GroundLevel");
2415
                                                        PMCGL = PSNPMCDT.Select(string.Format("Code= '{0}'", PMC)).FirstOrDefault().Field<string>("GroundLevel");
2416
                                                        if (FluidCodeGL == "AG" && PMCGL == "AG")
2417
                                                            GroundLevel = "AG";
2418
                                                        else if (FluidCodeGL == "UG" && PMCGL == "UG")
2419
                                                            GroundLevel = "UG";
2420
                                                        else
2421
                                                            GroundLevel = "AG_UG";
2422
                                                    }
2423
                                                    newPipesystemRow["GroundLevel"] = GroundLevel;
2424

    
2425
                                                    pipesystemDT.Rows.Add(newPipesystemRow);
2426
                                                }
2427
                                            }
2428
                                        }
2429

    
2430
                                        DataRow newRow = pipeSystemNetworkDT.NewRow();
2431
                                        newRow["OID"] = PSNItem.PSN_OID();
2432

    
2433
                                        newRow["OrderNumber"] = psnOrder;
2434
                                        newRow["Pipeline_OID"] = item.PSNPipeLineID;
2435
                                        PSNItem.KeywordInfos = KeywordInfos;
2436
                                        PSNItem.Nozzle = Nozzle;
2437

    
2438
                                        string FromType = string.Empty;
2439
                                        Item From_item = new Item();
2440

    
2441
                                        string FROM_DATA = PSNItem.GetFromData(ref FromType, ref From_item);
2442
                                        string status = string.Empty;
2443
                                        if (psnOrder == 0)
2444
                                        {
2445
                                            status = PSNItem.Status;
2446
                                        }
2447

    
2448
                                        if (PSNItem.IsKeyword)
2449
                                        {
2450
                                            PSNItem.StartType = PSNType.Equipment;
2451
                                        }
2452
                                        string ToType = string.Empty;
2453
                                        Item To_item = new Item();
2454
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item);
2455
                                        if (PSNItem.IsKeyword)
2456
                                        {
2457
                                            PSNItem.EndType = PSNType.Equipment;
2458
                                        }
2459

    
2460
                                        //if (Groups.Count == psnOrder + 1 && !string.IsNullOrEmpty(PSNItem.Status))
2461
                                        //{
2462
                                        if (!string.IsNullOrEmpty(PSNItem.Status))
2463
                                            status += PSNItem.Status;
2464
                                        //}
2465

    
2466
                                        newRow["FROM_DATA"] = FROM_DATA;
2467
                                        newRow["TO_DATA"] = TO_DATA;
2468
                                        //if(TO_DATA.Contains("Free Vent W-Screen") || TO_DATA.Contains("Empty LineNumber") || FROM_DATA.Contains("Empty LineNumber"))
2469
                                        //{
2470

    
2471
                                        //}
2472
                                        newRow["Type"] = PSNItem.GetPSNType();
2473

    
2474
                                        if (psnOrder > 0)
2475
                                        {
2476
                                            DataRow dr = pipeSystemNetworkDT.Select(string.Format("OID = '{0}' AND OrderNumber = {1}", PSNItem.PSN_OID(), psnOrder - 1)).FirstOrDefault();
2477
                                            if (!string.IsNullOrEmpty(PSNItem.Status))
2478
                                            {//status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2479
                                                if (dr["Status"].ToString().Contains(PSNItem.Status))
2480
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status, string.Empty);
2481
                                                else if (dr["Status"].ToString().Contains(PSNItem.Status.Remove(0, 2)))
2482
                                                    dr["Status"] = dr["Status"].ToString().Replace(PSNItem.Status.Remove(0, 2), string.Empty);
2483

    
2484
                                            }
2485

    
2486
                                            if (dr != null)
2487
                                            {
2488
                                                newRow["FROM_DATA"] = dr.Field<string>("FROM_DATA");
2489
                                                newRow["TO_DATA"] = dr.Field<string>("TO_DATA");
2490
                                                newRow["Type"] = dr.Field<string>("Type");
2491
                                            }
2492
                                        }
2493

    
2494
                                        status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2495
                                        if (group.Items.Count == 1 && !string.IsNullOrEmpty(status))
2496
                                        {
2497
                                            MatchCollection matches = Regex.Matches(status, "Missing LineNumber_1");
2498
                                            int cnt = matches.Count;
2499
                                            if (cnt > 1)
2500
                                                status.Replace(", Missing LineNumber_1", string.Empty);
2501
                                        }
2502
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2503
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
2504

    
2505

    
2506
                                        newRow["IsValid"] = PSNItem.IsValid;
2507
                                        newRow["Status"] = status;
2508
                                        newRow["PBS"] = PSNItem.GetPBSData();
2509

    
2510
                                        List<string> drawingNames = new List<string>();
2511
                                        foreach (Group _group in PSNItem.Groups)
2512
                                        {
2513
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
2514
                                            {
2515
                                                if (drawingNames.Count == 0)
2516
                                                    newRow["Drawings"] = _group.Document.DrawingName;
2517
                                                else
2518
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
2519
                                                drawingNames.Add(_group.Document.DrawingName);
2520
                                            }
2521
                                        }
2522

    
2523
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
2524
                                        if (bVentDrain)
2525
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
2526
                                        else
2527
                                            newRow["IncludingVirtualData"] = "No";
2528
                                        //    return;
2529
                                        //newRow["IncludingVirtualData"] = "No";
2530
                                        newRow["PSNAccuracy"] = "100";
2531

    
2532
                                        string Pocket = "No";
2533
                                        string Condition = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("Condition");
2534
                                        if (Condition.Equals("Flare"))
2535
                                            Pocket = "Yes";
2536

    
2537
                                        if (item.ID2DBType == "Nozzles" && PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null) 
2538
                                        {
2539
                                          //  string itemName = From_item.Name;
2540
                                            Equipment Equipment = From_item.Equipment;
2541
                                      
2542
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name && x.Type != "Pump").FirstOrDefault();
2543
                                          
2544

    
2545
                                            if (nopocket != null)
2546
                                            {
2547
                                                DataRow bNozzle = null;
2548
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2549
                                                {
2550
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, From_item.UID)).FirstOrDefault();
2551
                                                    if (drNozzle != null)
2552
                                                    {
2553
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2554
                                                        {
2555
                                                            bNozzle = drNozzle;
2556
                                                        }
2557

    
2558
                                                        if (bNozzle == null)
2559
                                                        {
2560
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2561

    
2562
                                                            if (drNozzle != null)
2563
                                                            {
2564
                                                                bNozzle = drNozzle;
2565
                                                                foreach (DataRow it in nozzleRows)
2566
                                                                {
2567
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2568
                                                                    {
2569
                                                                        bNozzle = null;
2570
                                                                        break;
2571
                                                                    }
2572
                                                                }
2573
                                                            }
2574
                                                        }
2575
                                                    }
2576

    
2577
                                                    if (bNozzle != null)
2578
                                                        Pocket = "Yes";
2579
                                                }
2580
                                                else
2581
                                                    Pocket = "Yes";
2582
                                            }
2583
                                        }
2584
                                        
2585
                                        if (item.ID2DBType == "Nozzles" && PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null) //To는 전체
2586
                                        {
2587
                                           // string itemName = To_item.Name;
2588
                                            Equipment Equipment = To_item.Equipment;
2589
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name).FirstOrDefault();
2590
                                            if (nopocket != null)
2591
                                            {
2592
                                                DataRow bNozzle = null;
2593
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2594
                                                {
2595
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, To_item.UID)).FirstOrDefault();
2596
                                                    if(drNozzle != null)
2597
                                                    {
2598
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2599
                                                        {
2600
                                                            bNozzle = drNozzle;
2601
                                                        }
2602

    
2603
                                                        if (bNozzle == null)
2604
                                                        {
2605
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2606

    
2607
                                                            if (drNozzle != null)
2608
                                                            {
2609
                                                                bNozzle = drNozzle;
2610
                                                                foreach (DataRow it in nozzleRows)
2611
                                                                {
2612
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2613
                                                                    {
2614
                                                                        bNozzle = null;
2615
                                                                        break;
2616
                                                                    }
2617
                                                                }
2618
                                                            }
2619
                                                        }
2620
                                                    }                                                   
2621

    
2622
                                                    if (bNozzle != null)
2623
                                                        Pocket = "Yes";
2624
                                                }
2625
                                                else
2626
                                                    Pocket = "Yes";
2627
                                            }
2628
                                        }
2629
                                        
2630
                                        newRow["Pocket"] = Pocket;
2631
                                        string AFC = "P2";
2632
                                        if(PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null)
2633
                                        {
2634
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2635
                                                AFC = "P1\\" + From_item.Equipment.Name;
2636
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2637
                                                newRow["PUMP"] = "PUMP";
2638
                                        }
2639

    
2640
                                        if (PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null)
2641
                                        {
2642
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2643
                                                AFC = "P1\\" + To_item.Equipment.Name;
2644
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2645
                                                newRow["PUMP"] = "PUMP";
2646
                                        }
2647

    
2648
                                        newRow["AFC"] = AFC;
2649

    
2650
                                        newRow["EGTag"] = string.Empty;
2651
                                        newRow["HasMLTags"] = "False";
2652
                                        pipeSystemNetworkDT.Rows.Add(newRow);
2653
                                    }
2654
                                }
2655

    
2656
                            }
2657
                        
2658

    
2659
                        }
2660
                        catch (Exception ex)
2661
                        {
2662
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2663
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2664
                        }
2665

    
2666
                        //TopologySet 관련
2667
                        foreach (Topology topology in PSNItem.Topologies)
2668
                        {
2669
                            DataRow newRow = topologySetDT.NewRow();
2670
                            newRow["OID"] = topology.FullName;
2671
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
2672
                            if (bVentDrain)
2673
                                newRow["SubType"] = "Vent_Drain";
2674
                            else
2675
                                newRow["SubType"] = null;
2676
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
2677
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
2678
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
2679
                            newRow["TailItemSPID"] = topology.Items.First().UID;
2680
                            topologySetDT.Rows.Add(newRow);
2681
                        }
2682

    
2683
                    }
2684
                    catch (Exception ee)
2685
                    {
2686

    
2687
                    }
2688
                }
2689

    
2690

    
2691
                foreach (var item in startBranchDic)
2692
                {
2693
                    string uid = item.Key.UID;
2694
                    string topologyName = item.Value.Topology.FullName;
2695
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2696

    
2697
                    if (rows.Length == 1)
2698
                    {
2699
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2700
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2701
                    }
2702
                    else if (rows.Length > 1)
2703
                    {
2704
                        DataRow targetRow = null;
2705
                        int index = int.MaxValue;
2706
                        foreach (DataRow row in rows)
2707
                        {
2708
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2709
                            if (split.StartsWith("L"))
2710
                            {
2711
                                int num = Convert.ToInt32(split.Remove(0, 1));
2712
                                if (index > num)
2713
                                {
2714
                                    index = num;
2715
                                    targetRow = row;
2716
                                }
2717
                            }
2718
                        }
2719

    
2720
                        if (targetRow != null)
2721
                        {
2722
                            targetRow["BranchTopologySet_OID"] = topologyName;
2723
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2724
                        }
2725
                    }
2726
                }
2727

    
2728
                foreach (var item in endBranchDic)
2729
                {
2730
                    string uid = item.Key.UID;
2731
                    string topologyName = item.Value.Topology.FullName;
2732
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2733
                    if (rows.Length == 1)
2734
                    {
2735
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2736
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2737
                    }
2738
                    else if (rows.Length > 1)
2739
                    {
2740
                        DataRow targetRow = null;
2741
                        int index = int.MinValue;
2742
                        foreach (DataRow row in rows)
2743
                        {
2744
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2745
                            if (split.StartsWith("L"))
2746
                            {
2747
                                int num = Convert.ToInt32(split.Remove(0, 1));
2748
                                if (index < num)
2749
                                {
2750
                                    index = num;
2751
                                    targetRow = row;
2752
                                }
2753
                            }
2754
                        }
2755

    
2756
                        if (targetRow != null)
2757
                        {
2758
                            targetRow["BranchTopologySet_OID"] = topologyName;
2759
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2760
                        }
2761
                    }
2762
                }
2763

    
2764
                PathItems = pathItemsDT;
2765
                SequenceData = sequenceDataDT;
2766
                PipeSystemNetwork = pipeSystemNetworkDT;
2767
                TopologySet = topologySetDT;
2768
                PipeLine = pipelineDT;
2769
                PipeSystem = pipesystemDT;
2770
            }
2771
            catch (Exception ex)
2772
            {
2773
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2774
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2775
            }
2776
        }
2777

    
2778
        private double AccuracyCalculation(List<double> lstAcc, double acc)
2779
        {
2780
            foreach (double lacc in lstAcc)
2781
            {
2782
                acc *= lacc;
2783
            }
2784
            return acc;
2785
        }
2786

    
2787
        private void UpdateSubType()
2788
        {
2789
            try
2790
            {
2791
                foreach (PSNItem PSNItem in PSNItems)
2792
                {
2793
                    if (PSNItem.IsBypass)
2794
                    {
2795
                        foreach (Topology topology in PSNItem.Topologies)
2796
                        {
2797
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2798
                            if (rows.Length.Equals(1))
2799
                                rows.First()["SubType"] = "Bypass";
2800
                        }
2801
                    }
2802

    
2803
                    if (PSNItem.StartType == PSNType.Header)
2804
                    {
2805
                        Topology topology = PSNItem.Topologies.First();
2806
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2807
                        if (rows.Length.Equals(1))
2808
                            rows.First()["SubType"] = "Header";
2809
                    }
2810
                    else if (PSNItem.EndType == PSNType.Header)
2811
                    {
2812
                        Topology topology = PSNItem.Topologies.Last();
2813
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2814
                        if (rows.Length.Equals(1))
2815
                            rows.First()["SubType"] = "Header";
2816
                    }
2817
                }
2818

    
2819

    
2820
                foreach (Topology topology in Topologies)
2821
                {
2822
                    try
2823
                    {
2824
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2825

    
2826
                        if (rows.Count() > 0)
2827
                        {
2828
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
2829
                            {
2830
                                if (topology.Items == null)
2831
                                    continue;
2832

    
2833
                                Item firstItem = topology.Items.First();
2834
                                Item lastItem = topology.Items.Last();
2835

    
2836
                                List<Relation> relations = new List<Relation>();
2837

    
2838
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2839
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2840

    
2841
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2842
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2843

    
2844
                                if (relations.Count > 0)
2845
                                    rows.First()["SubType"] = "OtherSystem";
2846
                            }
2847
                        }
2848
                    }
2849
                    catch (Exception ex)
2850
                    {
2851

    
2852
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2853
                    }
2854
                }
2855

    
2856
                foreach (DataRow row in TopologySet.Rows)
2857
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
2858
                        row["SubType"] = "Normal";
2859
            }
2860
            catch (Exception ex)
2861
            {
2862
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2863
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2864
            }
2865
        }
2866

    
2867
        private bool IsBypass(PSNItem PSNItem)
2868
        {
2869
            bool bResult = false;
2870

    
2871
            if (PSNItem.GetPSNType() == "B2B")
2872
            {
2873
                Group firstGroup = PSNItem.Groups.First();
2874
                Group lastGroup = PSNItem.Groups.Last();
2875
                Item firstItem = firstGroup.Items.First();
2876
                Item lastItem = lastGroup.Items.Last();
2877

    
2878
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
2879
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
2880

    
2881
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
2882
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
2883
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
2884
                    bResult = true;
2885
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
2886
                    bResult = true;
2887
            }
2888

    
2889
            Item GetConnectedItemByPSN(Item item)
2890
            {
2891
                Item result = null;
2892

    
2893
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
2894
                if (relation != null)
2895
                    result = relation.Item;
2896

    
2897

    
2898
                return result;
2899
            }
2900

    
2901
            return bResult;
2902
        }
2903

    
2904
        private void DeleteVentDrain()
2905
        {
2906
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
2907

    
2908
            foreach (DataRow dataRow in ventdrainRows)
2909
            {
2910
                dataRow.Delete();
2911
            }
2912
        }
2913

    
2914
        private void UpdateAccuracy()
2915
        {
2916
            //DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
2917
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'");
2918
            List<double> lstAcc = null;
2919
            string Status = string.Empty;
2920

    
2921
            foreach (DataRow dataRow in statusRows)
2922
            {
2923
                lstAcc = new List<double>();
2924
                Status = dataRow.Field<string>("Status");
2925
                if (!string.IsNullOrEmpty(Status))
2926
                {
2927
                    string[] arrStatus = Status.Split(',');
2928
                    foreach (string arrstr in arrStatus)
2929
                    {
2930
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
2931
                            lstAcc.Add(0.75);
2932

    
2933
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
2934
                            lstAcc.Add(0.7);
2935

    
2936
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
2937
                            lstAcc.Add(0.5);
2938

    
2939
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
2940
                            lstAcc.Add(0.65);
2941

    
2942
                        if (arrstr.Contains(Rule5)) //Line Disconnected
2943
                            lstAcc.Add(0.6);
2944
                    }
2945
                }
2946

    
2947
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
2948
                if (PSNAccuracy == "100")
2949
                    PSNAccuracy = "1";
2950

    
2951
                PSNAccuracy = Convert.ToString(Convert.ToDecimal(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))));
2952
                //if (PSNAccuracy != "100")
2953
                //{
2954
                //    //dataRow["IncludingVirtualData"] = "No";
2955
                dataRow["PSNAccuracy"] = PSNAccuracy;
2956
                //}
2957
            }
2958
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
2959
            foreach (DataRow dr in dt.Rows)
2960
            {
2961
                string oid = dr.Field<string>("OID");
2962
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
2963
                double totalDdr = 0;
2964
                foreach (DataRow ddr in select)
2965
                {
2966
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
2967
                    if (acc == 100) acc = 1;
2968
                    if (totalDdr == 0) totalDdr = acc;
2969
                    else totalDdr *= acc;
2970
                }
2971

    
2972
                totalDdr *= 100;
2973

    
2974
                if (totalDdr != 100)
2975
                {
2976
                    foreach (DataRow ddr in select)
2977
                    {
2978
                        ddr["IncludingVirtualData"] = "Yes";
2979
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2980
                    }
2981
                }
2982
                else
2983
                {
2984
                    foreach (DataRow ddr in select)
2985
                    {
2986
                        ddr["IncludingVirtualData"] = "No";
2987
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
2988
                    }
2989
                }
2990
            }
2991

    
2992
        }
2993

    
2994
        private void UpdateKeywordForPSN()
2995
        {
2996
            #region Keyword Info
2997
            KeywordInfo KeywordInfos = new KeywordInfo();
2998
            DataTable dtKeyword = DB.SelectKeywordsSetting();
2999
            foreach (DataRow row in dtKeyword.Rows)
3000
            {
3001
                int index = Convert.ToInt32(row["INDEX"]);
3002
                string name = row["NAME"].ToString();
3003
                string keyword = row["KEYWORD"].ToString();
3004

    
3005
                //KeywordInfo keywordInfo = new KeywordInfo();   
3006
                KeywordInfos.KeywordItems.Add(new KeywordItem()
3007
                {
3008
                    Index = index,
3009
                    Name = name,
3010
                    Keyword = keyword
3011
                });
3012
            }
3013
            #endregion
3014

    
3015
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
3016
            foreach (DataRow dataRow in endofHeaderRows)
3017
            {
3018
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3019

    
3020
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
3021
                {
3022
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3023
                    DataRow dr = pathItemRows.First();
3024
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
3025
                    dr["TYPE"] = "End";
3026
                    dr["ITEMTAG"] = "ENDOFHEADER";
3027
                    dr["DESCRIPTION"] = "ENDOFHEADER";
3028
                }
3029

    
3030
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
3031
                {
3032
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3033
                    DataRow dr = pathItemRows.Last();
3034
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
3035
                    dr["TYPE"] = "End";
3036
                    dr["ITEMTAG"] = "ENDOFHEADER";
3037
                    dr["DESCRIPTION"] = "ENDOFHEADER";
3038
                }
3039
            }
3040

    
3041
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3042
            {
3043
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
3044
                foreach (DataRow dataRow in keywordRows)
3045
                {
3046
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3047

    
3048
                    if (dataRow.Field<string>("From_Data") == keyitem.Keyword)
3049
                    {
3050
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3051

    
3052
                        //
3053
                        //if(.)
3054
                        if (PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
3055
                        {
3056
                            DataRow dr = pathItemRows.First();
3057
                            //dr["CLASS"] = ""; //Type
3058
                            dr["TYPE"] = "End";
3059
                            dr["ITEMTAG"] = keyitem.Keyword;
3060
                            dr["DESCRIPTION"] = keyitem.Keyword;
3061
                        }
3062

    
3063
                    }
3064

    
3065
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
3066
                    {
3067
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3068

    
3069
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
3070
                        {
3071
                            DataRow dr = pathItemRows.Last();
3072
                            //dr["CLASS"] = ""; //Type
3073
                            dr["TYPE"] = "End";
3074
                            dr["ITEMTAG"] = keyitem.Keyword;
3075
                            dr["DESCRIPTION"] = keyitem.Keyword;
3076
                            //dr.Field<string>("Type")
3077
                        }
3078

    
3079
                    }
3080
                }
3081
            }
3082
        }
3083

    
3084
        private void UpdateErrorForPSN()
3085
        {
3086
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
3087
            foreach (DataRow dataRow in errorRows)
3088
            {
3089
                try
3090
                {
3091
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3092
                   
3093
                    bool change = false;
3094
                    bool bCheck = false;
3095
                    if (!PSNItem.EnableType(PSNItem.StartType))
3096
                    {
3097
                        change = true;
3098
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3099
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3100

    
3101
                        Item item = PSNItem.Groups.First().Items.First();
3102
                        try
3103
                        {
3104
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
3105

    
3106
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3107
                            {
3108
                                loopRow["FROM_DATA"] = FROM_DATA;
3109
                                if (item.ItemType == ItemType.Line)
3110
                                {
3111
                                    if (loopRow.Field<string>("OrderNumber") == "0")
3112
                                    {
3113
                                        string status = loopRow.Field<string>("Status");
3114
                                        //string isvali
3115
                                        if (string.IsNullOrEmpty(status))
3116
                                            status = "Line Disconnected";
3117
                                        else if (!status.Contains("Line Disconnected"))
3118
                                            status += ", Line Disconnected";
3119
                                        loopRow["Status"] = status;
3120
                                        if (!string.IsNullOrEmpty(status))
3121
                                            loopRow["IsValid"] = "Error";
3122
                                    }
3123
                                }
3124
                            }
3125

    
3126
                            tieInPointIndex++;
3127

    
3128
                            if (item.ItemType == ItemType.Line)
3129
                            {
3130
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);                                
3131
                            }
3132
                            else
3133
                            {
3134
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
3135
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
3136

    
3137
                                bCheck = true;
3138
                            }
3139

    
3140
                            PSNItem.StartType = PSNType.Equipment;
3141
                        }
3142
                        catch (Exception ex)
3143
                        {
3144
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3145
                            return;
3146
                        }
3147
                    }
3148

    
3149
                    if (!PSNItem.EnableType(PSNItem.EndType))
3150
                    {                        
3151
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3152
                        //int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
3153
                        DataRow dr = pathItemRows.Last();
3154
                        if (change)
3155
                        {
3156
                            if(bCheck)
3157
                                dr = pathItemRows[pathItemRows.Count() - 3];
3158
                            else
3159
                            {
3160
                                dr = pathItemRows[pathItemRows.Count() - 2];
3161
                            }
3162
                        }
3163

    
3164
                        change = true;
3165
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3166

    
3167
                        Item item = PSNItem.Groups.Last().Items.Last();
3168
                        try
3169
                        {
3170
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
3171

    
3172
                           
3173
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3174
                            {
3175
                                loopRow["TO_DATA"] = TO_DATA;
3176
                                if (item.ItemType == ItemType.Line)
3177
                                {
3178
                                    if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
3179
                                    {
3180
                                        string status = loopRow.Field<string>("Status");
3181
                                        if (string.IsNullOrEmpty(status))
3182
                                            status = "Line Disconnected";
3183
                                        else if (!status.Contains("Line Disconnected"))
3184
                                            status += ", Line Disconnected";
3185
                                        loopRow["Status"] = status;
3186
                                        if (!string.IsNullOrEmpty(status))
3187
                                            loopRow["IsValid"] = "Error";
3188
                                    }
3189
                                }
3190
                            }                            
3191

    
3192
                            tieInPointIndex++;
3193

    
3194
                            if (item.ItemType == ItemType.Line)
3195
                            {
3196
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3197
                            }
3198
                            else
3199
                            {
3200
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3201
                                if(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Count() > 0)
3202
                                    PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last()), insertIndex);
3203
                               
3204
                            }
3205

    
3206
                            PSNItem.EndType = PSNType.Equipment;
3207
                        }
3208
                        catch (Exception ex)
3209
                        {
3210
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3211
                            return;
3212
                        }
3213
                    }
3214

    
3215
                    dataRow["Type"] = PSNItem.GetPSNType();
3216
                    if (change)
3217
                    {
3218
                        int rowIndex = 0;
3219
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3220
                        {
3221
                            DataRow row = PathItems.Rows[i];
3222
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
3223
                                continue;
3224
                            string sequenceData = row["SequenceData_OID"].ToString();
3225
                            string[] split = sequenceData.Split(new char[] { '_' });
3226

    
3227
                            StringBuilder sb = new StringBuilder();
3228
                            for (int j = 0; j < split.Length - 1; j++)
3229
                                sb.Append(split[j] + "_");
3230
                            sb.Append(rowIndex++);
3231
                            row["SequenceData_OID"] = sb.ToString();
3232

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

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

    
3238
                            if (seqItemRows == null)
3239
                            {
3240
                                DataRow newRow = SequenceData.NewRow();
3241
                                newRow["OID"] = sb.ToString();
3242
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3243
                                newRow["PathItem_OID"] = row["OID"];
3244
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3245
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3246
                            }
3247
                            else
3248
                            {
3249
                                seqItemRows["OID"] = sb.ToString();
3250
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3251
                                seqItemRows["PathItem_OID"] = row["OID"];
3252
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3253
                            }
3254
                        }
3255
                    }
3256

    
3257
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
3258
                    {
3259
                        DataRow newRow = PathItems.NewRow();
3260
                        newRow["OID"] = Guid.NewGuid().ToString();
3261
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3262
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3263
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3264
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3265
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
3266
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
3267
                        newRow["DESCRIPTION"] = DATA;
3268
                        newRow["Class"] = "End of line terminator";
3269
                        newRow["SubClass"] = "End of line terminator";
3270
                        newRow["TYPE"] = "End";
3271
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3272
                        newRow["NPD"] = itemRow["NPD"];
3273
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3274
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3275
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3276
                        newRow["EGTConnectedPoint"] = "0";
3277
                        return newRow;
3278
                    }
3279

    
3280
                    DataRow createLineRow(DataRow itemRow)
3281
                    {
3282
                        DataRow newRow = PathItems.NewRow();
3283
                        newRow["OID"] = Guid.NewGuid().ToString();
3284
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3285
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3286
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3287
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3288
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
3289
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3290
                        newRow["Class"] = itemRow["Class"];
3291
                        newRow["SubClass"] = itemRow["SubClass"];
3292
                        newRow["TYPE"] = itemRow["TYPE"];
3293
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3294
                        newRow["NPD"] = itemRow["NPD"];
3295
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3296
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3297
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3298
                        newRow["EGTConnectedPoint"] = "0";
3299
                        return newRow;
3300
                    }
3301
                }
3302
                catch (Exception ex)
3303
                {
3304

    
3305
                }
3306
            }
3307
        }
3308

    
3309
        private void InsertTeePSN()
3310
        {
3311
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
3312
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
3313
            bool change = false;
3314
            foreach (DataRow dataRow in branchRows)
3315
            {
3316
                try
3317
                {
3318
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3319
                    change = false;
3320

    
3321
                    if (PSNItem.StartType == PSNType.Branch)
3322
                    {
3323
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3324
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3325
                        Item Teeitem = PSNItem.Groups.First().Items.First();
3326
                        try
3327
                        {
3328
                            if (Teeitem.ItemType == ItemType.Line)
3329
                            {
3330
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
3331
                                {
3332
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
3333
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
3334
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3335
                                    change = true;
3336
                                }
3337

    
3338
                            }
3339
                        }
3340
                        catch (Exception ex)
3341
                        {
3342
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3343
                            return;
3344
                        }
3345
                    }
3346

    
3347
                    if (PSNItem.EndType == PSNType.Branch)
3348
                    {
3349
                        //change = true;
3350
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3351

    
3352
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
3353

    
3354
                        DataRow dr = pathItemRows.Last();
3355
                        if (change)
3356
                            dr = pathItemRows[pathItemRows.Count() - 2];
3357

    
3358
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3359

    
3360
                        try
3361
                        {
3362
                            if (Teeitem.ItemType == ItemType.Line)
3363
                            {
3364
                                if (dr.Field<string>("SubClass") != "Tee")
3365
                                {
3366
                                    PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
3367
                                    change = true;
3368
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
3369
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3370
                                }
3371

    
3372
                            }
3373
                        }
3374
                        catch (Exception ex)
3375
                        {
3376
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3377
                            return;
3378
                        }
3379
                    }
3380

    
3381
                    if (change)
3382
                    {
3383
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3384
                        int rowIndex = 0;
3385
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3386
                        {
3387
                            DataRow row = PathItems.Rows[i];
3388
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
3389
                                continue;
3390
                            string sequenceData = row["SequenceData_OID"].ToString();
3391
                            string[] split = sequenceData.Split(new char[] { '_' });
3392

    
3393
                            StringBuilder sb = new StringBuilder();
3394
                            for (int j = 0; j < split.Length - 1; j++)
3395
                                sb.Append(split[j] + "_");
3396
                            sb.Append(rowIndex++);
3397
                            row["SequenceData_OID"] = sb.ToString();
3398

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

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

    
3404
                            if (seqItemRows == null)
3405
                            {
3406
                                DataRow newRow = SequenceData.NewRow();
3407
                                newRow["OID"] = sb.ToString();
3408
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3409
                                newRow["PathItem_OID"] = row["OID"];
3410
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3411
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3412
                            }
3413
                            else
3414
                            {
3415
                                seqItemRows["OID"] = sb.ToString();
3416
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3417
                                seqItemRows["PathItem_OID"] = row["OID"];
3418
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3419
                            }
3420
                        }
3421
                    }
3422

    
3423
                    DataRow createTeeRow(DataRow itemRow)
3424
                    {
3425
                        DataRow newRow = PathItems.NewRow();
3426
                        newRow["OID"] = Guid.NewGuid().ToString();
3427
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3428
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3429
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3430
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3431
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
3432
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3433
                        newRow["DESCRIPTION"] = "";
3434
                        newRow["Class"] = "Branch";
3435
                        newRow["SubClass"] = "Tee";
3436
                        newRow["TYPE"] = itemRow["TYPE"];
3437
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3438
                        newRow["NPD"] = itemRow["NPD"];
3439
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3440
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3441
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3442
                      
3443
                        newRow["EGTConnectedPoint"] = 0;
3444
                        return newRow;
3445
                    }
3446
                }
3447
                catch (Exception ex)
3448
                {
3449

    
3450
                }
3451
            }
3452
        }
3453
    }
3454

    
3455
    public class PSNItem
3456
    {
3457
        public PSNItem(int count, int Revision)
3458
        {
3459
            Groups = new List<Group>();
3460
            Topologies = new List<Topology>();
3461

    
3462
            Index = count + 1;
3463
            this.Revision = Revision;
3464
        }
3465

    
3466
        private int Revision;
3467
        public string UID { get; set; }
3468
        public List<Group> Groups { get; set; }
3469
        public List<Topology> Topologies { get; set; }
3470
        public PSNType StartType { get; set; }
3471
        public PSNType EndType { get; set; }
3472
        public int Index { get; set; }
3473
        public string IsValid { get; set; }
3474
        public bool IsKeyword { get; set; }
3475
        public string Status { get; set; }
3476
        public string IncludingVirtualData { get; set; }
3477
        public string PSNAccuracy { get; set; }
3478
        public KeywordInfo KeywordInfos = new KeywordInfo();
3479
        public DataTable Nozzle = new DataTable();
3480

    
3481
        public string PSN_OID()
3482
        {
3483
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
3484
        }
3485

    
3486
        public string GetPSNType()
3487
        {
3488
            string result = string.Empty;
3489

    
3490
            if (EnableType(StartType) && EnableType(EndType))
3491
            {
3492
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
3493
                    result = "E2E";
3494
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
3495
                    result = "B2B";
3496
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
3497
                    result = "HD2";
3498

    
3499
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
3500
                    result = "E2B";
3501
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
3502
                    result = "B2E";
3503

    
3504
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
3505
                    result = "HDB";
3506
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
3507
                    result = "HDB";
3508

    
3509
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
3510
                    result = "HDE";
3511
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
3512
                    result = "HDE";
3513
                else
3514
                    result = "Error";
3515
            }
3516
            else
3517
                result = "Error";
3518

    
3519
            return result;
3520

    
3521

    
3522
        }
3523

    
3524
        public bool EnableType(PSNType type)
3525
        {
3526
            bool result = false;
3527

    
3528
            if (type == PSNType.Branch ||
3529
                type == PSNType.Equipment ||
3530
                type == PSNType.Header)
3531
            {
3532
                result = true;
3533
            }
3534

    
3535
            return result;
3536
        }
3537

    
3538
        public bool IsBypass { get; set; }
3539

    
3540
        public string GetFromData(ref string Type, ref Item item)
3541
        {
3542
            Status = string.Empty;
3543
            string result = string.Empty;
3544
            if (IsKeyword)
3545
                IsKeyword = false;
3546
            try
3547
            {
3548
                item = Groups.First().Items.First();
3549

    
3550
                if (StartType == PSNType.Header)
3551
                    result = "ENDOFHEADER";
3552
                else if (StartType == PSNType.Branch)
3553
                {
3554
                    if (item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
3555
                    {
3556
                        result = item.Relations.First().Item.LineNumber.Name;
3557
                        if (item.MissingLineNumber2)
3558
                        {
3559
                            Status += ", Missing LineNumber_2";
3560
                            IsValid = "Error";
3561
                        }
3562
                        if (item.MissingLineNumber1)
3563
                        {
3564
                            Status += ", Missing LineNumber_1";
3565
                            IsValid = "Error";
3566
                        }
3567
                    }
3568
                    else
3569
                    {
3570
                        IsValid = "Error";
3571
                        result = "Empty LineNumber";
3572
                    }
3573
                }
3574
                else if (StartType == PSNType.Equipment)
3575
                {
3576
                    if (Groups.First().Items.First().Equipment != null)
3577
                        result = Groups.First().Items.First().Equipment.ItemTag;
3578
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
3579

    
3580
                    if (drNozzle != null)
3581
                        result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3582
                }
3583
                else
3584
                {
3585
                    
3586
                    item = Groups.First().Items.First();
3587
                    if (item.ItemType == ItemType.Symbol)
3588
                    {
3589
                        string keyword = string.Empty;
3590
                        keyword = GetFromKeywordData(ref Type, item);
3591

    
3592
                        if (string.IsNullOrEmpty(keyword))
3593
                        {
3594
                            if (item.ID2DBType.Contains("OPC's"))
3595
                                Status += ", OPC Disconnected";
3596
                            else
3597
                                Status += ", Missing ItemTag or Description";
3598

    
3599
                            result = item.ID2DBName;
3600
                            IsValid = "Error";
3601
                        }
3602
                        else
3603
                        {
3604
                            result = keyword;
3605
                            IsKeyword = true;
3606
                        }
3607

    
3608
                    }
3609
                    else if (item.ItemType == ItemType.Line)
3610
                    {
3611

    
3612
                        if (item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name))
3613
                        {
3614
                            result = item.LineNumber.Name;
3615
                            if (item.MissingLineNumber2)
3616
                            {
3617
                                Status += ", Missing LineNumber_2";
3618
                                IsValid = "Error";
3619
                            }
3620
                            if (item.MissingLineNumber1)
3621
                            {
3622
                                Status += ", Missing LineNumber_1";
3623
                                IsValid = "Error";
3624
                            }
3625
                        }
3626
                        else
3627
                        {
3628
                            IsValid = "Error";
3629
                            result = "Empty LineNumber";
3630
                        }
3631
                    }
3632
                    else
3633
                        result = "Unknown";
3634
                }
3635
            }
3636
            catch (Exception ex)
3637
            {
3638

    
3639
            }
3640

    
3641
            return result;
3642
        }
3643

    
3644
        public string GetFromKeywordData(ref string Type, Item item)
3645
        {
3646
            string result = string.Empty;
3647

    
3648
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3649
            {
3650
                if (keyitem.Name.Equals(item.Name))
3651
                {
3652
                    result = keyitem.Keyword;
3653
                    Type = item.ID2DBType;
3654
                    break;
3655
                }
3656
            }
3657

    
3658
            return result;
3659
        }
3660

    
3661
        public string GetToKeywordData(ref string Type, Item item)
3662
        {
3663
            string result = string.Empty;
3664

    
3665
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3666
            {
3667
                if (keyitem.Name.Equals(item.Name))
3668
                {
3669
                    result = keyitem.Keyword;
3670
                    Type = item.ID2DBType;
3671
                    break;
3672
                }
3673
            }
3674
            return result;
3675
        }
3676

    
3677
        public string GetToData(ref string ToType, ref Item item)
3678
        {
3679
            string result = string.Empty;
3680
            Status = string.Empty;
3681

    
3682
            if (IsKeyword)
3683
                IsKeyword = false;
3684

    
3685
            item = Groups.Last().Items.Last();
3686

    
3687
            if (EndType == PSNType.Header)
3688
                result = "ENDOFHEADER";
3689
            else if (EndType == PSNType.Branch)
3690
            {
3691
                if (item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
3692
                {
3693
                    result = item.Relations.Last().Item.LineNumber.Name;
3694
                    if (item.MissingLineNumber2)
3695
                    {
3696
                        Status += ", Missing LineNumber_2";
3697
                        IsValid = "Error";
3698
                    }
3699
                    if (item.MissingLineNumber1)
3700
                    {
3701
                        Status += ", Missing LineNumber_1";
3702
                        IsValid = "Error";
3703
                    }
3704
                }
3705
                else
3706
                {
3707
                    IsValid = "Error";
3708
                    result = "Empty LineNumber";
3709
                }                
3710
            }
3711
            else if (EndType == PSNType.Equipment)
3712
            {
3713
                if (Groups.Last().Items.Last().Equipment != null)
3714
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
3715

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

    
3718
                if (drNozzle != null)
3719
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3720
            }
3721
            else
3722
            {
3723
                
3724
                item = Groups.Last().Items.Last();
3725
                if (item.ItemType == ItemType.Symbol)
3726
                {
3727
                    string keyword = string.Empty;
3728
                    keyword = GetToKeywordData(ref ToType, item);
3729

    
3730
                    if (string.IsNullOrEmpty(keyword))
3731
                    {
3732
                        if (item.ID2DBType.Contains("OPC's"))
3733
                            Status += ", OPC Disconnected";
3734
                        else
3735
                            Status += ", Missing ItemTag or Description";
3736

    
3737
                        result = item.ID2DBName;
3738
                        IsValid = "Error";
3739
                    }
3740
                    else
3741
                    {
3742
                        result = keyword;
3743
                        IsKeyword = true;
3744
                    }
3745

    
3746
                }
3747
                else if (item.ItemType == ItemType.Line)
3748
                {
3749
                    if (item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name))
3750
                    {
3751
                        result = item.LineNumber.Name;
3752
                        if (item.MissingLineNumber2)
3753
                        {
3754
                            Status += ", Missing LineNumber_2";
3755
                            IsValid = "Error";
3756
                        }
3757
                        if (item.MissingLineNumber1)
3758
                        {
3759
                            Status += ", Missing LineNumber_1";
3760
                            IsValid = "Error";
3761
                        }
3762
                    }
3763
                    else
3764
                    {
3765
                        IsValid = "Error";
3766
                        result = "Empty LineNumber";
3767
                    }
3768
                }
3769
                else
3770
                    result = "Unknown";
3771
            }
3772
            return result;
3773
        }
3774

    
3775
        public string GetPBSData()
3776
        {
3777
            string result = string.Empty;
3778
            List<string> PBSList = new List<string>();
3779
            if (Settings.Default.PBSSetting.Equals("Line Number"))
3780
            {
3781
                string attrValue = Settings.Default.PBSSettingValue;
3782

    
3783
                foreach (Group group in Groups)
3784
                {
3785
                    List<LineNumber> lineNumbers = group.Items.Select(x => x.LineNumber).Distinct().ToList();
3786
                    foreach (LineNumber lineNumber in lineNumbers)
3787
                    {
3788
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
3789
                        if (attribute != null)
3790
                        {
3791
                            string value = attribute.Value;
3792
                            if (!PBSList.Contains(value))
3793
                                PBSList.Add(value);
3794
                        }
3795
                    }
3796
                }
3797
            }
3798
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
3799
            {
3800
                string attrValue = Settings.Default.PBSSettingValue;
3801

    
3802
                foreach (Group group in Groups)
3803
                {
3804
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
3805
                    foreach (Item item in items)
3806
                    {
3807
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
3808
                        if (!PBSList.Contains(value))
3809
                            PBSList.Add(value);
3810
                    }
3811
                }
3812
            }
3813
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
3814
            {
3815
                string attrValue = Settings.Default.PBSSettingValue;
3816

    
3817
                foreach (Group group in Groups)
3818
                {
3819
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3820
                    foreach (Document document in documents)
3821
                    {
3822
                        string name = document.DrawingName;
3823

    
3824
                        int startIndex = Settings.Default.PBSSettingStartValue;
3825
                        int endIndex = Settings.Default.PBSSettingEndValue;
3826

    
3827
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
3828
                        if (!PBSList.Contains(subStr))
3829
                            PBSList.Add(subStr);
3830
                    }
3831
                }
3832
            }
3833
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
3834
            {
3835
                foreach (Group group in Groups)
3836
                {
3837
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3838
                    foreach (Document document in documents)
3839
                    {
3840
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
3841
                        foreach (TextInfo textInfo in textInfos)
3842
                        {
3843
                            if (!PBSList.Contains(textInfo.Value))
3844
                                PBSList.Add(textInfo.Value);
3845
                        }
3846
                    }
3847
                }
3848
            }
3849

    
3850
            foreach (var item in PBSList)
3851
            {
3852
                if (string.IsNullOrEmpty(result))
3853
                    result = item;
3854
                else
3855
                    result += ", " + item;
3856
            }
3857
            return result;
3858
        }
3859
    }
3860
}
클립보드 이미지 추가 (최대 크기: 500 MB)