프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / ID2PSN / PSN.cs @ 2327f39c

이력 | 보기 | 이력해설 | 다운로드 (199 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 PSN From/To Keyword & EndofHeader
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
            PathItemSorting();
262
            InsertTeePSN();
263

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

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

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

    
276
            UpdateNoPocket();
277

    
278
            // 확도 계산
279
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateAccuracy ( 95 % )");
280
            UpdateAccuracy();
281

    
282
            //UpdatePSNType();
283

    
284
        }
285

    
286
        private void UpdateNoPocket()
287
        {
288
            try
289
            {
290
                DataRow[] nopocketRows = PipeSystemNetwork.Select("Pocket = 'Yes'");
291
                foreach (DataRow row in nopocketRows)
292
                {
293
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", row["OID"].ToString()));
294
                    foreach (DataRow dr in pathItemRows)
295
                    {
296
                        if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
297
                        {
298
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));
299

    
300
                            if (rows.First()["SubType"].ToString() == "Bypass")
301
                            {
302
                                DataRow[] bypassRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", dr.Field<string>("ViewPipeSystemNetwork_OID")));
303

    
304
                                foreach (DataRow drby in bypassRows)
305
                                {
306
                                    drby["Pocket"] = "Yes";
307
                                }
308
                            }
309
                        }
310
                    }                    
311
                }            
312
            }
313
            catch (Exception ex)
314
            {
315
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
316
            }
317
        }
318

    
319
        private void UpdatePSNType()
320
        {
321
            try
322
            {
323
                foreach (PSNItem PSNItem in PSNItems)
324
                {    
325
                    foreach (Group group in PSNItem.Groups)
326
                    {
327
                        foreach (Item item in group.Items)
328
                        {
329
                            DataRow[] pipeSystems = PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID()));
330
                           // PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
331

    
332
                            foreach(DataRow dr in pipeSystems)
333
                            {
334
                                dr["Type"] = PSNItem.GetPSNType();
335
                            }                            
336
                        }
337
                    }                
338
                }
339
            }
340
            catch (Exception ex)
341
            {
342
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
343
            }
344
        }
345

    
346
        private void PathItemSorting()
347
        {
348
            try
349
            {
350
                DataTable dtPathItems = PathItems.Clone();
351
                DataTable dtPipeSystemNetwork = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
352

    
353
                foreach (DataRow drpipe in dtPipeSystemNetwork.Rows)
354
                {
355
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drpipe["OID"].ToString()));
356
                    DataTable dtSequenceItems = SequenceData.Clone();
357
                    foreach (DataRow drpath in pathItemRows)
358
                    {
359
                        DataRow sequenceRows = SequenceData.Select(string.Format("PathItem_OID = '{0}'", drpath.Field<string>("OID"))).First();
360

    
361
                        DataRow newRow = dtSequenceItems.NewRow();
362
                        foreach (DataColumn column in SequenceData.Columns)
363
                            if (dtSequenceItems.Columns[column.ColumnName] != null)
364
                                newRow[column.ColumnName] = sequenceRows[column.ColumnName];
365

    
366
                        dtSequenceItems.Rows.Add(newRow);
367
                    }
368

    
369
                    foreach (DataRow sqrow in dtSequenceItems.Select().OrderBy(x => Convert.ToInt32(x.Field<string>("SERIALNUMBER"))))
370
                    {
371
                        DataRow newRow = dtPathItems.NewRow();
372
                        DataRow row = PathItems.Select(string.Format("OID = '{0}'", sqrow["PathItem_OID"])).First();
373

    
374
                        foreach (DataColumn column in PathItems.Columns)
375
                            if (dtPathItems.Columns[column.ColumnName] != null)
376
                                newRow[column.ColumnName] = row[column.ColumnName];
377

    
378
                        dtPathItems.Rows.Add(newRow);
379
                    }
380
                }
381

    
382
                PathItems.Clear();
383
                PathItems = dtPathItems.Copy();
384
            }
385
            catch (Exception ex)
386
            {
387
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
388
            }
389
        }
390
        
391
        private void UpdateAirFinCooler()
392
        {
393
            try
394
            {
395
                
396
                int pumpTagNum = 0;
397
                #region EquipmentAirFinCooler Info
398
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
399
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
400
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
401
                {
402
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
403
                    {
404
                        Type = row["Type"].ToString(),
405
                        TagIdentifier = row["TagIdentifier"].ToString(),
406
                        AttributeName = row["AttributeName"].ToString(),
407
                        Name = row["Name"].ToString()
408
                    });
409
                }
410
                #endregion
411

    
412
                
413
                DataRow[] pumpRows = PipeSystemNetwork.Select("PUMP = 'PUMP'");
414
                Dictionary<string, string> eqkeyValuePairs = new Dictionary<string, string>();
415
                // 1, 2번
416
                foreach (DataRow dataRow in pumpRows) 
417
                {                  
418
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
419

    
420
                    string EGTAG = "EGTAG";
421
                   // string ItemTag = "ItemTag";
422
                    string EGFlowDirection = string.Empty;
423
                    string Prefix = string.Empty;
424
                    string SymbolName = string.Empty;
425

    
426
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
427
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
428
                    {
429
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
430
                        {
431
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
432
                            if (!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
433
                                EGTAG = PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null
434
                                   ? string.Empty : PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
435

    
436
                            SymbolName = PSNItem.Groups.First().Items.First().Equipment.Name;
437
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;                            
438
                            EGFlowDirection = "O";
439
                        }                        
440
                    } 
441
                    
442
                    if(string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
443
                    {
444
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
445
                        {
446
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
447
                            if (!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
448
                                EGTAG = PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null
449
                                    ? string.Empty : PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
450

    
451
                            SymbolName = PSNItem.Groups.Last().Items.Last().Equipment.Name;
452
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;                            
453
                            EGFlowDirection = "I";
454
                        }
455
                    }
456

    
457
                    //Attribute가 세팅되어있지 않다면
458
                    if (EGTAG.Equals("EGTAG"))
459
                    {
460
                        if (!eqkeyValuePairs.ContainsKey(SymbolName))
461
                        {
462
                            if (!string.IsNullOrEmpty(Prefix))
463
                            {
464
                                pumpTagNum++;
465
                                EGTAG = Prefix + string.Format("-{0}", string.Format("{0:D5}", pumpTagNum));
466
                                eqkeyValuePairs.Add(SymbolName, EGTAG);
467
                            }
468
                            else
469
                            {
470
                                eqkeyValuePairs.Add(SymbolName, SymbolName);
471
                            }
472
                        }
473
                        else
474
                        {
475
                            EGTAG = eqkeyValuePairs[SymbolName];
476
                        }
477
                    }
478
                    else
479
                    {
480
                        if (!string.IsNullOrEmpty(Prefix))
481
                            EGTAG = Prefix + "-" + EGTAG;
482
                    }
483

    
484

    
485
                    foreach (DataRow dr in pathItemRows)
486
                    {
487
                        dr["EqpGroupTag"] = EGTAG;
488
                        dr["EGFlowDirection"] = EGFlowDirection;
489
                    }
490
                }
491

    
492
                // 3, 4번
493
                foreach (DataRow dataRow in pumpRows) 
494
                {
495

    
496
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
497
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
498
                    string EGFlowDirection = string.Empty;
499

    
500
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
501
                    {
502
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
503
                        {
504
                            EGFlowDirection = "O";
505
                        }
506
                    }
507
                    
508
                    if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
509
                    {
510
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
511
                        {
512
                            EGFlowDirection = "I";
513
                        }
514
                    }
515

    
516

    
517
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
518

    
519
                    foreach (DataRow dr in pathItemRows)
520
                    {
521
                        if(dr.Field<string>("ViewPipeSystemNetwork_OID") != dataRow["OID"].ToString())
522
                        {
523
                            string viewEGFlowDirection = string.Empty;
524
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}'", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
525
                            {
526
                                PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));                               
527

    
528
                                if (viewPSNItem.Groups.First().Items.First().Equipment != null)
529
                                {
530
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
531
                                    {
532
                                        viewEGFlowDirection = "O";
533
                                    }
534
                                }
535
                                
536
                                
537
                                if (string.IsNullOrEmpty(viewEGFlowDirection) && viewPSNItem.Groups.Last().Items.Last().Equipment != null)
538
                                {
539
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
540
                                    {
541
                                        viewEGFlowDirection = "I";
542
                                    }
543
                                }
544

    
545
                                if (EGFlowDirection.Equals(viewEGFlowDirection) && !lstViewPipeSystemNetwork_OID.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
546
                                    lstViewPipeSystemNetwork_OID.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
547
                            }
548
                            else
549
                            {
550
                            }
551
                        }
552
                    }
553

    
554
                    string selectViewOID = string.Empty;
555

    
556
                    if (EGFlowDirection == "O") //From 이면 시작점에서 제일 먼 값
557
                    {
558
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
559
                        {
560
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
561
                            {                                
562
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
563
                            }
564
                        }
565
                    }
566
                    else if (EGFlowDirection == "I") //To 이면 시작점에서 제일 가까운 값
567
                    {
568
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
569
                        {
570
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
571
                            {
572
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
573
                                break;
574
                            }
575
                        }
576
                    }
577

    
578
                    if (!string.IsNullOrEmpty(selectViewOID)) //selectViewOID 가 있으면
579
                    {              
580
                        string EqpGroupTag = string.Empty;                       
581

    
582
                        if((EGFlowDirection == "O" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.Last().Field<string>("ViewPipeSystemNetwork_OID"))) ||
583
                            (EGFlowDirection == "I" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID"))))
584
                        { 
585
                            DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID")));
586

    
587
                            foreach (DataRow row in viewpathItemRows)
588
                            {
589
                                if (!string.IsNullOrEmpty(row.Field<string>("EqpGroupTag")))
590
                                {
591
                                    EqpGroupTag = row.Field<string>("EqpGroupTag");
592
                                    break;
593
                                }
594
                            }
595

    
596
                            foreach (DataRow dr in pathItemRows)
597
                            {
598
                                dr["EqpGroupTag"] = EqpGroupTag;
599
                            }
600

    
601
                        }
602
                        else
603
                        {
604
                            bool bCheck = false;
605
                            if (EGFlowDirection == "I") //To 일때
606
                            {
607
                                foreach (DataRow dr in pathItemRows)
608
                                {
609
                                    if (selectViewOID == dr["OID"].ToString())
610
                                    {
611
                                        dr["EGTConnectedPoint"] = "1";
612
                                        bCheck = true;
613
                                    }
614

    
615
                                    if (!bCheck)
616
                                    {
617
                                        dr["EqpGroupTag"] = string.Empty;
618
                                        dr["MainLineTag"] = string.Empty;
619
                                        dr["EGTConnectedPoint"] = "0";
620
                                        dr["EGFlowDirection"] = string.Empty;
621
                                    }
622
                                    else
623
                                    {
624
                                        dr["MainLineTag"] = "M";
625
                                    }
626
                                    
627
                                }
628

    
629
                            }
630
                            else if (EGFlowDirection == "O") //From 일 때
631
                            {
632
                                foreach (DataRow dr in pathItemRows)
633
                                {
634
                                    if (bCheck)
635
                                    {
636
                                        
637
                                        dr["EqpGroupTag"] = string.Empty;
638
                                        dr["MainLineTag"] = string.Empty;
639
                                        dr["EGTConnectedPoint"] = "0";
640
                                        dr["EGFlowDirection"] = string.Empty;
641
                                    }
642
                                    else
643
                                    {
644
                                        dr["MainLineTag"] = "M";
645
                                    }
646

    
647
                                    if (selectViewOID == dr["OID"].ToString())
648
                                    {
649
                                        dr["EGTConnectedPoint"] = "1";
650
                                        bCheck = true;
651
                                    }
652
                                }
653
                            }
654
                        }
655
                    }
656
                    else
657
                    {
658
                        //foreach (DataRow dr in pathItemRows)
659
                        //{
660
                        //    dr["EqpGroupTag"] = string.Empty;
661
                        //    dr["EGFlowDirection"] = string.Empty;
662
                        //    dr["EGTConnectedPoint"] = "0";
663
                        //    dr["MainLineTag"] = string.Empty;
664
                        //}
665
                    }
666
                }
667
                                
668
                // 5번
669
                foreach (DataRow dataRow in pumpRows)
670
                {
671
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
672

    
673
                    bool bCheck = false;
674
                    string EqpGroupTag = string.Empty;
675

    
676
                    string EGFlowDirection = string.Empty;                   
677

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

    
680
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
681
                    {
682
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
683
                        {
684
                            EGFlowDirection = "O";
685
                        }
686
                    }
687
                    
688
                    if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
689
                    {
690
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
691
                        {
692
                            EGFlowDirection = "I";
693
                        }
694
                    }
695

    
696
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
697
                    List<string> lstEqTagRows = new List<string>();
698
                    if (EGFlowDirection.Equals("I"))
699
                    {
700
                        foreach (DataRow dr in pathItemRows)
701
                        {                            
702
                            if (!string.IsNullOrEmpty(dr.Field<string>("MainLineTag")) && dr.Field<string>("MainLineTag").Equals("M") && !string.IsNullOrEmpty(dr.Field<string>("EqpGroupTag")))
703
                            {
704
                                bCheck = true;
705
                                EqpGroupTag = dr.Field<string>("EqpGroupTag");
706
                                if(!lstEqTagRows.Contains(EqpGroupTag))
707
                                    lstEqTagRows.Add(EqpGroupTag);
708

    
709
                                if(dataRow["OID"].ToString() != dr.Field<string>("ViewPipeSystemNetwork_OID"))
710
                                {
711
                                    PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));
712
                                    if (viewPSNItem.Groups.Last().Items.Last().Equipment == null)
713
                                        continue;
714

    
715
                                    if (!lstEqTagRows.Contains(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag))
716
                                        lstEqTagRows.Add(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag);
717
                                }
718
                                
719
                            }
720

    
721
                        }
722
                        if(bCheck)
723
                        {
724
                            foreach (DataRow row in pumpRows)
725
                            {
726
                                if (row.Field<string>("OID").Equals(dataRow["OID"].ToString()))
727
                                    continue;
728

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

    
731
                                if (viewPSNItem.Groups.First().Items.First().Equipment == null)
732
                                    continue;
733
                                
734
                                if (lstEqTagRows.Contains(viewPSNItem.Groups.First().Items.First().Equipment.ItemTag) && !lstViewPipeSystemNetwork_OID.Contains(row.Field<string>("OID")))
735
                                    lstViewPipeSystemNetwork_OID.Add(row.Field<string>("OID"));
736
                            }
737

    
738
                                
739

    
740
                            if (lstViewPipeSystemNetwork_OID.Count() > 0)
741
                            {
742
                                foreach (string viewPipesystem in lstViewPipeSystemNetwork_OID)
743
                                {
744
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewPipesystem));
745
                                    foreach (DataRow viewdr in viewpathItemRows)
746
                                    {
747
                                        if (!string.IsNullOrEmpty(viewdr["EqpGroupTag"].ToString()))
748
                                            viewdr["EqpGroupTag"] = EqpGroupTag;
749
                                    }
750
                                }
751
                            }
752
                        }                        
753
                    }                   
754
                }
755
                
756
                int afcTagNum = 0;
757
                DataRow[] airFinCoolerRows = PipeSystemNetwork.Select("AFC Like 'P1%'");
758
                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
759
                foreach (DataRow dataRow in airFinCoolerRows)
760
                {
761
                    string EGFlowDirection = string.Empty;
762
                    string EGTAG = "EGTAG";
763
                    string Prefix = string.Empty;
764
                    string SymbolName = string.Empty;
765

    
766
                    //item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
767
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
768
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
769
                    {
770
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
771
                        {
772
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
773
                            if(!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
774
                                EGTAG = PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null 
775
                                    ? string.Empty : PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
776

    
777
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;
778
                            EGFlowDirection = "O";
779
                        }
780
                    }
781

    
782
                    if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
783
                    {
784
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
785
                        {
786
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
787
                            if (!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
788
                                EGTAG = PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null 
789
                                    ? string.Empty : PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
790

    
791
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;
792
                            EGFlowDirection = "I";
793
                        }
794
                    }
795

    
796
                    if(!string.IsNullOrEmpty(EGFlowDirection))
797
                    {
798
                        string[] afcTag = dataRow.Field<string>("AFC").Split(new string[] { "\\" }, StringSplitOptions.None);
799

    
800
                        //Attribute가 세팅되어있지 않다면
801
                        if (EGTAG.Equals("EGTAG"))
802
                        {                          
803
                            if (!keyValuePairs.ContainsKey(afcTag[1]))
804
                            {
805
                                if (!string.IsNullOrEmpty(Prefix))
806
                                {
807
                                    afcTagNum++;
808
                                    EGTAG = Prefix + string.Format("-{0}", string.Format("{0:D5}", afcTagNum));
809
                                    keyValuePairs.Add(afcTag[1], EGTAG);
810
                                }
811
                                else
812
                                {
813
                                    keyValuePairs.Add(afcTag[1], afcTag[1]);
814

    
815
                                }
816
                            }
817
                            else
818
                            {
819
                                EGTAG = keyValuePairs[afcTag[1]];
820
                            }
821
                            
822
                        }
823
                        else
824
                        {
825
                            if (!string.IsNullOrEmpty(Prefix))
826
                                EGTAG = Prefix + "-" + EGTAG;                          
827
                        }
828

    
829
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
830
                        foreach (DataRow dr in pathItemRows)
831
                        {
832
                            dr["EqpGroupTag"] = EGTAG;
833
                            dr["EGFlowDirection"] = EGFlowDirection;
834
                        }
835
                    }
836
                    
837
                }
838

    
839
                List<string> changePSN = new List<string>();
840
                foreach (DataRow dataRow in airFinCoolerRows)
841
                {
842
                    if (changePSN.Contains(dataRow["OID"].ToString()))
843
                        continue;
844

    
845
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
846
                    string AFCTag = string.Empty;
847
                    if (pathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).Count() > 0)
848
                        AFCTag = pathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).First().Field<string>("EqpGroupTag");
849

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

    
852
                    if (dataRow["Type"].ToString() == "E2E")
853
                    {
854
                        foreach (DataRow dr in pathItemRows)
855
                        {
856
                            dr["MainLineTag"] = "M";
857
                        }
858
                        dataRow["AFC"] = "P3";
859
                    }
860
                    else if (dataRow["Type"].ToString() == "E2B" || dataRow["Type"].ToString() == "B2E")
861
                    {
862
                        foreach (string lstoid in lstViewPipeSystemNetwork_OID)
863
                        {
864
                            DataRow[] p2psn = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", lstoid));
865

    
866
                            if (p2psn.Count() > 0)
867
                            {
868
                                DataRow[] viewPathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstoid));
869
                                List<string> lstview = viewPathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
870
                                lstview.Remove(dataRow["OID"].ToString()); // P1인 자신 제거
871
                                lstview.Remove(lstoid); // P2 자신 제거
872

    
873
                                List<string> lstnewpipe = new List<string>();
874
                                foreach (string lstvw in lstview) //자신 외 P1이 있는지 확인
875
                                {
876
                                    if (airFinCoolerRows.Where(x => x.Field<string>("OID").Equals(lstvw)).Count() > 0) //P1이면 리스트에 추가
877
                                        lstnewpipe.Add(lstvw);
878
                                }
879

    
880
                                if (lstnewpipe.Count() == 0)
881
                                {
882
                                    foreach (DataRow dr in pathItemRows)
883
                                    {
884
                                        dr["MainLineTag"] = "M";
885
                                    }
886
                                    dataRow["AFC"] = "P3";
887
                                }
888
                                else
889
                                {
890
                                    // P2에 ML값 AGT값 지정
891
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstoid));
892
                                    DataRow[] pipesystemRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", lstoid));
893
                                    foreach (DataRow viewdr in pipesystemRows)
894
                                    {
895
                                        viewdr["AFC"] = "P4";
896
                                    }
897

    
898
                                    foreach (DataRow viewdr in viewpathItemRows)
899
                                    {
900
                                        viewdr["EqpGroupTag"] = AFCTag;
901
                                        viewdr["MainLineTag"] = "M";
902
                                    }
903
                                    // 연결된 모든 P1들의 AGT값 치환
904
                                    foreach (string pipe in lstnewpipe)
905
                                    {
906
                                        viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipe));
907
                                        foreach (DataRow viewdr in viewpathItemRows)
908
                                        {
909
                                            viewdr["EqpGroupTag"] = AFCTag;
910
                                        }
911
                                    }
912
                                }
913
                            }                               
914
                        }   
915
                    }
916
                }
917
                
918
                //P3을 제외한 P1
919
                airFinCoolerRows = PipeSystemNetwork.Select("AFC Like 'P1%'");
920
                foreach (DataRow dataRow in airFinCoolerRows)
921
                {
922
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
923
                    
924
                    if (pathItemRows.Count() > 0)
925
                    {
926
                        List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
927
                        List<string> lstpsn = new List<string>();
928
                        List<string> lstAll = new List<string>();
929
                        string EqpGroupTag = string.Empty;
930
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
931
                        {
932
                            if (dataRow["OID"].ToString() == viewOID)
933
                            {
934
                                lstAll.Add(viewOID);
935
                                continue;
936
                            }
937

    
938
                            //P3이면
939
                            DataRow viewPSN = null;
940
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).Count() > 0)
941
                                viewPSN = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).First();
942
                            
943
                            if (viewPSN != null)
944
                            {
945
                                //P3의 AGT를 가져와 P1에 입력
946
                                if(string.IsNullOrEmpty(EqpGroupTag))
947
                                    EqpGroupTag = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID)).First().Field<string>("EqpGroupTag");
948

    
949
                                foreach (DataRow dr in pathItemRows)
950
                                {
951
                                    dr["EqpGroupTag"] = EqpGroupTag;
952

    
953
                                    //P1의 AGT와 같은 모든 AGT를 P3의 AGT로 변경하기위해 
954
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
955
                                    {
956
                                        //AND MainLineTag = ''
957
                                        if (PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' ", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
958
                                        {
959
                                            lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
960
                                            lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
961
                                        }
962
                                    }
963
                                }
964
                            }                            
965
                        }
966

    
967
                        while (lstpsn.Count() != 0)
968
                        {                            
969
                            DataRow[] rule4pathItems = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstpsn[0]));
970
                            foreach (DataRow dr in rule4pathItems)
971
                            {
972
                                if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstAll.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
973
                                {
974
                                    DataRow viewPSN = null;
975

    
976
                                    if (airFinCoolerRows.Where(x => x.Field<string>("OID") == dr.Field<string>("ViewPipeSystemNetwork_OID")).Count() > 0)
977
                                        viewPSN = airFinCoolerRows.Where(x => x.Field<string>("OID") == dr.Field<string>("ViewPipeSystemNetwork_OID")).First();
978
                                                                        
979
                                    if (viewPSN != null)
980
                                    {
981
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
982
                                        lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
983
                                    }
984
                                }                                
985

    
986
                                dr["EqpGroupTag"] = EqpGroupTag;
987

    
988
                            }
989
                            lstpsn.Remove(lstpsn[0]);
990
                        }
991
                    }
992
                    
993
                }
994

    
995
                foreach(DataRow dr in PipeSystemNetwork.Rows)
996
                {
997
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = 'M'", dr["OID"].ToString()));
998
                    if(pathItemRows.Count() > 0)
999
                    {
1000
                        if(dr["Type"].ToString() == "HD2")
1001
                        {
1002
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
1003
                            foreach(string viewpsn in lstViewPipeSystemNetwork_OID)
1004
                            {                              
1005
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", viewpsn)).Count() > 0)
1006
                                {
1007
                                    foreach(DataRow dataRow in pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewpsn))
1008
                                    {
1009
                                        dataRow["EGTConnectedPoint"] = "1";
1010
                                    }
1011
                                }
1012
                            }
1013
                        }
1014
                        else if(dr["Type"].ToString() == "E2B" || dr["Type"].ToString() == "B2E" || dr["Type"].ToString() == "E2E")
1015
                        {
1016
                            PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dr["OID"].ToString());
1017
                            string EGFlowDirection = string.Empty;
1018
                            if (PSNItem.Groups.First().Items.First().Equipment != null)
1019
                            {
1020
                                if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
1021
                                {
1022
                                    EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
1023
                                    if (equipmentAirFinCoolerItem != null)
1024
                                        EGFlowDirection = "O";
1025
                                }
1026
                            }
1027
                            
1028
                            if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
1029
                            {
1030
                                if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
1031
                                {
1032
                                    EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
1033
                                    if(equipmentAirFinCoolerItem != null)
1034
                                        EGFlowDirection = "I";
1035
                                }
1036
                            }
1037

    
1038
                            if (!string.IsNullOrEmpty(EGFlowDirection))
1039
                            {
1040
                                List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
1041
                                string lastP1 = string.Empty;
1042

    
1043
                                foreach (string viewpsn in lstViewPipeSystemNetwork_OID)
1044
                                {
1045
                                    if (viewpsn == dr["OID"].ToString())
1046
                                        continue;
1047

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

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

    
1053
                                    if (rows != null)
1054
                                    {
1055
                                        lastP1 = viewpsn;
1056
                                        if (EGFlowDirection.Equals("I")) // To         
1057
                                            break;
1058
                                    }
1059
                                }
1060

    
1061
                                if (!string.IsNullOrEmpty(lastP1))
1062
                                {
1063
                                    bool bCheck = false;
1064
                                    if (EGFlowDirection.Equals("O")) // From
1065
                                    {
1066
                                        foreach (DataRow dataRow in pathItemRows)
1067
                                        {
1068
                                            if (bCheck)
1069
                                            {
1070
                                                dataRow["EqpGroupTag"] = string.Empty;
1071
                                                dataRow["MainLineTag"] = string.Empty;
1072
                                                dataRow["EGTConnectedPoint"] = 0;
1073
                                                dataRow["EGFlowDirection"] = string.Empty;
1074
                                            }
1075

    
1076
                                            if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
1077
                                            {
1078
                                                bCheck = true;
1079
                                                dataRow["EGTConnectedPoint"] = 1;
1080
                                            }
1081
                                        }
1082
                                    }
1083
                                    else
1084
                                    {
1085
                                        foreach (DataRow dataRow in pathItemRows)
1086
                                        {
1087
                                            if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
1088
                                            {
1089
                                                dataRow["EGTConnectedPoint"] = 1;
1090
                                                break;
1091
                                            }
1092
                                            
1093
                                            dataRow["EqpGroupTag"] = string.Empty;
1094
                                            dataRow["MainLineTag"] = string.Empty;
1095
                                            dataRow["EGTConnectedPoint"] = 0;
1096
                                            dataRow["EGFlowDirection"] = string.Empty;
1097

    
1098
                                        }
1099
                                    }
1100
                                }
1101
                            }                          
1102
                        }
1103
                    }
1104
                }
1105

    
1106
                //psn data 정리
1107
                foreach(DataRow pipesystem in PipeSystemNetwork.Rows)
1108
                {
1109
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipesystem["OID"].ToString()));
1110
                    string EGTag = string.Empty;
1111
                    string HasMLTags = "False";
1112

    
1113
                    foreach (DataRow dataRow in pathItemRows)
1114
                    {
1115
                        if (string.IsNullOrEmpty(EGTag) && !string.IsNullOrEmpty(dataRow.Field<string>("EqpGroupTag")))
1116
                            EGTag = dataRow.Field<string>("EqpGroupTag");
1117

    
1118
                        if (HasMLTags.Equals("False") && !string.IsNullOrEmpty(dataRow.Field<string>("MainLineTag")) && dataRow.Field<string>("MainLineTag").Equals("M"))
1119
                            HasMLTags = "True";
1120

    
1121
                        if (!string.IsNullOrEmpty(EGTag) && HasMLTags == "True")
1122
                            break;
1123
                    }
1124

    
1125
                    pipesystem["EGTag"] = EGTag;
1126
                    pipesystem["HasMLTags"] = HasMLTags;
1127
                }
1128
            }
1129
            catch (Exception ex)
1130
            {
1131
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
1132
            }
1133
            //}
1134
        }
1135

    
1136
        private void UpdateValveGrouping()
1137
        {
1138
            try
1139
            {
1140
                #region ValveGrouping Info
1141
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
1142
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
1143
                foreach (DataRow row in dtValveGroupung.Rows)
1144
                {
1145
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
1146
                    {
1147
                        OID = row["OID"].ToString(),
1148
                        GroupType = row["GroupType"].ToString(),
1149
                        TagIdentifier = row["TagIdentifier"].ToString(),
1150
                        AttributeName = row["AttributeName"].ToString(),
1151
                        SppidSymbolName = row["SppidSymbolName"].ToString()
1152
                    });
1153
                }
1154
                #endregion
1155

    
1156

    
1157
                int vgTagNum = 1;
1158
                DataRow[] tagpathItemRows = PathItems.Select(string.Format("GROUPTAG Like '%\\%'"));
1159
                List<string> pathOid = new List<string>();
1160
                foreach (DataRow drPathitem in tagpathItemRows)
1161
                {
1162
                    if (pathOid.Contains(drPathitem.Field<string>("OID")))
1163
                        continue;
1164

    
1165
                    string[] valvetag = drPathitem["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
1166
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1167
                    ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
1168
                    if (valveitem == null || valveitem.GroupType == "Scope Break")
1169
                        continue;
1170
                    Dictionary<int, List<DataRow>> keyValuePairs = new Dictionary<int, List<DataRow>>();
1171
                    List<Item> valveGroupingItem = new List<Item>();
1172
                    int bCnt = 0;
1173

    
1174
                    
1175
                    List<DataRow> lstitem = new List<DataRow>();
1176
                    foreach (DataRow dr in pathItemRows)
1177
                    {
1178
                        if (dr["GROUPTAG"].ToString() == "Scope Break")
1179
                        {
1180
                            dr["GROUPTAG"] = string.Empty;
1181
                            keyValuePairs.Add(bCnt, lstitem.ToList());
1182
                            bCnt++;
1183
                            lstitem.Clear();
1184
                            continue;
1185
                        }
1186
                       
1187

    
1188
                        if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1189
                        {
1190
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));                          
1191
                           
1192
                            if (rows.First()["SubType"].ToString() != "Bypass" && rows.First()["SubType"].ToString() != "Vent_Drain")
1193
                            {
1194
                                if (lstitem.ToList().Where(x => !string.IsNullOrEmpty(x.Field<string>("GROUPTAG"))).Count() > 0)
1195
                                {
1196
                                    lstitem.Add(dr);
1197
                                    keyValuePairs.Add(bCnt, lstitem.ToList());
1198
                                    lstitem.Clear();
1199
                                }
1200
                                else
1201
                                {
1202
                                    keyValuePairs.Add(bCnt, lstitem.ToList());
1203
                                    lstitem.Clear();
1204
                                    lstitem.Add(dr);
1205
                                }
1206
                                bCnt++;
1207

    
1208
                            }
1209
                            else
1210
                                lstitem.Add(dr);
1211
                            
1212
                        }
1213
                        else
1214
                            lstitem.Add(dr);
1215
                    }
1216

    
1217
                    if (lstitem.Count > 0)
1218
                    {
1219
                        keyValuePairs.Add(bCnt, lstitem);
1220
                    }
1221

    
1222
                    if (keyValuePairs.Count() == 0)
1223
                        continue;
1224

    
1225
                    string VGTag = string.Empty;
1226
                    if (valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
1227
                    {
1228
                        VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1229
                        vgTagNum++;
1230
                    }
1231
                    else
1232
                    {                        
1233
                        VGTag = valveitem.TagIdentifier + "-" + valvetag[1];
1234
                    }
1235

    
1236
                    foreach (KeyValuePair<int, List<DataRow>> keyValuePair in keyValuePairs)
1237
                    {                       
1238
                        if (keyValuePair.Value.Where(x => x.Field<string>("OID") == drPathitem.Field<string>("OID")).Count() > 0)
1239
                        {
1240
                            if (!pathOid.Contains(drPathitem.Field<string>("OID")))
1241
                                pathOid.Add(drPathitem.Field<string>("OID"));
1242

    
1243
                            foreach (DataRow dr in keyValuePair.Value)
1244
                            {
1245
                                dr["GROUPTAG"] = VGTag;
1246

    
1247
                                if(!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1248
                                {
1249
                                    if(TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString())).First().Field<string>("SubType") == "Bypass")
1250
                                    {
1251
                                        DataRow[] rows = keyValuePair.Value.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID").Equals(dr["ViewPipeSystemNetwork_OID"].ToString())).ToArray();
1252
                                        foreach(DataRow path in rows)
1253
                                        {
1254
                                            DataRow topology = TopologySet.Select(string.Format("OID = '{0}'", path["BranchTopologySet_OID"].ToString())).First();
1255
                                            if (topology.Field<string>("SubType").Equals("Bypass"))
1256
                                            {
1257
                                                DataRow[] drPathItem = PathItems.Select(string.Format("TopologySet_OID = '{0}'", topology.Field<string>("OID")));
1258
                                                //if (dr["GROUPTAG"].ToString() == "Scope Break")
1259
                                                if(drPathItem.Where(x => x.Field<string>("GROUPTAG") == "Scope Break").Count() == 0)
1260
                                                {
1261
                                                    foreach (DataRow pathitem in drPathItem)
1262
                                                    {
1263
                                                        pathitem["GROUPTAG"] = VGTag;
1264
                                                    }
1265
                                                }
1266
                                            }
1267
                                        }
1268
                                    }
1269
                                }
1270
                            }
1271
                        }
1272
                        else
1273
                        {                            
1274
                            foreach (DataRow drs in tagpathItemRows)
1275
                            {
1276
                                if (drs.Field<string>("OID").Equals(drPathitem.Field<string>("OID")))
1277
                                    continue;
1278
                              
1279
                                if(keyValuePair.Value.Where(x => x.Field<string>("OID") == drs.Field<string>("OID")).Count() > 0)
1280
                                {
1281
                                    if (!pathOid.Contains(drs.Field<string>("OID")))
1282
                                    {
1283
                                        pathOid.Add(drs.Field<string>("OID"));
1284

    
1285
                                        valvetag = drs["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
1286
                                        ValveGroupItem valveitems = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
1287
                                        if (valveitems == null || valveitems.GroupType == "Scope Break")
1288
                                            continue;
1289

    
1290
                                        VGTag = string.Empty;
1291
                                        if (valveitems.AttributeName == "NoSelection" || valveitems.AttributeName == string.Empty)
1292
                                        {
1293
                                            VGTag = valveitems.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1294
                                            vgTagNum++;
1295
                                        }
1296
                                        else
1297
                                        {
1298
                                            VGTag = valveitems.TagIdentifier + "-" + valvetag[1];
1299
                                        }
1300

    
1301
                                        foreach (DataRow dr in keyValuePair.Value)
1302
                                        {
1303
                                            dr["GROUPTAG"] = VGTag;
1304

    
1305
                                            if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1306
                                            {
1307
                                                if (TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString())).First().Field<string>("SubType") == "Bypass")
1308
                                                {
1309
                                                    DataRow[] rows = keyValuePair.Value.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID").Equals(dr["ViewPipeSystemNetwork_OID"].ToString())).ToArray();
1310
                                                    foreach (DataRow path in rows)
1311
                                                    {
1312
                                                        DataRow topology = TopologySet.Select(string.Format("OID = '{0}'", path["BranchTopologySet_OID"].ToString())).First();
1313
                                                        if (topology.Field<string>("SubType").Equals("Bypass"))
1314
                                                        {
1315
                                                            DataRow[] drPathItem = PathItems.Select(string.Format("TopologySet_OID = '{0}'", topology.Field<string>("OID")));
1316
                                                            if (drPathItem.Where(x => x.Field<string>("GROUPTAG") == "Scope Break").Count() == 0)
1317
                                                            {
1318
                                                                foreach (DataRow pathitem in drPathItem)
1319
                                                                {
1320
                                                                    pathitem["GROUPTAG"] = VGTag;
1321
                                                                }
1322
                                                            }
1323
                                                        }
1324
                                                    }
1325
                                                }
1326
                                            }
1327
                                        }
1328

    
1329
                                        if (valveitems.GroupType.Contains("PSV"))
1330
                                        {
1331
                                            DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1332
                                            foreach (DataRow row in psnRows)
1333
                                                row["Pocket"] = "Yes";
1334
                                        }
1335
                                    }     
1336
                                }
1337
                            }                            
1338
                        }
1339
                    }
1340

    
1341
                    if(valveitem.GroupType.Contains("PSV"))
1342
                    {
1343
                        DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1344
                        foreach (DataRow row in psnRows)
1345
                            row["Pocket"] = "Yes";
1346
                    }                    
1347
                }
1348

    
1349
                tagpathItemRows = PathItems.Select(string.Format("GROUPTAG = 'Scope Break'"));
1350
                foreach (DataRow drPathitem in tagpathItemRows)
1351
                {
1352
                    drPathitem["GROUPTAG"] = string.Empty;
1353
                }
1354
            }
1355
            catch (Exception ex)
1356
            {
1357
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
1358
            }
1359
        }
1360

    
1361
        private void SetTopologyData()
1362
        {
1363
            // 13번 excel
1364
            foreach (Group group in groups)
1365
            {
1366
                LineNumber prevLineNumber = null;
1367
                for (int i = 0; i < group.Items.Count; i++)
1368
                {
1369
                    Item item = group.Items[i];
1370
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1371
                    if (lineNumber == null)
1372
                    {
1373
                        if (prevLineNumber != null)
1374
                        {
1375
                            if (!prevLineNumber.IsCopy)
1376
                            {
1377
                                prevLineNumber = prevLineNumber.Copy();
1378
                                prevLineNumber.MissingLineNumber1 = true;
1379
                                item.Document.LineNumbers.Add(prevLineNumber);
1380
                                //item.LineNumber.MissingLineNumber1 = true;
1381
                            }
1382
                            item.Owner = prevLineNumber.UID;
1383
                        }
1384
                    }
1385
                    else
1386
                        prevLineNumber = lineNumber;
1387
                }
1388

    
1389
                prevLineNumber = null;
1390
                for (int i = group.Items.Count - 1; i > -1; i--)
1391
                {
1392
                    Item item = group.Items[i];
1393
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1394
                    if (lineNumber == null)
1395
                    {
1396
                        if (prevLineNumber != null)
1397
                        {
1398
                            if (!prevLineNumber.IsCopy)
1399
                            {
1400
                                prevLineNumber = prevLineNumber.Copy();
1401
                                prevLineNumber.MissingLineNumber1 = true;
1402
                                item.Document.LineNumbers.Add(prevLineNumber);
1403
                                //item.LineNumber.MissingLineNumber1 = true;                                
1404
                            }
1405

    
1406
                            item.Owner = prevLineNumber.UID;
1407
                        }
1408
                    }
1409
                    else
1410
                        prevLineNumber = lineNumber;
1411
                }
1412

    
1413
                if (prevLineNumber == null)
1414
                {
1415
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
1416
                    Random random = new Random();
1417

    
1418
                    LineNumber cLineNumber = null;
1419

    
1420
                    if (lineNumbers.Count == 0)
1421
                    {
1422
                        var _groups = groups.Where(w => w != group).ToList();
1423
                        while (cLineNumber == null)
1424
                        {
1425
                            int _index = random.Next(_groups.Count - 1);
1426
                            List<LineNumber> _lineNumbers = groups[_index].Document.LineNumbers.FindAll(x => !x.IsCopy);
1427
                            if (_lineNumbers.Count != 0)
1428
                            {
1429
                                _index = random.Next(_lineNumbers.Count - 1);
1430

    
1431
                                // Copy
1432
                                cLineNumber = _lineNumbers[_index].Copy();
1433
                            }
1434
                        }
1435
                    }
1436
                    else
1437
                    {
1438
                        int index = random.Next(lineNumbers.Count - 1);
1439

    
1440
                        // Copy
1441
                        cLineNumber = lineNumbers[index].Copy();
1442
                    }
1443

    
1444
                    cLineNumber.MissingLineNumber2 = true;
1445
                    group.Document.LineNumbers.Add(cLineNumber);
1446

    
1447
                    foreach (Item item in group.Items)
1448
                    {
1449
                        item.Owner = cLineNumber.UID;                        
1450
                    }
1451
                }
1452

    
1453
                //if (prevLineNumber == null)
1454
                //{
1455
                //    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
1456
                //    Random random = new Random();
1457
                //    int index = random.Next(lineNumbers.Count - 1);
1458

    
1459
                //    // Copy
1460
                //    LineNumber cLineNumber = lineNumbers[index].Copy();
1461
                //    group.Document.LineNumbers.Add(cLineNumber);
1462

    
1463
                //    foreach (Item item in group.Items)
1464
                //    {
1465
                //        item.Owner = cLineNumber.UID;
1466
                //        item.Document.MissingLineNumber2 = true;
1467
                //    }
1468
                //}
1469
            }
1470

    
1471
            foreach (Document document in Documents)
1472
            {
1473
                foreach (Item item in document.Items)
1474
                {
1475
                    item.TopologyData = string.Empty;
1476
                    item.PSNPipeLineID = string.Empty;
1477
                    List<string> pipeLineID = new List<string>();
1478
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
1479
                    
1480
                    if (lineNumber != null)
1481
                    {
1482
                        item.LineNumber = lineNumber;
1483

    
1484
                        foreach (DataRow row in topologyRuleDT.Rows)
1485
                        {
1486
                            string uid = row["UID"].ToString();
1487
                            //if (uid == "-")
1488
                            //    pipeLineID.Add(item.TopologyData);//item.TopologyData += "-"; 
1489
                            if (uid != "-")
1490
                            {
1491
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
1492

    
1493
                                Attribute attribute = lineNumber.Attributes.Find(x => x.DisplayName == uid);
1494
                                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
1495
                                {
1496
                                    pipeLineID.Add(attribute.Value);//item.TopologyData += attribute.Value;
1497
                                                                    //if (uid.Equals("Tag Seq No") && attribute.Value.ToString().Substring(attribute.Value.ToString().Length - 1, 1).Equals("V"))
1498
                                                                    //{
1499
                                    if (item.LineNumber.MissingLineNumber1 && item.LineNumber.MissingLineNumber2)
1500
                                    {
1501

    
1502
                                    }
1503

    
1504
                                 
1505
                                    //    //if (item.Document.MissingLineNumber1)
1506
                                    //    //    item.MissingLineNumber1 = true;
1507
                                    //    //else if (item.Document.MissingLineNumber2)
1508
                                    //    //    item.MissingLineNumber2 = true;
1509
                                    //}
1510
                                }
1511
                            }
1512
                        }
1513
                        
1514
                        if (topologyRuleDT.Select(string.Format("UID = '{0}'", "InsulationPurpose")) == null)
1515
                        {
1516
                            Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
1517
                            if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
1518
                                pipeLineID.Add(insulAttr.Value); //item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
1519
                                                                 //else
1520
                                                                 //    item.PSNPipeLineID = item.TopologyData;
1521
                        }
1522

    
1523
                        item.PSNPipeLineID = string.Join("-", pipeLineID);
1524
                        item.TopologyData = string.Join("-", pipeLineID);
1525
                        
1526
                    }
1527
                    else
1528
                    {
1529
                        item.TopologyData = "Empty LineNumber";
1530
                        item.LineNumber = new LineNumber();
1531
                    }
1532
                }
1533
            }
1534

    
1535
            int emptyIndex = 1;
1536
            foreach (Group group in groups)
1537
            {
1538
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
1539
                if (groupItems.Count > 0)
1540
                {
1541
                    foreach (var item in groupItems)
1542
                        item.TopologyData += string.Format("-{0}", emptyIndex);
1543
                    emptyIndex++;
1544
                }
1545
            }
1546

    
1547
        }
1548

    
1549
        private void ConnectByOPC()
1550
        {
1551
            try
1552
            {
1553
                foreach (Group group in groups.FindAll(x => x.Items.Last().SubItemType == SubItemType.OPC))
1554
                {
1555
                    Item opcItem = group.Items.Last();
1556
                    DataRow[] fromRows = opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID));
1557
                    if (fromRows.Length.Equals(1))
1558
                    {
1559
                        DataRow opcRow = fromRows.First();
1560
                        string toDrawing = opcRow["ToDrawing"].ToString();
1561
                        string toOPCUID = opcRow["ToOPCUID"].ToString();
1562

    
1563
                        Document toDocument = Documents.Find(x => x.DrawingName == toDrawing);
1564
                        if (toDocument != null)
1565
                        {
1566
                            Group toGroup = toDocument.Groups.Find(x => x.Items.Find(y => y.UID == toOPCUID) != null);
1567
                            DataRow[] toRows = opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID));
1568
                            //1대1 매칭이 아닐때 걸림 (2개 이상일 때) 2021.11.07 
1569
                            if (toRows.Length > 1)
1570
                            {
1571
                                //throw new Exception("OPC error(multi connect)");
1572
                                MessageBox.Show("OPC error(multi connect)", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1573
                                return;
1574
                            }
1575
                            group.EndGroup = toGroup;
1576
                            toGroup.StartGroup = group;
1577
                        }
1578
                    }
1579
                }
1580
            }
1581
            catch (Exception ex)
1582
            {
1583
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1584
                //MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1585
            }
1586
        }
1587

    
1588
        private void SetPSNItem()
1589
        {
1590
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>();
1591
            foreach (Group group in groups)
1592
                groupDic.Add(group, Guid.NewGuid().ToString());
1593

    
1594
            foreach (Group group in groups)
1595
            {
1596
                string groupKey = groupDic[group];
1597
                if (group.StartGroup != null)
1598
                {
1599
                    string otherKey = groupDic[group.StartGroup];
1600
                    ChangeGroupID(otherKey, groupKey);
1601
                }
1602
            }
1603

    
1604
            // PSN 정리
1605
            foreach (var item in groupDic)
1606
            {
1607
                Group group = item.Key;
1608
                string uid = item.Value;
1609
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
1610
                if (PSNItem == null)
1611
                {
1612
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
1613
                    PSNItems.Add(PSNItem);
1614
                }
1615
                PSNItem.Groups.Add(group);
1616
                foreach (Item groupItem in group.Items)
1617
                    groupItem.PSNItem = PSNItem;
1618
            }
1619

    
1620
            // Sort PSN
1621
            foreach (PSNItem PSNItem in PSNItems)
1622
            {
1623
                List<Group> _groups = new List<Group>();
1624

    
1625
                Stack<Group> stacks = new Stack<Group>();
1626
                stacks.Push(PSNItem.Groups.First());
1627
                while (stacks.Count > 0)
1628
                {
1629
                    Group stack = stacks.Pop();
1630
                    if (_groups.Contains(stack))
1631
                        continue;
1632

    
1633
                    if (_groups.Count == 0)
1634
                        _groups.Add(stack);
1635
                    else
1636
                    {
1637
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
1638
                        {
1639
                            int index = _groups.IndexOf(stack.StartGroup);
1640
                            _groups.Insert(index + 1, stack);
1641
                        }
1642
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
1643
                        {
1644
                            int index = _groups.IndexOf(stack.EndGroup);
1645
                            _groups.Insert(index, stack);
1646
                        }
1647
                    }
1648

    
1649
                    if (stack.StartGroup != null)
1650
                        stacks.Push(stack.StartGroup);
1651
                    if (stack.EndGroup != null)
1652
                        stacks.Push(stack.EndGroup);
1653
                }
1654

    
1655
                PSNItem.Groups.Clear();
1656
                PSNItem.Groups.AddRange(_groups);
1657
            }
1658

    
1659
            void ChangeGroupID(string from, string to)
1660
            {
1661
                if (from.Equals(to))
1662
                    return;
1663

    
1664
                List<Group> changeItems = new List<Group>();
1665
                foreach (var _item in groupDic)
1666
                    if (_item.Value.Equals(from))
1667
                        changeItems.Add(_item.Key);
1668
                foreach (var _item in changeItems)
1669
                    groupDic[_item] = to;
1670
            }
1671
        }
1672

    
1673
        private void SetPSNType()
1674
        {
1675
            foreach (PSNItem PSNItem in PSNItems)
1676
            {
1677
                Group firstGroup = PSNItem.Groups.First();
1678
                Group lastGroup = PSNItem.Groups.Last();
1679

    
1680
                Item firstItem = firstGroup.Items.First();
1681
                Item lastItem = lastGroup.Items.Last();
1682

    
1683
                PSNItem.StartType = GetPSNType(firstItem, true);
1684
                PSNItem.EndType = GetPSNType(lastItem, false);
1685

    
1686
            }
1687

    
1688
            PSNType GetPSNType(Item item, bool bFirst = true)
1689
            {
1690
                PSNType type = PSNType.None;
1691

    
1692
                if (item.ItemType == ItemType.Line)
1693
                {
1694
                    Group group = groups.Find(x => x.Items.Contains(item));
1695
                    if (bFirst && item.Relations[0].Item != null && !group.Items.Contains(item.Relations[0].Item))
1696
                    {
1697
                        Item connItem = item.Relations[0].Item;
1698
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1699
                            type = PSNType.Branch;
1700
                        else if (connItem.ItemType == ItemType.Symbol)
1701
                            type = PSNType.Symbol;
1702
                    }
1703
                    else if (!bFirst && item.Relations[1].Item != null && !group.Items.Contains(item.Relations[1].Item))
1704
                    {
1705
                        Item connItem = item.Relations[1].Item;
1706
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1707
                            type = PSNType.Branch;
1708
                        else if (connItem.ItemType == ItemType.Symbol)
1709
                            type = PSNType.Symbol;
1710
                    }
1711
                }
1712
                else if (item.ItemType == ItemType.Symbol)
1713
                {
1714
                    if (item.SubItemType == SubItemType.Nozzle)
1715
                        type = PSNType.Equipment;
1716
                    else if (item.SubItemType == SubItemType.Header)
1717
                        type = PSNType.Header;
1718
                    else if (item.SubItemType == SubItemType.OPC)
1719
                        type = PSNType.OPC;
1720
                }
1721

    
1722
                return type;
1723
            }
1724
        }
1725

    
1726
        private void SetBranchInfo()
1727
        {
1728
            foreach (Document document in Documents)
1729
            {
1730
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
1731
                foreach (Item line in lines)
1732
                {
1733
                    double[] point = line.Relations[0].Point;
1734
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
1735
                    connLines.Sort(SortBranchLine);
1736
                    line.BranchItems.AddRange(connLines);
1737

    
1738
                    int SortBranchLine(Item a, Item b)
1739
                    {
1740
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
1741
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
1742

    
1743
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
1744
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
1745

    
1746
                        // 내림차순
1747
                        return distanceA.CompareTo(distanceB);
1748
                    }
1749
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
1750
                    {
1751
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
1752
                    }
1753
                }
1754
            }
1755
        }
1756

    
1757
        private void SetTopology()
1758
        {
1759
            try
1760
            {
1761
                #region 기본 topology 정리
1762
                foreach (PSNItem PSNItem in PSNItems)
1763
                {
1764
                    Topology topology = null;
1765
                    foreach (Group group in PSNItem.Groups)
1766
                    {
1767
                        foreach (Item item in group.Items)
1768
                        {
1769
                            if (string.IsNullOrEmpty(item.TopologyData))
1770
                                topology = null;
1771
                            else
1772
                            {
1773
                                if (topology == null)
1774
                                {
1775
                                    topology = new Topology()
1776
                                    {
1777
                                        ID = item.TopologyData
1778
                                    };
1779
                                    Topologies.Add(topology);
1780

    
1781
                                    if (!PSNItem.Topologies.Contains(topology))
1782
                                        PSNItem.Topologies.Add(topology);
1783
                                }
1784
                                else
1785
                                {
1786
                                    if (topology.ID != item.TopologyData)
1787
                                    {
1788
                                        topology = new Topology()
1789
                                        {
1790
                                            ID = item.TopologyData
1791
                                        };
1792
                                        Topologies.Add(topology);
1793

    
1794
                                        if (!PSNItem.Topologies.Contains(topology))
1795
                                            PSNItem.Topologies.Add(topology);
1796
                                    }
1797
                                }
1798

    
1799
                                item.Topology = topology;
1800
                                topology.Items.Add(item);
1801
                            }
1802
                        }
1803
                    }
1804
                }
1805
                #endregion
1806

    
1807
                #region Type
1808
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1809
                foreach (string id in ids)
1810
                {
1811
                    try
1812
                    {
1813

    
1814

    
1815
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1816

    
1817
                        // Main
1818
                        List<Topology> mainTopologies = FindMainTopology(topologies);
1819
                        foreach (Topology topology in mainTopologies)
1820
                            topology.Type = "M";
1821

    
1822
                        // Branch
1823
                        List<Topology> branchToplogies = topologies.FindAll(x => string.IsNullOrEmpty(x.Type));
1824
                        foreach (Topology topology in branchToplogies)
1825
                            topology.Type = "B";
1826
                    }
1827
                    catch (Exception ex)
1828
                    {
1829
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1830
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1831
                    }
1832
                }
1833
                #endregion
1834
            }
1835
            catch (Exception ex)
1836
            {
1837
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1838
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1839
            }
1840

    
1841
        }
1842

    
1843
        private void SetTopologyIndex()
1844
        {
1845
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1846
            foreach (string id in ids)
1847
            {
1848
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1849

    
1850
                // Main
1851
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
1852
                foreach (Topology topology in mainTopologies)
1853
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
1854

    
1855
                // Branch
1856
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
1857
                foreach (Topology topology in branchToplogies)
1858
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
1859
            }
1860
        }
1861

    
1862
        private void SetPSNBypass()
1863
        {
1864
            foreach (PSNItem PSNItem in PSNItems)
1865
                PSNItem.IsBypass = IsBypass(PSNItem);
1866
        }
1867

    
1868
        private List<Topology> FindMainTopology(List<Topology> data)
1869
        {
1870
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
1871
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
1872
            //2021.11.17 안쓰네 JY
1873
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
1874

    
1875
            List<Topology> main = new List<Topology>();
1876
            main.AddRange(data);
1877
            //
1878
            main = GetNozzleTopology(data);
1879
            if (main.Count == 1)
1880
                return main;
1881
            else
1882
            {
1883
                if (main.Count > 0)
1884
                    main = GetPMCTopology(main);
1885
                else
1886
                    main = GetPMCTopology(data);
1887

    
1888
                if (main.Count == 1)
1889
                    return main;
1890
                else
1891
                {
1892
                    if (main.Count > 0)
1893
                        main = GetDiaTopology(main);
1894
                    else
1895
                        main = GetDiaTopology(data);
1896

    
1897

    
1898
                    if (main.Count == 1)
1899
                        return main;
1900
                    else
1901
                    {
1902
                        if (main.Count > 0)
1903
                            main = GetItemTopology(main);
1904
                        else
1905
                            main = GetItemTopology(data);
1906
                    }
1907
                }
1908
            }
1909

    
1910
            List<Topology> GetNozzleTopology(List<Topology> topologies)
1911
            {
1912
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
1913
            }
1914

    
1915
            List<Topology> GetPMCTopology(List<Topology> topologies)
1916
            {
1917
                List<Topology> result = new List<Topology>();
1918
                foreach (DataRow row in PMCDT.Rows)
1919
                {
1920
                    string value = row["CODE"].ToString();
1921
                    foreach (Topology topology in topologies)
1922
                    {
1923
                        foreach (Item item in topology.Items)
1924
                        {
1925
                            if (item.LineNumber == null)
1926
                                continue;
1927
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1928
                            if (attribute != null && value == attribute.Value)
1929
                            {
1930
                                result.Add(topology);
1931
                                break;
1932
                            }
1933
                        }
1934
                    }
1935

    
1936
                    if (result.Count > 0)
1937
                        break;
1938
                }
1939

    
1940
                return result;
1941
            }
1942

    
1943
            List<Topology> GetDiaTopology(List<Topology> topologies)
1944
            {
1945
                List<Topology> result = new List<Topology>();
1946
                foreach (DataRow row in nominalDiameterDT.Rows)
1947
                {
1948
                    string inchValue = row["InchStr"].ToString();
1949
                    string metricValue = row["MetricStr"].ToString();
1950
                    foreach (Topology topology in topologies)
1951
                    {
1952
                        foreach (Item item in topology.Items)
1953
                        {
1954
                            if (item.LineNumber == null)
1955
                                continue;
1956
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1957
                            if (attribute != null && (inchValue == attribute.Value || metricValue == attribute.Value))
1958
                            {
1959
                                result.Add(topology);
1960
                                break;
1961
                            }
1962
                        }
1963
                    }
1964

    
1965
                    if (result.Count > 0)
1966
                        break;
1967
                }
1968

    
1969
                return result;
1970
            }
1971

    
1972
            List<Topology> GetItemTopology(List<Topology> topologies)
1973
            {
1974
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
1975
            }
1976

    
1977
            return main;
1978
        }
1979

    
1980
        private DataTable GetOPCInfo()
1981
        {
1982
            DataTable opc = DB.SelectOPCRelations();
1983
            DataTable drawing = DB.AllDrawings();
1984

    
1985
            DataTable dt = new DataTable();
1986
            dt.Columns.Add("FromDrawing", typeof(string));
1987
            dt.Columns.Add("FromDrawingUID", typeof(string));
1988
            dt.Columns.Add("FromOPCUID", typeof(string));
1989
            dt.Columns.Add("ToDrawing", typeof(string));
1990
            dt.Columns.Add("ToDrawingUID", typeof(string));
1991
            dt.Columns.Add("ToOPCUID", typeof(string));
1992
            foreach (DataRow row in opc.Rows)
1993
            {
1994
                string fromDrawingUID = row["From_Drawings_UID"] == null ? string.Empty : row["From_Drawings_UID"].ToString();
1995
                string fromOPCUID = row["From_OPC_UID"] == null ? string.Empty : row["From_OPC_UID"].ToString();
1996
                string toDrawingUID = row["To_Drawings_UID"] == null ? string.Empty : row["To_Drawings_UID"].ToString();
1997
                string toOPCUID = row["To_OPC_UID"] == null ? string.Empty : row["To_OPC_UID"].ToString();
1998
                if (!string.IsNullOrEmpty(toOPCUID))
1999
                {
2000
                    DataRow[] fromRows = drawing.Select(string.Format("UID = '{0}'", fromDrawingUID));
2001
                    DataRow[] toRows = drawing.Select(string.Format("UID = '{0}'", toDrawingUID));
2002
                    if (fromRows.Length.Equals(1) && toRows.Length.Equals(1))
2003
                    {
2004
                        string fromDrawingName = Path.GetFileNameWithoutExtension(fromRows.First()["NAME"].ToString());
2005
                        string toDrawingName = Path.GetFileNameWithoutExtension(toRows.First()["NAME"].ToString());
2006

    
2007
                        DataRow newRow = dt.NewRow();
2008
                        newRow["FromDrawing"] = fromDrawingName;
2009
                        newRow["FromDrawingUID"] = fromDrawingUID;
2010
                        newRow["FromOPCUID"] = fromOPCUID;
2011
                        newRow["ToDrawing"] = toDrawingName;
2012
                        newRow["ToDrawingUID"] = toDrawingUID;
2013
                        newRow["ToOPCUID"] = toOPCUID;
2014

    
2015
                        dt.Rows.Add(newRow);
2016
                    }
2017
                }
2018
            }
2019

    
2020
            return dt;
2021
        }
2022

    
2023
        private DataTable GetTopologyRule()
2024
        {
2025
            DataTable dt = DB.SelectTopologyRule();
2026

    
2027
            return dt;
2028
        }
2029

    
2030
        private bool IsConnected(Item item1, Item item2)
2031
        {
2032
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
2033
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
2034
                return true;
2035
            else
2036
                return false;
2037
        }
2038

    
2039
        private void SaveNozzleAndEquipment()
2040
        {
2041
            List<Item> nozzles = new List<Item>();
2042
            List<Equipment> equipments = new List<Equipment>();
2043
            foreach (Document document in Documents)
2044
            {
2045
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
2046
                equipments.AddRange(document.Equipments);
2047
            }
2048

    
2049

    
2050
            DataTable nozzleDT = new DataTable();
2051
            nozzleDT.Columns.Add("OID", typeof(string));
2052
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
2053
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
2054
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
2055
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
2056
            nozzleDT.Columns.Add("FLUID", typeof(string));
2057
            nozzleDT.Columns.Add("NPD", typeof(string));
2058
            nozzleDT.Columns.Add("PMC", typeof(string));
2059
            nozzleDT.Columns.Add("ROTATION", typeof(string));
2060
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
2061

    
2062
            foreach (Item item in nozzles)
2063
            {
2064
                DataRow row = nozzleDT.NewRow();
2065
                row["OID"] = item.UID;
2066

    
2067
                Relation relation = item.Relations.Find(x => equipments.Find(y => y.UID == x.UID) != null);
2068
                if (relation != null)
2069
                {
2070
                    Equipment equipment = equipments.Find(x => x.UID == relation.UID);
2071
                    equipment.Nozzles.Add(item);
2072
                    row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", equipment.Nozzles.Count + 100));
2073
                    row["Equipment_OID"] = equipment.UID;
2074
                    item.Equipment = equipment;
2075
                }
2076
                row["XCOORDS"] = (item.POINT[0] / DrawingWidth).ToString();
2077
                row["YCOORDS"] = (item.POINT[1] / DrawingHeight).ToString();
2078
                Attribute fluidAttr = item.LineNumber.Attributes.Find(x => x.Name == "FluidCode");
2079
                row["FLUID"] = fluidAttr != null ? fluidAttr.Value : string.Empty;
2080
                Attribute npdAttr = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
2081
                row["NPD"] = npdAttr != null ? npdAttr.Value : string.Empty;
2082
                Attribute pmcAttr = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
2083
                row["PMC"] = pmcAttr != null ? pmcAttr.Value : string.Empty;
2084

    
2085
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
2086
                if (angle >= Math.PI * 2)
2087
                    angle = angle - Math.PI * 2;
2088
                row["ROTATION"] = angle.ToString();
2089

    
2090
                if (item.Topology.Items.First().Equals(item))
2091
                    row["FlowDirection"] = "Outlet";
2092
                else if (item.Topology.Items.Last().Equals(item))
2093
                    row["FlowDirection"] = "Inlet";
2094
                else
2095
                    row["FlowDirection"] = string.Empty;
2096

    
2097
                nozzleDT.Rows.Add(row);
2098
            }
2099

    
2100
            DataTable equipDT = new DataTable();
2101
            equipDT.Columns.Add("OID", typeof(string));
2102
            equipDT.Columns.Add("ITEMTAG", typeof(string));
2103
            equipDT.Columns.Add("XCOORDS", typeof(string));
2104
            equipDT.Columns.Add("YCOORDS", typeof(string));
2105

    
2106
            foreach (Equipment equipment in equipments)
2107
            {
2108
                DataRow row = equipDT.NewRow();
2109
                row["OID"] = equipment.UID;
2110
                if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
2111
                {
2112
                    Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
2113
                    if (attribute != null)
2114
                        equipment.ItemTag = attribute.Value;
2115
                }
2116
                else
2117
                    equipment.ItemTag = equipment.Name;
2118

    
2119
                row["ITEMTAG"] = equipment.ItemTag;
2120
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
2121
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
2122

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

    
2126
                equipDT.Rows.Add(row);
2127
            }
2128

    
2129
            Equipment = equipDT;
2130
            Nozzle = nozzleDT;
2131
        }
2132

    
2133
        private void SavePSNData()
2134
        {
2135
            try
2136
            {
2137
                DataTable pathItemsDT = new DataTable();
2138
                pathItemsDT.Columns.Add("OID", typeof(string));
2139
                pathItemsDT.Columns.Add("SequenceData_OID", typeof(string));
2140
                pathItemsDT.Columns.Add("TopologySet_OID", typeof(string));
2141
                pathItemsDT.Columns.Add("BranchTopologySet_OID", typeof(string));
2142
                pathItemsDT.Columns.Add("PipeLine_OID", typeof(string));
2143
                pathItemsDT.Columns.Add("ITEMNAME", typeof(string));
2144
                pathItemsDT.Columns.Add("ITEMTAG", typeof(string));
2145
                pathItemsDT.Columns.Add("DESCRIPTION", typeof(string));
2146
                pathItemsDT.Columns.Add("Class", typeof(string));
2147
                pathItemsDT.Columns.Add("SubClass", typeof(string));
2148
                pathItemsDT.Columns.Add("TYPE", typeof(string));
2149
                pathItemsDT.Columns.Add("PIDNAME", typeof(string));
2150
                pathItemsDT.Columns.Add("Equipment_OID", typeof(string));
2151
                pathItemsDT.Columns.Add("NPD", typeof(string));
2152
                pathItemsDT.Columns.Add("GROUPTAG", typeof(string));
2153
                pathItemsDT.Columns.Add("PipeSystemNetwork_OID", typeof(string));
2154
                pathItemsDT.Columns.Add("ViewPipeSystemNetwork_OID", typeof(string));
2155
                pathItemsDT.Columns.Add("PipeRun_OID", typeof(string));
2156
                pathItemsDT.Columns.Add("EqpGroupTag", typeof(string));
2157
                pathItemsDT.Columns.Add("MainLineTag", typeof(string));
2158
                pathItemsDT.Columns.Add("EGTConnectedPoint", typeof(string));
2159
                pathItemsDT.Columns.Add("EGFlowDirection", typeof(string));
2160

    
2161
                DataTable sequenceDataDT = new DataTable();
2162
                sequenceDataDT.Columns.Add("OID", typeof(string));
2163
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
2164
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
2165
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
2166

    
2167
                DataTable pipeSystemNetworkDT = new DataTable();
2168
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
2169
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
2170
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
2171
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
2172
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
2173
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
2174
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
2175
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
2176
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
2177
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
2178
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
2179
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
2180
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
2181
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
2182
                pipeSystemNetworkDT.Columns.Add("Pocket", typeof(string));
2183
                pipeSystemNetworkDT.Columns.Add("EGTag", typeof(string));
2184
                pipeSystemNetworkDT.Columns.Add("HasMLTags", typeof(string));
2185
                pipeSystemNetworkDT.Columns.Add("AFC", typeof(string));
2186
                pipeSystemNetworkDT.Columns.Add("PUMP", typeof(string));
2187

    
2188
                DataTable topologySetDT = new DataTable();
2189
                topologySetDT.Columns.Add("OID", typeof(string));
2190
                topologySetDT.Columns.Add("Type", typeof(string));
2191
                topologySetDT.Columns.Add("SubType", typeof(string));
2192
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
2193
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
2194
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
2195
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
2196

    
2197
                DataTable pipelineDT = new DataTable();
2198
                pipelineDT.Columns.Add("OID", typeof(string));
2199
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
2200
                pipelineDT.Columns.Add("FLUID", typeof(string));
2201
                pipelineDT.Columns.Add("PMC", typeof(string));
2202
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
2203
                pipelineDT.Columns.Add("INSULATION", typeof(string));
2204
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
2205
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
2206
                pipelineDT.Columns.Add("Unit", typeof(string));
2207

    
2208
                DataTable pipesystemDT = new DataTable();
2209
                pipesystemDT.Columns.Add("OID", typeof(string));
2210
                pipesystemDT.Columns.Add("DESCRIPTION", typeof(string));
2211
                pipesystemDT.Columns.Add("FLUID", typeof(string));
2212
                pipesystemDT.Columns.Add("PMC", typeof(string));
2213
                pipesystemDT.Columns.Add("PipeLineQty", typeof(string));
2214
                pipesystemDT.Columns.Add("GroundLevel", typeof(string));
2215

    
2216
                // Set Vent/Drain Info
2217
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
2218
                DataTable dt = DB.SelectVentDrainSetting();
2219
                foreach (DataRow row in dt.Rows)
2220
                {
2221
                    string groupID = row["GROUP_ID"].ToString();
2222
                    string desc = row["DESCRIPTION"].ToString();
2223
                    int index = Convert.ToInt32(row["INDEX"]);
2224
                    string name = row["NAME"].ToString();
2225

    
2226
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
2227
                    if (ventDrainInfo == null)
2228
                    {
2229
                        ventDrainInfo = new VentDrainInfo(groupID);
2230
                        ventDrainInfo.Description = desc;
2231
                        VentDrainInfos.Add(ventDrainInfo);
2232
                    }
2233

    
2234
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
2235
                    {
2236
                        Index = index,
2237
                        Name = name
2238
                    });
2239
                }
2240
                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2241
                    ventDrainInfo.VentDrainItems = ventDrainInfo.VentDrainItems.OrderBy(x => x.Index).ToList();
2242

    
2243
                #region Keyword Info
2244
                KeywordInfo KeywordInfos = new KeywordInfo();
2245
                DataTable dtKeyword = DB.SelectKeywordsSetting();
2246
                foreach (DataRow row in dtKeyword.Rows)
2247
                {
2248
                    int index = Convert.ToInt32(row["INDEX"]);
2249
                    string name = row["NAME"].ToString();
2250
                    string keyword = row["KEYWORD"].ToString();
2251

    
2252
                    //KeywordInfo keywordInfo = new KeywordInfo();   
2253
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
2254
                    {
2255
                        Index = index,
2256
                        Name = name,
2257
                        Keyword = keyword
2258
                    });
2259
                }
2260
                #endregion
2261

    
2262
                #region ValveGrouping Info
2263
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
2264
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
2265
                foreach (DataRow row in dtValveGroupung.Rows)
2266
                {
2267
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
2268
                    {
2269
                        OID = row["OID"].ToString(),
2270
                        GroupType = row["GroupType"].ToString(),
2271
                        TagIdentifier = row["TagIdentifier"].ToString(),
2272
                        AttributeName = row["AttributeName"].ToString(),
2273
                        SppidSymbolName = row["SppidSymbolName"].ToString()
2274
                    });
2275
                }
2276
                #endregion
2277

    
2278
                #region EquipmentNoPocket Info
2279
                EquipmentNoPocketInfo EquipmentNoPocket = new EquipmentNoPocketInfo();
2280
                DataTable dtEquipmentNoPocket = DB.SelectEquipmentNoPocketSetting();
2281
                foreach (DataRow row in dtEquipmentNoPocket.Rows)
2282
                {
2283
                    EquipmentNoPocket.EquipmentNoPocketItem.Add(new EquipmentNoPocketItem()
2284
                    {
2285
                        Index = Convert.ToInt32(row["INDEX"]),
2286
                        Type = row["TYPE"].ToString(),
2287
                        Name = row["NAME"].ToString()
2288
                    });
2289
                }
2290
                #endregion
2291

    
2292
                #region EquipmentAirFinCooler Info
2293
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
2294
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
2295
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
2296
                {
2297
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
2298
                    {
2299
                        Type = row["Type"].ToString(),
2300
                        Name = row["Name"].ToString()
2301
                    });
2302
                }
2303
                #endregion
2304

    
2305
                // key = 미입력 branch
2306
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
2307
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
2308
                DataTable PSNFluidDT = DB.SelectPSNFluidCode();
2309
                DataTable PSNPMCDT = DB.SelectPSNPIPINGMATLCLASS();
2310
                foreach (PSNItem PSNItem in PSNItems)
2311
                {
2312
                    try
2313
                    {
2314
                        int psnOrder = 0;
2315
                        int index = 0;
2316
                        bool bPSNStart = true;
2317
                        string sPSNData = string.Empty;
2318
                        bool bVentDrain = false;
2319

    
2320
                      List<Group> Groups = PSNItem.Groups;
2321
                        Dictionary<string, List<Item>> keyValuePairs = new Dictionary<string, List<Item>>();
2322
                        List<Item> valveGroupingItem = new List<Item>();
2323

    
2324
                        //VentDrain 검사
2325
                        if (PSNItem.Groups.Count.Equals(1))
2326
                        {
2327
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
2328
                            for (int g = 0; g < Groups.Count; g++)
2329
                            {
2330
                                Group group = Groups[g];
2331

    
2332
                                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2333
                                {
2334
                                    if(!bVentDrain)
2335
                                    {
2336
                                        for (int i = 0; i < group.Items.Count; i++)
2337
                                        {
2338
                                            Item item = group.Items[i];
2339
                                            if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2340
                                                endInfos.Add(ventDrainInfo);
2341
                                            else
2342
                                            {
2343
                                                endInfos.Clear();
2344
                                                if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2345
                                                    endInfos.Add(ventDrainInfo);
2346
                                            }
2347

    
2348
                                            if (ventDrainInfo.VentDrainItems.Count().Equals(endInfos.Count()))
2349
                                            {
2350
                                                bVentDrain = true;
2351
                                                break;
2352
                                            }
2353
                                        }
2354
                                    }                                   
2355
                                }                               
2356

    
2357
                                if (!bVentDrain)
2358
                                {
2359
                                    endInfos = new List<VentDrainInfo>();
2360

    
2361
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2362
                                    {
2363
                                        if (!bVentDrain)
2364
                                        {
2365
                                            for (int i = 0; i < group.Items.Count; i++)
2366
                                            {
2367
                                                Item item = group.Items[group.Items.Count - i - 1];
2368

    
2369
                                                if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2370
                                                    endInfos.Add(ventDrainInfo);
2371
                                                else
2372
                                                {
2373
                                                    endInfos.Clear();
2374
                                                    if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2375
                                                        endInfos.Add(ventDrainInfo);
2376
                                                }
2377

    
2378
                                                if (ventDrainInfo.VentDrainItems.Count().Equals(endInfos.Count()))
2379
                                                {
2380
                                                    bVentDrain = true;
2381
                                                    break;
2382
                                                }
2383
                                            }
2384
                                        }
2385
                                    }
2386
                                }
2387
                            }
2388
                        }
2389

    
2390
                        try
2391
                        {
2392
                            foreach (Group group in PSNItem.Groups)
2393
                            {
2394
                                foreach (Item item in group.Items)
2395
                                {
2396
                                    string VgTag = string.Empty;
2397
                                    
2398
                                    if (ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).Count() > 0)
2399
                                    {
2400
                                        ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).First();
2401
                                        string value = string.Empty;
2402

    
2403
                                        if (valveitem.GroupType == "Scope Break" || valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
2404
                                            value = "NoSelection";
2405
                                        else
2406
                                        {
2407
                                            if(item.Attributes.Find(x => x.Name == valveitem.AttributeName) == null)
2408
                                                value = "NoSelection";
2409
                                            else
2410
                                                value = item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
2411
                                        }
2412

    
2413
                                        if (valveitem.GroupType == "Scope Break")
2414
                                            VgTag = "Scope Break";
2415
                                        else
2416
                                            VgTag = valveitem.SppidSymbolName + "\\" + value;
2417

    
2418
                                    }
2419

    
2420
                                    string PathitemUID = string.Empty;
2421
                                    if (item.BranchItems.Count == 0)
2422
                                    {
2423
                                        PathitemUID = item.UID;
2424
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2425
                                        CreateSequenceDataDataRow(PathitemUID);
2426
                                        index++;
2427
                                    }
2428
                                    else
2429
                                    {
2430
                                        PathitemUID = item.UID + "_L1";
2431
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2432
                                        CreateSequenceDataDataRow(PathitemUID);
2433
                                        index++;
2434
                                        for (int i = 0; i < item.BranchItems.Count; i++)
2435
                                        {
2436
                                            CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", string.Empty, item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
2437
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
2438
                                            index++;
2439

    
2440
                                            CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
2441
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
2442
                                            index++;
2443

    
2444
                                            if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
2445
                                                startBranchDic.Add(item.BranchItems[i], item);
2446
                                            else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
2447
                                                endBranchDic.Add(item.BranchItems[i], item);
2448
                                        }
2449
                                    }
2450

    
2451
                                    if (bPSNStart)
2452
                                    {
2453
                                        CreatePipeSystemNetworkDataRow();
2454
                                        sPSNData = item.TopologyData;
2455
                                        psnOrder++;
2456
                                        bPSNStart = false;
2457
                                    }
2458
                                    else
2459
                                    {
2460
                                        if (item.TopologyData != sPSNData)
2461
                                        {
2462
                                            CreatePipeSystemNetworkDataRow();
2463
                                            sPSNData = item.TopologyData;
2464
                                            psnOrder++;
2465
                                        }
2466
                                    }
2467

    
2468
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string GROUPTAG = "", string branchTopologyName = "", Item branchItem = null)
2469
                                    {
2470
                                        DataRow newRow = pathItemsDT.NewRow();
2471

    
2472
                                        if (itemType == "Nozzles")
2473
                                        {
2474
                                            newRow["Equipment_OID"] = item.Equipment != null ? item.Equipment.UID : "";
2475
                                        }
2476

    
2477
                                        newRow["OID"] = itemOID;
2478
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2479
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
2480
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
2481
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
2482
                                        newRow["ITEMNAME"] = GetItemName(item, itemOID);
2483
                                        newRow["ITEMTAG"] = GetItemTag(item);
2484
                                        newRow["Class"] = GetClass(item, itemOID);
2485
                                        string subClass = GetSubClass(item, itemOID);
2486
                                        newRow["SubClass"] = subClass;
2487

    
2488
                                        if (item.ItemType == ItemType.Symbol)
2489
                                            newRow["TYPE"] = item.ID2DBName;
2490
                                        else if (item.ItemType == ItemType.Line)
2491
                                            newRow["TYPE"] = item.ID2DBType;
2492
                                        newRow["PIDNAME"] = group.Document.DrawingName;
2493

    
2494
                                        // NPD
2495
                                        if (item.LineNumber != null)
2496
                                        {
2497
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
2498
                                            if (attribute != null)
2499
                                                newRow["NPD"] = attribute.Value;
2500
                                        }
2501
                                        else
2502
                                            newRow["NPD"] = null;
2503

    
2504
                                        newRow["GROUPTAG"] = GROUPTAG;
2505
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2506
                                        if (branchItem == null)
2507
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2508
                                        else
2509
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
2510

    
2511
                                        newRow["PipeRun_OID"] = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
2512
                                        newRow["EGTConnectedPoint"] = 0;
2513
                                        pathItemsDT.Rows.Add(newRow);
2514
                                    }
2515

    
2516

    
2517
                                    void CreateSequenceDataDataRow(string itemOID)
2518
                                    {
2519
                                        DataRow newRow = sequenceDataDT.NewRow();
2520
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2521
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
2522
                                        newRow["PathItem_OID"] = itemOID;
2523
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2524

    
2525
                                        sequenceDataDT.Rows.Add(newRow);
2526
                                    }
2527

    
2528
                                    void CreatePipeSystemNetworkDataRow()
2529
                                    {
2530
                                        LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
2531
                                        string FluidCode = string.Empty;
2532
                                        if (lineNumber != null)
2533
                                        {
2534
                                            List<Attribute> att = lineNumber.Attributes;
2535
                                            if (att != null)
2536
                                            {
2537
                                                List<string> oid = new List<string>();
2538
                                                FluidCode = att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault() != null ? att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault().Value : string.Empty;
2539
                                                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;
2540
                                                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;
2541
                                                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;
2542
                                                //InsulationPurpose
2543
                                                if (!string.IsNullOrEmpty(FluidCode)) oid.Add(FluidCode);
2544
                                                if (!string.IsNullOrEmpty(PMC)) oid.Add(PMC);
2545

    
2546
                                                string PipeSystem_OID = string.Join("-", oid);
2547

    
2548
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
2549
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
2550

    
2551
                                                string OID = string.Join("-", oid);
2552
                                                string FluidCodeGL = string.Empty;
2553
                                                string PMCGL = string.Empty;
2554

    
2555

    
2556
                                                if (pipelineDT.Select(string.Format("OID = '{0}'", OID)).Count() == 0)
2557
                                                {
2558
                                                    DataRow newPipelineRow = pipelineDT.NewRow();
2559
                                                    newPipelineRow["OID"] = OID;
2560
                                                    newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
2561
                                                    newPipelineRow["FLUID"] = FluidCode;
2562
                                                    newPipelineRow["PMC"] = PMC;
2563
                                                    newPipelineRow["SEQNUMBER"] = SEQNUMBER;
2564
                                                    newPipelineRow["INSULATION"] = INSULATION;
2565
                                                    newPipelineRow["FROM_DATA"] = string.Empty;
2566
                                                    newPipelineRow["TO_DATA"] = string.Empty;
2567
                                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
2568
                                                    pipelineDT.Rows.Add(newPipelineRow);
2569
                                                }
2570

    
2571
                                                if (pipesystemDT.Select(string.Format("OID = '{0}'", PipeSystem_OID)).Count() == 0)
2572
                                                {
2573
                                                    DataRow newPipesystemRow = pipesystemDT.NewRow();
2574
                                                    newPipesystemRow["OID"] = PipeSystem_OID;
2575
                                                    newPipesystemRow["DESCRIPTION"] = string.Empty;
2576
                                                    newPipesystemRow["FLUID"] = FluidCode;
2577
                                                    newPipesystemRow["PMC"] = PMC;
2578
                                                    newPipesystemRow["PipeLineQty"] = string.Empty;
2579
                                                    string GroundLevel = string.Empty;
2580
                                                    if (!string.IsNullOrEmpty(FluidCode) && !string.IsNullOrEmpty(PMC))
2581
                                                    {
2582
                                                        FluidCodeGL = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("GroundLevel");
2583
                                                        PMCGL = PSNPMCDT.Select(string.Format("Code= '{0}'", PMC)).FirstOrDefault().Field<string>("GroundLevel");
2584
                                                        if (FluidCodeGL == "AG" && PMCGL == "AG")
2585
                                                            GroundLevel = "AG";
2586
                                                        else if (FluidCodeGL == "UG" && PMCGL == "UG")
2587
                                                            GroundLevel = "UG";
2588
                                                        else
2589
                                                            GroundLevel = "AG_UG";
2590
                                                    }
2591
                                                    newPipesystemRow["GroundLevel"] = GroundLevel;
2592

    
2593
                                                    pipesystemDT.Rows.Add(newPipesystemRow);
2594
                                                }
2595
                                            }
2596
                                        }
2597

    
2598
                                        DataRow newRow = pipeSystemNetworkDT.NewRow();
2599
                                        newRow["OID"] = PSNItem.PSN_OID();
2600

    
2601
                                        newRow["OrderNumber"] = psnOrder;
2602
                                        newRow["Pipeline_OID"] = item.PSNPipeLineID;
2603
                                        PSNItem.KeywordInfos = KeywordInfos;
2604
                                        PSNItem.Nozzle = Nozzle;
2605

    
2606
                                        string FromType = string.Empty;
2607
                                        Item From_item = new Item();
2608

    
2609
                                        string FROM_DATA = PSNItem.GetFromData(ref FromType, ref From_item);
2610
                                        string status = string.Empty;
2611
                                        status = PSNItem.Status;                                      
2612

    
2613
                                        if (PSNItem.IsKeyword)
2614
                                        {
2615
                                            PSNItem.StartType = PSNType.Equipment;
2616
                                        }
2617
                                        string ToType = string.Empty;
2618
                                        Item To_item = new Item();
2619
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item);
2620
                                        if (PSNItem.IsKeyword)
2621
                                        {
2622
                                            PSNItem.EndType = PSNType.Equipment;
2623
                                        }
2624
                                                   
2625
                                        newRow["FROM_DATA"] = FROM_DATA;
2626
                                        newRow["TO_DATA"] = TO_DATA;
2627
                                       
2628
                                        newRow["Type"] = PSNItem.GetPSNType();
2629

    
2630
                                       
2631
                                        if(psnOrder == 0) //order 0일땐 그냥 붙여줌
2632
                                        {
2633
                                            if (!string.IsNullOrEmpty(PSNItem.Status)) //to에 status가 있다면
2634
                                            {
2635
                                                status += PSNItem.Status;
2636
                                            }                                            
2637
                                        }
2638
                                        else if (psnOrder > 0) //0보다 크면 
2639
                                        {
2640
                                            DataRow dr = pipeSystemNetworkDT.Select(string.Format("OID = '{0}' AND OrderNumber = {1}", PSNItem.PSN_OID(), psnOrder - 1)).FirstOrDefault();
2641
                                            if (psnOrder == 1) //1이면 0번 Order에 From Status 값만 남김 
2642
                                            {
2643
                                                dr["Status"] = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty; //status;
2644
                                            }
2645
                                            if (psnOrder > 1) // 2 -> 1 3->2 엔 status 값 삭제
2646
                                            {
2647
                                                dr["Status"] = string.Empty;
2648
                                            }
2649

    
2650
                                            status = PSNItem.Status;
2651
                                            if (dr != null)
2652
                                            {
2653
                                                newRow["FROM_DATA"] = dr.Field<string>("FROM_DATA");
2654
                                                newRow["TO_DATA"] = dr.Field<string>("TO_DATA");
2655
                                                newRow["Type"] = dr.Field<string>("Type");
2656
                                            }
2657
                                        }
2658

    
2659
                                        
2660
                                    
2661
                                        status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2662
                                        string[] st = status.Split(new string[] { ", " }, StringSplitOptions.None);
2663
                                        if (st.Count() > 1)
2664
                                        {
2665
                                            status = string.Join(", ", st.Distinct());                                                                                     
2666
                                        }
2667
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2668
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
2669

    
2670

    
2671
                                        newRow["IsValid"] = PSNItem.IsValid;
2672
                                        newRow["Status"] = status;
2673
                                        newRow["PBS"] = PSNItem.GetPBSData();
2674

    
2675
                                        List<string> drawingNames = new List<string>();
2676
                                        foreach (Group _group in PSNItem.Groups)
2677
                                        {
2678
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
2679
                                            {
2680
                                                if (drawingNames.Count == 0)
2681
                                                    newRow["Drawings"] = _group.Document.DrawingName;
2682
                                                else
2683
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
2684
                                                drawingNames.Add(_group.Document.DrawingName);
2685
                                            }
2686
                                        }
2687

    
2688
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
2689
                                        if (bVentDrain)
2690
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
2691
                                        else
2692
                                            newRow["IncludingVirtualData"] = "No";
2693
                                        //    return;
2694
                                        //newRow["IncludingVirtualData"] = "No";
2695
                                        newRow["PSNAccuracy"] = "100";
2696

    
2697
                                        string Pocket = "No";
2698
                                        string Condition = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("Condition");
2699
                                        if (Condition.Equals("Flare"))
2700
                                            Pocket = "Yes";
2701

    
2702
                                        if (item.ID2DBType == "Nozzles" && PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null) 
2703
                                        {
2704
                                          //  string itemName = From_item.Name;
2705
                                            Equipment Equipment = From_item.Equipment;
2706
                                      
2707
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name && x.Type != "Pump").FirstOrDefault();
2708
                                          
2709

    
2710
                                            if (nopocket != null)
2711
                                            {
2712
                                                DataRow bNozzle = null;
2713
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2714
                                                {
2715
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, From_item.UID)).FirstOrDefault();
2716
                                                    if (drNozzle != null)
2717
                                                    {
2718
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2719
                                                        {
2720
                                                            bNozzle = drNozzle;
2721
                                                        }
2722

    
2723
                                                        if (bNozzle == null)
2724
                                                        {
2725
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2726

    
2727
                                                            if (drNozzle != null)
2728
                                                            {
2729
                                                                bNozzle = drNozzle;
2730
                                                                foreach (DataRow it in nozzleRows)
2731
                                                                {
2732
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2733
                                                                    {
2734
                                                                        bNozzle = null;
2735
                                                                        break;
2736
                                                                    }
2737
                                                                }
2738
                                                            }
2739
                                                        }
2740
                                                    }
2741

    
2742
                                                    if (bNozzle != null)
2743
                                                        Pocket = "Yes";
2744
                                                }
2745
                                                else
2746
                                                    Pocket = "Yes";
2747
                                            }
2748
                                        }
2749
                                        
2750
                                        if (item.ID2DBType == "Nozzles" && PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null) //To는 전체
2751
                                        {
2752
                                           // string itemName = To_item.Name;
2753
                                            Equipment Equipment = To_item.Equipment;
2754
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name).FirstOrDefault();
2755
                                            if (nopocket != null)
2756
                                            {
2757
                                                DataRow bNozzle = null;
2758
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2759
                                                {
2760
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, To_item.UID)).FirstOrDefault();
2761
                                                    if(drNozzle != null)
2762
                                                    {
2763
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2764
                                                        {
2765
                                                            bNozzle = drNozzle;
2766
                                                        }
2767

    
2768
                                                        if (bNozzle == null)
2769
                                                        {
2770
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2771

    
2772
                                                            if (drNozzle != null)
2773
                                                            {
2774
                                                                bNozzle = drNozzle;
2775
                                                                foreach (DataRow it in nozzleRows)
2776
                                                                {
2777
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2778
                                                                    {
2779
                                                                        bNozzle = null;
2780
                                                                        break;
2781
                                                                    }
2782
                                                                }
2783
                                                            }
2784
                                                        }
2785
                                                    }                                                   
2786

    
2787
                                                    if (bNozzle != null)
2788
                                                        Pocket = "Yes";
2789
                                                }
2790
                                                else
2791
                                                    Pocket = "Yes";
2792
                                            }
2793
                                        }
2794
                                        
2795
                                        newRow["Pocket"] = Pocket;
2796
                                        string AFC = "P2";
2797
                                        if(PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null)
2798
                                        {
2799
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2800
                                                AFC = "P1\\" + From_item.Equipment.Name;
2801
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2802
                                                newRow["PUMP"] = "PUMP";
2803
                                        }
2804

    
2805
                                        if (PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null)
2806
                                        {
2807
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2808
                                                AFC = "P1\\" + To_item.Equipment.Name;
2809
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2810
                                                newRow["PUMP"] = "PUMP";
2811
                                        }
2812

    
2813
                                        newRow["AFC"] = AFC;
2814

    
2815
                                        newRow["EGTag"] = string.Empty;
2816
                                        newRow["HasMLTags"] = "False";
2817
                                        pipeSystemNetworkDT.Rows.Add(newRow);
2818
                                    }
2819
                                }
2820

    
2821
                            }
2822
                        
2823

    
2824
                        }
2825
                        catch (Exception ex)
2826
                        {
2827
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2828
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2829
                        }
2830

    
2831
                        //TopologySet 관련
2832
                        foreach (Topology topology in PSNItem.Topologies)
2833
                        {
2834
                            DataRow newRow = topologySetDT.NewRow();
2835
                            newRow["OID"] = topology.FullName;
2836
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
2837
                            if (bVentDrain)
2838
                                newRow["SubType"] = "Vent_Drain";
2839
                            else
2840
                                newRow["SubType"] = null;
2841
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
2842
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
2843
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
2844
                            newRow["TailItemSPID"] = topology.Items.First().UID;
2845
                            topologySetDT.Rows.Add(newRow);
2846
                        }
2847

    
2848
                    }
2849
                    catch (Exception ee)
2850
                    {
2851

    
2852
                    }
2853
                }
2854

    
2855

    
2856
                foreach (var item in startBranchDic)
2857
                {
2858
                    string uid = item.Key.UID;
2859
                    string topologyName = item.Value.Topology.FullName;
2860
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2861

    
2862
                    if (rows.Length == 1)
2863
                    {
2864
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2865
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2866
                    }
2867
                    else if (rows.Length > 1)
2868
                    {
2869
                        DataRow targetRow = null;
2870
                        int index = int.MaxValue;
2871
                        foreach (DataRow row in rows)
2872
                        {
2873
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2874
                            if (split.StartsWith("L"))
2875
                            {
2876
                                int num = Convert.ToInt32(split.Remove(0, 1));
2877
                                if (index > num)
2878
                                {
2879
                                    index = num;
2880
                                    targetRow = row;
2881
                                }
2882
                            }
2883
                        }
2884

    
2885
                        if (targetRow != null)
2886
                        {
2887
                            targetRow["BranchTopologySet_OID"] = topologyName;
2888
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2889
                        }
2890
                    }
2891
                }
2892

    
2893
                foreach (var item in endBranchDic)
2894
                {
2895
                    string uid = item.Key.UID;
2896
                    string topologyName = item.Value.Topology.FullName;
2897
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2898
                    if (rows.Length == 1)
2899
                    {
2900
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2901
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2902
                    }
2903
                    else if (rows.Length > 1)
2904
                    {
2905
                        DataRow targetRow = null;
2906
                        int index = int.MinValue;
2907
                        foreach (DataRow row in rows)
2908
                        {
2909
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2910
                            if (split.StartsWith("L"))
2911
                            {
2912
                                int num = Convert.ToInt32(split.Remove(0, 1));
2913
                                if (index < num)
2914
                                {
2915
                                    index = num;
2916
                                    targetRow = row;
2917
                                }
2918
                            }
2919
                        }
2920

    
2921
                        if (targetRow != null)
2922
                        {
2923
                            targetRow["BranchTopologySet_OID"] = topologyName;
2924
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2925
                        }
2926
                    }
2927
                }
2928

    
2929
                PathItems = pathItemsDT;
2930
                SequenceData = sequenceDataDT;
2931
                PipeSystemNetwork = pipeSystemNetworkDT;
2932
                TopologySet = topologySetDT;
2933
                PipeLine = pipelineDT;
2934
                PipeSystem = pipesystemDT;
2935
            }
2936
            catch (Exception ex)
2937
            {
2938
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2939
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2940
            }
2941
        }
2942

    
2943
        private double AccuracyCalculation(List<double> lstAcc, double acc)
2944
        {
2945
            foreach (double lacc in lstAcc)
2946
            {
2947
                acc *= lacc;
2948
            }
2949
            return acc;
2950
        }
2951

    
2952
        private void UpdateSubType()
2953
        {
2954
            try
2955
            {
2956
                foreach (PSNItem PSNItem in PSNItems)
2957
                {
2958
                    if (PSNItem.IsBypass)
2959
                    {
2960
                        foreach (Topology topology in PSNItem.Topologies)
2961
                        {
2962
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2963
                            if (rows.Length.Equals(1))
2964
                                rows.First()["SubType"] = "Bypass";
2965
                        }
2966
                    }
2967

    
2968
                    if (PSNItem.StartType == PSNType.Header)
2969
                    {
2970
                        Topology topology = PSNItem.Topologies.First();
2971
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2972
                        if (rows.Length.Equals(1))
2973
                            rows.First()["SubType"] = "Header";
2974
                    }
2975
                    else if (PSNItem.EndType == PSNType.Header)
2976
                    {
2977
                        Topology topology = PSNItem.Topologies.Last();
2978
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2979
                        if (rows.Length.Equals(1))
2980
                            rows.First()["SubType"] = "Header";
2981
                    }
2982
                }
2983

    
2984

    
2985
                foreach (Topology topology in Topologies)
2986
                {
2987
                    try
2988
                    {
2989
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2990

    
2991
                        if (rows.Count() > 0)
2992
                        {
2993
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
2994
                            {
2995
                                if (topology.Items == null)
2996
                                    continue;
2997

    
2998
                                Item firstItem = topology.Items.First();
2999
                                Item lastItem = topology.Items.Last();
3000

    
3001
                                List<Relation> relations = new List<Relation>();
3002

    
3003
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
3004
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
3005

    
3006
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
3007
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
3008

    
3009
                                if (relations.Count > 0)
3010
                                    rows.First()["SubType"] = "OtherSystem";
3011
                            }
3012
                        }
3013
                    }
3014
                    catch (Exception ex)
3015
                    {
3016

    
3017
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
3018
                    }
3019
                }
3020

    
3021
                foreach (DataRow row in TopologySet.Rows)
3022
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
3023
                        row["SubType"] = "Normal";
3024
            }
3025
            catch (Exception ex)
3026
            {
3027
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
3028
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
3029
            }
3030
        }
3031

    
3032
        private bool IsBypass(PSNItem PSNItem)
3033
        {
3034
            bool bResult = false;
3035

    
3036
            if (PSNItem.GetPSNType() == "B2B")
3037
            {
3038
                Group firstGroup = PSNItem.Groups.First();
3039
                Group lastGroup = PSNItem.Groups.Last();
3040
                Item firstItem = firstGroup.Items.First();
3041
                Item lastItem = lastGroup.Items.Last();
3042

    
3043
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
3044
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
3045

    
3046
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
3047
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
3048
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
3049
                    bResult = true;
3050
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
3051
                    bResult = true;
3052
            }
3053

    
3054
            Item GetConnectedItemByPSN(Item item)
3055
            {
3056
                Item result = null;
3057

    
3058
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
3059
                if (relation != null)
3060
                    result = relation.Item;
3061

    
3062

    
3063
                return result;
3064
            }
3065

    
3066
            return bResult;
3067
        }
3068

    
3069
        private void DeleteVentDrain()
3070
        {
3071
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
3072

    
3073
            foreach (DataRow dataRow in ventdrainRows)
3074
            {
3075
                dataRow.Delete();
3076
            }
3077
        }
3078

    
3079
        private void UpdateAccuracy()
3080
        {
3081
            //DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
3082
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'");
3083
            List<double> lstAcc = null;
3084
            string Status = string.Empty;
3085

    
3086
            foreach (DataRow dataRow in statusRows)
3087
            {
3088
                lstAcc = new List<double>();
3089
                Status = dataRow.Field<string>("Status");
3090
                if (!string.IsNullOrEmpty(Status))
3091
                {
3092
                    string[] arrStatus = Status.Split(',');
3093
                    foreach (string arrstr in arrStatus)
3094
                    {
3095
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
3096
                            lstAcc.Add(0.75);
3097

    
3098
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
3099
                            lstAcc.Add(0.7);
3100

    
3101
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
3102
                            lstAcc.Add(0.5);
3103

    
3104
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
3105
                            lstAcc.Add(0.65);
3106

    
3107
                        if (arrstr.Contains(Rule5)) //Line Disconnected
3108
                            lstAcc.Add(0.6);
3109
                    }
3110
                }
3111

    
3112
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
3113
                if (PSNAccuracy == "100")
3114
                    PSNAccuracy = "1";
3115

    
3116
                PSNAccuracy = Convert.ToString(Convert.ToDecimal(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))));
3117
                //if (PSNAccuracy != "100")
3118
                //{
3119
                //    //dataRow["IncludingVirtualData"] = "No";
3120
                dataRow["PSNAccuracy"] = PSNAccuracy;
3121
                //}
3122
            }
3123
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
3124
            foreach (DataRow dr in dt.Rows)
3125
            {
3126
                string oid = dr.Field<string>("OID");
3127
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
3128
                double totalDdr = 0;
3129
                foreach (DataRow ddr in select)
3130
                {
3131
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
3132
                    if (acc == 100) acc = 1;
3133
                    if (totalDdr == 0) totalDdr = acc;
3134
                    else totalDdr *= acc;
3135
                }
3136

    
3137
                totalDdr *= 100;
3138

    
3139
                if (totalDdr != 100)
3140
                {
3141
                    foreach (DataRow ddr in select)
3142
                    {
3143
                        ddr["IncludingVirtualData"] = "Yes";
3144
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
3145
                        ddr["IsValid"] = "Error";
3146
                    }
3147
                }
3148
                else
3149
                {
3150
                    foreach (DataRow ddr in select)
3151
                    {
3152
                        ddr["IncludingVirtualData"] = "No";
3153
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
3154
                    }
3155
                }
3156
            }
3157

    
3158
        }
3159

    
3160
        private void UpdateKeywordForPSN()
3161
        {
3162
            #region Keyword Info
3163
            KeywordInfo KeywordInfos = new KeywordInfo();
3164
            DataTable dtKeyword = DB.SelectKeywordsSetting();
3165
            foreach (DataRow row in dtKeyword.Rows)
3166
            {
3167
                int index = Convert.ToInt32(row["INDEX"]);
3168
                string name = row["NAME"].ToString();
3169
                string keyword = row["KEYWORD"].ToString();
3170

    
3171
                //KeywordInfo keywordInfo = new KeywordInfo();   
3172
                KeywordInfos.KeywordItems.Add(new KeywordItem()
3173
                {
3174
                    Index = index,
3175
                    Name = name,
3176
                    Keyword = keyword
3177
                });
3178
            }
3179
            #endregion
3180

    
3181
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
3182
            foreach (DataRow dataRow in endofHeaderRows)
3183
            {
3184
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3185

    
3186
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
3187
                {
3188
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3189
                    DataRow dr = pathItemRows.First();
3190
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
3191
                    dr["TYPE"] = "End";
3192
                    dr["ITEMTAG"] = "ENDOFHEADER";
3193
                    dr["DESCRIPTION"] = "ENDOFHEADER";
3194
                }
3195

    
3196
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
3197
                {
3198
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3199
                    DataRow dr = pathItemRows.Last();
3200
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
3201
                    dr["TYPE"] = "End";
3202
                    dr["ITEMTAG"] = "ENDOFHEADER";
3203
                    dr["DESCRIPTION"] = "ENDOFHEADER";
3204
                }
3205
            }
3206

    
3207
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3208
            {
3209
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
3210
                foreach (DataRow dataRow in keywordRows)
3211
                {
3212
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3213

    
3214
                    if (dataRow.Field<string>("From_Data") == keyitem.Keyword)
3215
                    {
3216
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3217

    
3218
                        //
3219
                        //if(.)
3220
                        if (PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
3221
                        {
3222
                            DataRow dr = pathItemRows.First();
3223
                            //dr["CLASS"] = ""; //Type
3224
                            dr["TYPE"] = "End";
3225
                            dr["ITEMTAG"] = keyitem.Keyword;
3226
                            dr["DESCRIPTION"] = keyitem.Keyword;
3227
                        }
3228

    
3229
                    }
3230

    
3231
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
3232
                    {
3233
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3234

    
3235
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
3236
                        {
3237
                            DataRow dr = pathItemRows.Last();
3238
                            //dr["CLASS"] = ""; //Type
3239
                            dr["TYPE"] = "End";
3240
                            dr["ITEMTAG"] = keyitem.Keyword;
3241
                            dr["DESCRIPTION"] = keyitem.Keyword;
3242
                            //dr.Field<string>("Type")
3243
                        }
3244

    
3245
                    }
3246
                }
3247
            }
3248
        }
3249

    
3250
        private void UpdateErrorForPSN()
3251
        {
3252
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
3253
            foreach (DataRow dataRow in errorRows)
3254
            {
3255
                try
3256
                {
3257
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3258
                   
3259
                    bool change = false;
3260
                    bool bCheck = false;
3261
                    if (!PSNItem.EnableType(PSNItem.StartType))
3262
                    {
3263
                        change = true;
3264
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3265
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3266

    
3267
                        Item item = PSNItem.Groups.First().Items.First();
3268
                        try
3269
                        {
3270
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
3271

    
3272
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3273
                            {
3274
                                loopRow["FROM_DATA"] = FROM_DATA;
3275
                                if (item.ItemType == ItemType.Line)
3276
                                {
3277
                                    if (loopRow.Field<string>("OrderNumber") == "0")
3278
                                    {
3279
                                        string status = loopRow.Field<string>("Status");
3280
                                        //string isvali
3281
                                        if (string.IsNullOrEmpty(status))
3282
                                            status = "Line Disconnected";
3283
                                        else if (!status.Contains("Line Disconnected"))
3284
                                            status += ", Line Disconnected";
3285
                                        loopRow["Status"] = status;
3286
                                        if (!string.IsNullOrEmpty(status))
3287
                                            loopRow["IsValid"] = "Error";
3288
                                    }
3289
                                }
3290
                            }
3291

    
3292
                            tieInPointIndex++;
3293

    
3294
                            if (item.ItemType == ItemType.Line)
3295
                            {
3296
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);                                
3297
                            }
3298
                            else
3299
                            {
3300
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
3301
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
3302

    
3303
                                bCheck = true;
3304
                            }
3305

    
3306
                            PSNItem.StartType = PSNType.Equipment;
3307
                        }
3308
                        catch (Exception ex)
3309
                        {
3310
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3311
                            return;
3312
                        }
3313
                    }
3314

    
3315
                    if (!PSNItem.EnableType(PSNItem.EndType))
3316
                    {                        
3317
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3318
                        //int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
3319
                        DataRow dr = pathItemRows.Last();
3320
                        if (change)
3321
                        {
3322
                            if(bCheck)
3323
                                dr = pathItemRows[pathItemRows.Count() - 3];
3324
                            else
3325
                            {
3326
                                dr = pathItemRows[pathItemRows.Count() - 2];
3327
                            }
3328
                        }
3329

    
3330
                        change = true;
3331
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3332

    
3333
                        Item item = PSNItem.Groups.Last().Items.Last();
3334
                        try
3335
                        {
3336
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
3337

    
3338
                            
3339
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3340
                            {
3341
                                loopRow["TO_DATA"] = TO_DATA;
3342
                                if (item.ItemType == ItemType.Line)
3343
                                {
3344
                                    if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
3345
                                    {
3346
                                        string status = loopRow.Field<string>("Status");
3347
                                        if (string.IsNullOrEmpty(status))
3348
                                            status = "Line Disconnected";
3349
                                        else if (!status.Contains("Line Disconnected"))
3350
                                            status += ", Line Disconnected";
3351
                                        loopRow["Status"] = status;
3352
                                        if (!string.IsNullOrEmpty(status))
3353
                                            loopRow["IsValid"] = "Error";
3354
                                    }
3355
                                }
3356

    
3357
                            }                            
3358

    
3359
                            tieInPointIndex++;
3360

    
3361
                            if (item.ItemType == ItemType.Line)
3362
                            {
3363
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3364
                            }
3365
                            else
3366
                            {
3367
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3368
                                if(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Count() > 0)
3369
                                    PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last()), insertIndex);
3370
                               
3371
                            }
3372

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

    
3382
                    dataRow["Type"] = PSNItem.GetPSNType();
3383
                    if (change)
3384
                    {
3385
                        int rowIndex = 0;
3386
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3387
                        {
3388
                            DataRow row = PathItems.Rows[i];
3389
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
3390
                                continue;
3391
                            string sequenceData = row["SequenceData_OID"].ToString();
3392
                            string[] split = sequenceData.Split(new char[] { '_' });
3393

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

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

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

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

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

    
3447
                    DataRow createLineRow(DataRow itemRow)
3448
                    {
3449
                        DataRow newRow = PathItems.NewRow();
3450
                        newRow["OID"] = Guid.NewGuid().ToString();
3451
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3452
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3453
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3454
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3455
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
3456
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3457
                        newRow["Class"] = itemRow["Class"];
3458
                        newRow["SubClass"] = itemRow["SubClass"];
3459
                        newRow["TYPE"] = itemRow["TYPE"];
3460
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3461
                        newRow["NPD"] = itemRow["NPD"];
3462
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3463
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3464
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3465
                        newRow["EGTConnectedPoint"] = "0";
3466
                        return newRow;
3467
                    }
3468
                }
3469
                catch (Exception ex)
3470
                {
3471

    
3472
                }
3473
            }
3474
        }
3475

    
3476
        private void InsertTeePSN()
3477
        {
3478
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
3479
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
3480
            bool change = false;
3481
            foreach (DataRow dataRow in branchRows)
3482
            {
3483
                try
3484
                {
3485
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3486
                    change = false;
3487

    
3488
                    if (PSNItem.StartType == PSNType.Branch)
3489
                    {
3490
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3491
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3492
                        Item Teeitem = PSNItem.Groups.First().Items.First();
3493
                        try
3494
                        {
3495
                            if (Teeitem.ItemType == ItemType.Line)
3496
                            {
3497
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
3498
                                {
3499
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
3500
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
3501
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3502
                                    change = true;
3503
                                }
3504

    
3505
                            }
3506
                        }
3507
                        catch (Exception ex)
3508
                        {
3509
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3510
                            return;
3511
                        }
3512
                    }
3513

    
3514
                    if (PSNItem.EndType == PSNType.Branch)
3515
                    {
3516
                        //change = true;
3517
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3518

    
3519
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
3520

    
3521
                        DataRow dr = pathItemRows.Last();
3522
                        if (change)
3523
                            dr = pathItemRows[pathItemRows.Count() - 2];
3524

    
3525
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3526

    
3527
                        try
3528
                        {
3529
                            if (Teeitem.ItemType == ItemType.Line)
3530
                            {
3531
                                if (dr.Field<string>("SubClass") != "Tee")
3532
                                {
3533
                                    PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
3534
                                    change = true;
3535
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
3536
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3537
                                }
3538

    
3539
                            }
3540
                        }
3541
                        catch (Exception ex)
3542
                        {
3543
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3544
                            return;
3545
                        }
3546
                    }
3547

    
3548
                    if (change)
3549
                    {
3550
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3551
                        int rowIndex = 0;
3552
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3553
                        {
3554
                            DataRow row = PathItems.Rows[i];
3555
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
3556
                                continue;
3557
                            string sequenceData = row["SequenceData_OID"].ToString();
3558
                            string[] split = sequenceData.Split(new char[] { '_' });
3559

    
3560
                            StringBuilder sb = new StringBuilder();
3561
                            for (int j = 0; j < split.Length - 1; j++)
3562
                                sb.Append(split[j] + "_");
3563
                            sb.Append(rowIndex++);
3564
                            row["SequenceData_OID"] = sb.ToString();
3565

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

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

    
3571
                            if (seqItemRows == null)
3572
                            {
3573
                                DataRow newRow = SequenceData.NewRow();
3574
                                newRow["OID"] = sb.ToString();
3575
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3576
                                newRow["PathItem_OID"] = row["OID"];
3577
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3578
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3579
                            }
3580
                            else
3581
                            {
3582
                                seqItemRows["OID"] = sb.ToString();
3583
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3584
                                seqItemRows["PathItem_OID"] = row["OID"];
3585
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3586
                            }
3587
                        }
3588
                    }
3589

    
3590
                    DataRow createTeeRow(DataRow itemRow)
3591
                    {
3592
                        DataRow newRow = PathItems.NewRow();
3593
                        newRow["OID"] = Guid.NewGuid().ToString();
3594
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3595
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3596
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3597
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3598
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
3599
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3600
                        newRow["DESCRIPTION"] = "";
3601
                        newRow["Class"] = "Branch";
3602
                        newRow["SubClass"] = "Tee";
3603
                        newRow["TYPE"] = itemRow["TYPE"];
3604
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3605
                        newRow["NPD"] = itemRow["NPD"];
3606
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3607
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3608
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3609
                      
3610
                        newRow["EGTConnectedPoint"] = 0;
3611
                        return newRow;
3612
                    }
3613
                }
3614
                catch (Exception ex)
3615
                {
3616

    
3617
                }
3618
            }
3619
        }
3620
    }
3621

    
3622
    public class PSNItem
3623
    {
3624
        public PSNItem(int count, int Revision)
3625
        {
3626
            Groups = new List<Group>();
3627
            Topologies = new List<Topology>();
3628

    
3629
            Index = count + 1;
3630
            this.Revision = Revision;
3631
        }
3632

    
3633
        private int Revision;
3634
        public string UID { get; set; }
3635
        public List<Group> Groups { get; set; }
3636
        public List<Topology> Topologies { get; set; }
3637
        public PSNType StartType { get; set; }
3638
        public PSNType EndType { get; set; }
3639
        public int Index { get; set; }
3640
        public string IsValid { get; set; }
3641
        public bool IsKeyword { get; set; }
3642
        public string Status { get; set; }
3643
        public string IncludingVirtualData { get; set; }
3644
        public string PSNAccuracy { get; set; }
3645
        public KeywordInfo KeywordInfos = new KeywordInfo();
3646
        public DataTable Nozzle = new DataTable();
3647

    
3648
        public string PSN_OID()
3649
        {
3650
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
3651
        }
3652

    
3653
        public string GetPSNType()
3654
        {
3655
            string result = string.Empty;
3656

    
3657
            if (EnableType(StartType) && EnableType(EndType))
3658
            {
3659
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
3660
                    result = "E2E";
3661
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
3662
                    result = "B2B";
3663
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
3664
                    result = "HD2";
3665

    
3666
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
3667
                    result = "E2B";
3668
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
3669
                    result = "B2E";
3670

    
3671
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
3672
                    result = "HDB";
3673
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
3674
                    result = "HDB";
3675

    
3676
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
3677
                    result = "HDE";
3678
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
3679
                    result = "HDE";
3680
                else
3681
                    result = "Error";
3682
            }
3683
            else
3684
                result = "Error";
3685

    
3686
            return result;
3687

    
3688

    
3689
        }
3690

    
3691
        public bool EnableType(PSNType type)
3692
        {
3693
            bool result = false;
3694

    
3695
            if (type == PSNType.Branch ||
3696
                type == PSNType.Equipment ||
3697
                type == PSNType.Header)
3698
            {
3699
                result = true;
3700
            }
3701

    
3702
            return result;
3703
        }
3704

    
3705
        public bool IsBypass { get; set; }
3706

    
3707
        public string GetFromData(ref string Type, ref Item item)
3708
        {
3709
            Status = string.Empty;
3710
            string result = string.Empty;
3711
            if (IsKeyword)
3712
                IsKeyword = false;
3713
            try
3714
            {
3715
                item = Groups.First().Items.First();
3716

    
3717
                if (StartType == PSNType.Header)
3718
                    result = "ENDOFHEADER";
3719
                else if (StartType == PSNType.Branch)
3720
                {
3721
                    if (item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
3722
                    {
3723
                        result = item.Relations.First().Item.LineNumber.Name;
3724
                        if (item.Relations.First().Item.LineNumber.MissingLineNumber2)
3725
                        {
3726
                            Status += ", Missing LineNumber_2";
3727
                            IsValid = "Error";
3728
                        }
3729
                        if (item.Relations.First().Item.LineNumber.MissingLineNumber1)
3730
                        {
3731
                            Status += ", Missing LineNumber_1";
3732
                            IsValid = "Error";
3733
                        }
3734
                    }
3735
                    else
3736
                    {
3737
                        IsValid = "Error";
3738
                        result = "Empty LineNumber";
3739
                    }
3740
                }
3741
                else if (StartType == PSNType.Equipment)
3742
                {
3743
                    if (Groups.First().Items.First().Equipment != null)
3744
                        result = Groups.First().Items.First().Equipment.ItemTag;
3745
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
3746

    
3747
                    if (drNozzle != null)
3748
                        result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3749
                }
3750
                else
3751
                {
3752
                    
3753
                    item = Groups.First().Items.First();
3754
                    if (item.ItemType == ItemType.Symbol)
3755
                    {
3756
                        string keyword = string.Empty;
3757
                        keyword = GetFromKeywordData(ref Type, item);
3758

    
3759
                        if (string.IsNullOrEmpty(keyword))
3760
                        {
3761
                            if (item.ID2DBType.Contains("OPC's"))
3762
                                Status += ", OPC Disconnected";
3763
                            else
3764
                                Status += ", Missing ItemTag or Description";
3765

    
3766
                            result = item.ID2DBName;
3767
                            IsValid = "Error";
3768
                        }
3769
                        else
3770
                        {
3771
                            result = keyword;
3772
                            IsKeyword = true;
3773
                        }
3774

    
3775
                    }
3776
                    else if (item.ItemType == ItemType.Line)
3777
                    {
3778
                        if (item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name))
3779
                        {
3780
                            result = item.LineNumber.Name;
3781
                            if (item.LineNumber.MissingLineNumber2)
3782
                            {
3783
                                Status += ", Missing LineNumber_2";
3784
                                IsValid = "Error";
3785
                            }
3786
                            if (item.LineNumber.MissingLineNumber1)
3787
                            {
3788
                                Status += ", Missing LineNumber_1";
3789
                                IsValid = "Error";
3790
                            }
3791
                        }
3792
                        else
3793
                        {
3794
                            IsValid = "Error";
3795
                            result = "Empty LineNumber";
3796
                        }
3797
                    }
3798
                    else
3799
                        result = "Unknown";
3800
                }
3801
            }
3802
            catch (Exception ex)
3803
            {
3804

    
3805
            }
3806

    
3807
            return result;
3808
        }
3809

    
3810
        public string GetFromKeywordData(ref string Type, Item item)
3811
        {
3812
            string result = string.Empty;
3813

    
3814
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3815
            {
3816
                if (keyitem.Name.Equals(item.Name))
3817
                {
3818
                    result = keyitem.Keyword;
3819
                    Type = item.ID2DBType;
3820
                    break;
3821
                }
3822
            }
3823

    
3824
            return result;
3825
        }
3826

    
3827
        public string GetToKeywordData(ref string Type, Item item)
3828
        {
3829
            string result = string.Empty;
3830

    
3831
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3832
            {
3833
                if (keyitem.Name.Equals(item.Name))
3834
                {
3835
                    result = keyitem.Keyword;
3836
                    Type = item.ID2DBType;
3837
                    break;
3838
                }
3839
            }
3840
            return result;
3841
        }
3842

    
3843
        public string GetToData(ref string ToType, ref Item item)
3844
        {
3845
            string result = string.Empty;
3846
            Status = string.Empty;
3847

    
3848
            if (IsKeyword)
3849
                IsKeyword = false;
3850

    
3851
            item = Groups.Last().Items.Last();
3852

    
3853
            if (EndType == PSNType.Header)
3854
                result = "ENDOFHEADER";
3855
            else if (EndType == PSNType.Branch)
3856
            {
3857
                if (item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
3858
                {
3859
                    result = item.Relations.Last().Item.LineNumber.Name;
3860
                    if (item.Relations.Last().Item.LineNumber.MissingLineNumber2)
3861
                    {
3862
                        Status += ", Missing LineNumber_2";
3863
                        IsValid = "Error";
3864
                    }
3865
                    if (item.Relations.Last().Item.LineNumber.MissingLineNumber1)
3866
                    {
3867
                        Status += ", Missing LineNumber_1";
3868
                        IsValid = "Error";
3869
                    }
3870
                }
3871
                else
3872
                {
3873
                    IsValid = "Error";
3874
                    result = "Empty LineNumber";
3875
                }                
3876
            }
3877
            else if (EndType == PSNType.Equipment)
3878
            {
3879
                if (Groups.Last().Items.Last().Equipment != null)
3880
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
3881

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

    
3884
                if (drNozzle != null)
3885
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3886
            }
3887
            else
3888
            {
3889
                
3890
                item = Groups.Last().Items.Last();
3891
                if (item.ItemType == ItemType.Symbol)
3892
                {
3893
                    string keyword = string.Empty;
3894
                    keyword = GetToKeywordData(ref ToType, item);
3895

    
3896
                    if (string.IsNullOrEmpty(keyword))
3897
                    {
3898
                        if (item.ID2DBType.Contains("OPC's"))
3899
                            Status += ", OPC Disconnected";
3900
                        else
3901
                            Status += ", Missing ItemTag or Description";
3902

    
3903
                        result = item.ID2DBName;
3904
                        IsValid = "Error";
3905
                    }
3906
                    else
3907
                    {
3908
                        result = keyword;
3909
                        IsKeyword = true;
3910
                    }
3911

    
3912
                }
3913
                else if (item.ItemType == ItemType.Line)
3914
                {
3915
                    if (item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name))
3916
                    {
3917
                        result = item.LineNumber.Name;
3918
                        if (item.LineNumber.MissingLineNumber2)
3919
                        {
3920
                            Status += ", Missing LineNumber_2";
3921
                            IsValid = "Error";
3922
                        }
3923
                        if (item.LineNumber.MissingLineNumber1)
3924
                        {
3925
                            Status += ", Missing LineNumber_1";
3926
                            IsValid = "Error";
3927
                        }
3928
                    }
3929
                    else
3930
                    {
3931
                        IsValid = "Error";
3932
                        result = "Empty LineNumber";
3933
                    }
3934
                }
3935
                else
3936
                    result = "Unknown";
3937
            }
3938
            return result;
3939
        }
3940

    
3941
        public string GetPBSData()
3942
        {
3943
            string result = string.Empty;
3944
            List<string> PBSList = new List<string>();
3945
            if (Settings.Default.PBSSetting.Equals("Line Number"))
3946
            {
3947
                string attrValue = Settings.Default.PBSSettingValue;
3948

    
3949
                foreach (Group group in Groups)
3950
                {
3951
                    List<LineNumber> lineNumbers = group.Items.Select(x => x.LineNumber).Distinct().ToList();
3952
                    foreach (LineNumber lineNumber in lineNumbers)
3953
                    {
3954
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
3955
                        if (attribute != null)
3956
                        {
3957
                            string value = attribute.Value;
3958
                            if (!PBSList.Contains(value))
3959
                                PBSList.Add(value);
3960
                        }
3961
                    }
3962
                }
3963
            }
3964
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
3965
            {
3966
                string attrValue = Settings.Default.PBSSettingValue;
3967

    
3968
                foreach (Group group in Groups)
3969
                {
3970
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
3971
                    foreach (Item item in items)
3972
                    {
3973
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
3974
                        if (!PBSList.Contains(value))
3975
                            PBSList.Add(value);
3976
                    }
3977
                }
3978
            }
3979
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
3980
            {
3981
                string attrValue = Settings.Default.PBSSettingValue;
3982

    
3983
                foreach (Group group in Groups)
3984
                {
3985
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3986
                    foreach (Document document in documents)
3987
                    {
3988
                        string name = document.DrawingName;
3989

    
3990
                        int startIndex = Settings.Default.PBSSettingStartValue;
3991
                        int endIndex = Settings.Default.PBSSettingEndValue;
3992

    
3993
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
3994
                        if (!PBSList.Contains(subStr))
3995
                            PBSList.Add(subStr);
3996
                    }
3997
                }
3998
            }
3999
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
4000
            {
4001
                foreach (Group group in Groups)
4002
                {
4003
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
4004
                    foreach (Document document in documents)
4005
                    {
4006
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
4007
                        foreach (TextInfo textInfo in textInfos)
4008
                        {
4009
                            if (!PBSList.Contains(textInfo.Value))
4010
                                PBSList.Add(textInfo.Value);
4011
                        }
4012
                    }
4013
                }
4014
            }
4015

    
4016
            foreach (var item in PBSList)
4017
            {
4018
                if (string.IsNullOrEmpty(result))
4019
                    result = item;
4020
                else
4021
                    result += ", " + item;
4022
            }
4023
            return result;
4024
        }
4025
    }
4026
}
클립보드 이미지 추가 (최대 크기: 500 MB)