프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / ID2PSN / PSN.cs @ 7d6d1693

이력 | 보기 | 이력해설 | 다운로드 (192 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(); //test
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
            // 확도 계산
277
            splashScreenManager1.SetWaitFormDescription(i++ + " / 19  UpdateAccuracy ( 95 % )");
278
            UpdateAccuracy();
279

    
280
            //UpdatePSNType();
281

    
282
        }
283

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

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

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

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

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

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

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

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

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

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

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

    
385
                    string EGTAG = "EGTAG";
386
                   // string ItemTag = "ItemTag";
387
                    string EGFlowDirection = string.Empty;
388
                    string Prefix = string.Empty;
389
                    string SymbolName = string.Empty;
390

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

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

    
416
                            SymbolName = PSNItem.Groups.Last().Items.Last().Equipment.Name;
417
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;                            
418
                            EGFlowDirection = "I";
419
                        }
420
                    }
421

    
422
                    //Attribute가 세팅되어있지 않다면
423
                    if (EGTAG.Equals("EGTAG"))
424
                    {
425
                        if (!eqkeyValuePairs.ContainsKey(SymbolName))
426
                        {
427
                            if (!string.IsNullOrEmpty(Prefix))
428
                            {
429
                                pumpTagNum++;
430
                                EGTAG = Prefix + string.Format("-{0}", string.Format("{0:D5}", pumpTagNum));
431
                                eqkeyValuePairs.Add(SymbolName, EGTAG);
432
                            }
433
                            else
434
                            {
435
                                eqkeyValuePairs.Add(SymbolName, SymbolName);
436
                            }
437
                        }
438
                        else
439
                        {
440
                            EGTAG = eqkeyValuePairs[SymbolName];
441
                        }
442
                    }
443
                    else
444
                    {
445
                        if (!string.IsNullOrEmpty(Prefix))
446
                            EGTAG = Prefix + "-" + EGTAG;
447
                    }
448

    
449

    
450
                    foreach (DataRow dr in pathItemRows)
451
                    {
452
                        dr["EqpGroupTag"] = EGTAG;
453
                        dr["EGFlowDirection"] = EGFlowDirection;
454
                    }
455
                }
456

    
457
                // 3, 4번
458
                foreach (DataRow dataRow in pumpRows) 
459
                {
460

    
461
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
462
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
463
                    string EGFlowDirection = string.Empty;
464

    
465
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
466
                    {
467
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
468
                        {
469
                            EGFlowDirection = "O";
470
                        }
471
                    }
472
                    
473
                    if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
474
                    {
475
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
476
                        {
477
                            EGFlowDirection = "I";
478
                        }
479
                    }
480

    
481

    
482
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
483

    
484
                    foreach (DataRow dr in pathItemRows)
485
                    {
486
                        if(dr.Field<string>("ViewPipeSystemNetwork_OID") != dataRow["OID"].ToString())
487
                        {
488
                            string viewEGFlowDirection = string.Empty;
489
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}'", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
490
                            {
491
                                PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));                               
492

    
493
                                if (viewPSNItem.Groups.First().Items.First().Equipment != null)
494
                                {
495
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
496
                                    {
497
                                        viewEGFlowDirection = "O";
498
                                    }
499
                                }
500
                                
501
                                
502
                                if (string.IsNullOrEmpty(viewEGFlowDirection) && viewPSNItem.Groups.Last().Items.Last().Equipment != null)
503
                                {
504
                                    if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && viewPSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
505
                                    {
506
                                        viewEGFlowDirection = "I";
507
                                    }
508
                                }
509

    
510
                                if (EGFlowDirection.Equals(viewEGFlowDirection) && !lstViewPipeSystemNetwork_OID.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
511
                                    lstViewPipeSystemNetwork_OID.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
512
                            }
513
                            else
514
                            {
515
                            }
516
                        }
517
                    }
518

    
519
                    string selectViewOID = string.Empty;
520

    
521
                    if (EGFlowDirection == "O") //From 이면 시작점에서 제일 먼 값
522
                    {
523
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
524
                        {
525
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
526
                            {                                
527
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
528
                            }
529
                        }
530
                    }
531
                    else if (EGFlowDirection == "I") //To 이면 시작점에서 제일 가까운 값
532
                    {
533
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
534
                        {
535
                            if (PipeSystemNetwork.Select(string.Format("PUMP = 'PUMP' AND OID = '{0}'", viewOID)).Count() > 0)
536
                            {
537
                                selectViewOID = pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewOID).Last().Field<string>("OID");
538
                                break;
539
                            }
540
                        }
541
                    }
542

    
543
                    if (!string.IsNullOrEmpty(selectViewOID)) //selectViewOID 가 있으면
544
                    {              
545
                        string EqpGroupTag = string.Empty;                       
546

    
547
                        if((EGFlowDirection == "O" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.Last().Field<string>("ViewPipeSystemNetwork_OID"))) ||
548
                            (EGFlowDirection == "I" && lstViewPipeSystemNetwork_OID.Contains(pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID"))))
549
                        { 
550
                            DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pathItemRows.First().Field<string>("ViewPipeSystemNetwork_OID")));
551

    
552
                            foreach (DataRow row in viewpathItemRows)
553
                            {
554
                                if (!string.IsNullOrEmpty(row.Field<string>("EqpGroupTag")))
555
                                {
556
                                    EqpGroupTag = row.Field<string>("EqpGroupTag");
557
                                    break;
558
                                }
559
                            }
560

    
561
                            foreach (DataRow dr in pathItemRows)
562
                            {
563
                                dr["EqpGroupTag"] = EqpGroupTag;
564
                            }
565

    
566
                        }
567
                        else
568
                        {
569
                            bool bCheck = false;
570
                            if (EGFlowDirection == "I") //To 일때
571
                            {
572
                                foreach (DataRow dr in pathItemRows)
573
                                {
574
                                    if (selectViewOID == dr["OID"].ToString())
575
                                    {
576
                                        dr["EGTConnectedPoint"] = "1";
577
                                        bCheck = true;
578
                                    }
579

    
580
                                    if (!bCheck)
581
                                    {
582
                                        dr["EqpGroupTag"] = string.Empty;
583
                                        dr["MainLineTag"] = string.Empty;
584
                                        dr["EGTConnectedPoint"] = "0";
585
                                        dr["EGFlowDirection"] = string.Empty;
586
                                    }
587
                                    else
588
                                    {
589
                                        dr["MainLineTag"] = "M";
590
                                    }
591
                                    
592
                                }
593

    
594
                            }
595
                            else if (EGFlowDirection == "O") //From 일 때
596
                            {
597
                                foreach (DataRow dr in pathItemRows)
598
                                {
599
                                    if (bCheck)
600
                                    {
601
                                        
602
                                        dr["EqpGroupTag"] = string.Empty;
603
                                        dr["MainLineTag"] = string.Empty;
604
                                        dr["EGTConnectedPoint"] = "0";
605
                                        dr["EGFlowDirection"] = string.Empty;
606
                                    }
607
                                    else
608
                                    {
609
                                        dr["MainLineTag"] = "M";
610
                                    }
611

    
612
                                    if (selectViewOID == dr["OID"].ToString())
613
                                    {
614
                                        dr["EGTConnectedPoint"] = "1";
615
                                        bCheck = true;
616
                                    }
617
                                }
618
                            }
619
                        }
620
                    }
621
                    else
622
                    {
623
                        //foreach (DataRow dr in pathItemRows)
624
                        //{
625
                        //    dr["EqpGroupTag"] = string.Empty;
626
                        //    dr["EGFlowDirection"] = string.Empty;
627
                        //    dr["EGTConnectedPoint"] = "0";
628
                        //    dr["MainLineTag"] = string.Empty;
629
                        //}
630
                    }
631
                }
632
                                
633
                // 5번
634
                foreach (DataRow dataRow in pumpRows)
635
                {
636
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
637

    
638
                    bool bCheck = false;
639
                    string EqpGroupTag = string.Empty;
640

    
641
                    string EGFlowDirection = string.Empty;                   
642

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

    
645
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
646
                    {
647
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
648
                        {
649
                            EGFlowDirection = "O";
650
                        }
651
                    }
652
                    
653
                    if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
654
                    {
655
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
656
                        {
657
                            EGFlowDirection = "I";
658
                        }
659
                    }
660

    
661
                    List<string> lstViewPipeSystemNetwork_OID = new List<string>();
662
                    List<string> lstEqTagRows = new List<string>();
663
                    if (EGFlowDirection.Equals("I"))
664
                    {
665
                        foreach (DataRow dr in pathItemRows)
666
                        {                            
667
                            if (!string.IsNullOrEmpty(dr.Field<string>("MainLineTag")) && dr.Field<string>("MainLineTag").Equals("M") && !string.IsNullOrEmpty(dr.Field<string>("EqpGroupTag")))
668
                            {
669
                                bCheck = true;
670
                                EqpGroupTag = dr.Field<string>("EqpGroupTag");
671
                                if(!lstEqTagRows.Contains(EqpGroupTag))
672
                                    lstEqTagRows.Add(EqpGroupTag);
673

    
674
                                if(dataRow["OID"].ToString() != dr.Field<string>("ViewPipeSystemNetwork_OID"))
675
                                {
676
                                    PSNItem viewPSNItem = PSNItems.Find(x => x.PSN_OID() == dr.Field<string>("ViewPipeSystemNetwork_OID"));
677
                                    if (viewPSNItem.Groups.Last().Items.Last().Equipment == null)
678
                                        continue;
679

    
680
                                    if (!lstEqTagRows.Contains(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag))
681
                                        lstEqTagRows.Add(viewPSNItem.Groups.Last().Items.Last().Equipment.ItemTag);
682
                                }
683
                                
684
                            }
685

    
686
                        }
687
                        if(bCheck)
688
                        {
689
                            foreach (DataRow row in pumpRows)
690
                            {
691
                                if (row.Field<string>("OID").Equals(dataRow["OID"].ToString()))
692
                                    continue;
693

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

    
696
                                if (viewPSNItem.Groups.First().Items.First().Equipment == null)
697
                                    continue;
698
                                
699
                                if (lstEqTagRows.Contains(viewPSNItem.Groups.First().Items.First().Equipment.ItemTag) && !lstViewPipeSystemNetwork_OID.Contains(row.Field<string>("OID")))
700
                                    lstViewPipeSystemNetwork_OID.Add(row.Field<string>("OID"));
701
                            }
702

    
703
                                
704

    
705
                            if (lstViewPipeSystemNetwork_OID.Count() > 0)
706
                            {
707
                                foreach (string viewPipesystem in lstViewPipeSystemNetwork_OID)
708
                                {
709
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewPipesystem));
710
                                    foreach (DataRow viewdr in viewpathItemRows)
711
                                    {
712
                                        if (!string.IsNullOrEmpty(viewdr["EqpGroupTag"].ToString()))
713
                                            viewdr["EqpGroupTag"] = EqpGroupTag;
714
                                    }
715
                                }
716
                            }
717
                        }                        
718
                    }                   
719
                }
720
                
721
                int afcTagNum = 0;
722
                DataRow[] airFinCoolerRows = PipeSystemNetwork.Select("AFC Like 'P1%'");
723
                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
724
                foreach (DataRow dataRow in airFinCoolerRows)
725
                {
726
                    string EGFlowDirection = string.Empty;
727
                    string EGTAG = "EGTAG";
728
                    string Prefix = string.Empty;
729
                    string SymbolName = string.Empty;
730

    
731
                    //item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
732
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
733
                    if (PSNItem.Groups.First().Items.First().Equipment != null)
734
                    {
735
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
736
                        {
737
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
738
                            if(!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
739
                                EGTAG = PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null 
740
                                    ? string.Empty : PSNItem.Groups.First().Items.First().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
741

    
742
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;
743
                            EGFlowDirection = "O";
744
                        }
745
                    }
746

    
747
                    if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
748
                    {
749
                        if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
750
                        {
751
                            EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
752
                            if (!string.IsNullOrEmpty(equipmentAirFinCoolerItem.AttributeName))
753
                                EGTAG = PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName) == null 
754
                                    ? string.Empty : PSNItem.Groups.Last().Items.Last().Equipment.Attributes.Find(x => x.Name == equipmentAirFinCoolerItem.AttributeName).Value;
755

    
756
                            Prefix = equipmentAirFinCoolerItem.TagIdentifier;
757
                            EGFlowDirection = "I";
758
                        }
759
                    }
760

    
761
                    if(!string.IsNullOrEmpty(EGFlowDirection))
762
                    {
763
                        string[] afcTag = dataRow.Field<string>("AFC").Split(new string[] { "\\" }, StringSplitOptions.None);
764

    
765
                        //Attribute가 세팅되어있지 않다면
766
                        if (EGTAG.Equals("EGTAG"))
767
                        {                          
768
                            if (!keyValuePairs.ContainsKey(afcTag[1]))
769
                            {
770
                                if (!string.IsNullOrEmpty(Prefix))
771
                                {
772
                                    afcTagNum++;
773
                                    EGTAG = Prefix + string.Format("-{0}", string.Format("{0:D5}", afcTagNum));
774
                                    keyValuePairs.Add(afcTag[1], EGTAG);
775
                                }
776
                                else
777
                                {
778
                                    keyValuePairs.Add(afcTag[1], afcTag[1]);
779

    
780
                                }
781
                            }
782
                            else
783
                            {
784
                                EGTAG = keyValuePairs[afcTag[1]];
785
                            }
786
                            
787
                        }
788
                        else
789
                        {
790
                            if (!string.IsNullOrEmpty(Prefix))
791
                                EGTAG = Prefix + "-" + EGTAG;                          
792
                        }
793

    
794
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
795
                        foreach (DataRow dr in pathItemRows)
796
                        {
797
                            dr["EqpGroupTag"] = EGTAG;
798
                            dr["EGFlowDirection"] = EGFlowDirection;
799
                        }
800
                    }
801
                    
802
                }
803

    
804
                List<string> changePSN = new List<string>();
805
                foreach (DataRow dataRow in airFinCoolerRows)
806
                {
807
                    if (changePSN.Contains(dataRow["OID"].ToString()))
808
                        continue;
809

    
810
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
811
                    string AFCTag = string.Empty;
812
                    if (pathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).Count() > 0)
813
                        AFCTag = pathItemRows.Where(x => !string.IsNullOrEmpty(x.Field<string>("EqpGroupTag"))).First().Field<string>("EqpGroupTag");
814

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

    
817
                    if (dataRow["Type"].ToString() == "E2E")
818
                    {
819
                        foreach (DataRow dr in pathItemRows)
820
                        {
821
                            dr["MainLineTag"] = "M";
822
                        }
823
                        dataRow["AFC"] = "P3";
824
                    }
825
                    else if (dataRow["Type"].ToString() == "E2B" || dataRow["Type"].ToString() == "B2E")
826
                    {
827
                        foreach (string lstoid in lstViewPipeSystemNetwork_OID)
828
                        {
829
                            DataRow[] p2psn = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", lstoid));
830

    
831
                            if (p2psn.Count() > 0)
832
                            {
833
                                DataRow[] viewPathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstoid));
834
                                List<string> lstview = viewPathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
835
                                lstview.Remove(dataRow["OID"].ToString()); // P1인 자신 제거
836
                                lstview.Remove(lstoid); // P2 자신 제거
837

    
838
                                List<string> lstnewpipe = new List<string>();
839
                                foreach (string lstvw in lstview) //자신 외 P1이 있는지 확인
840
                                {
841
                                    if (airFinCoolerRows.Where(x => x.Field<string>("OID").Equals(lstvw)).Count() > 0) //P1이면 리스트에 추가
842
                                        lstnewpipe.Add(lstvw);
843
                                }
844

    
845
                                if (lstnewpipe.Count() == 0)
846
                                {
847
                                    foreach (DataRow dr in pathItemRows)
848
                                    {
849
                                        dr["MainLineTag"] = "M";
850
                                    }
851
                                    dataRow["AFC"] = "P3";
852
                                }
853
                                else
854
                                {
855
                                    // P2에 ML값 AGT값 지정
856
                                    DataRow[] viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstoid));
857
                                    DataRow[] pipesystemRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", lstoid));
858
                                    foreach (DataRow viewdr in pipesystemRows)
859
                                    {
860
                                        viewdr["AFC"] = "P4";
861
                                    }
862

    
863
                                    foreach (DataRow viewdr in viewpathItemRows)
864
                                    {
865
                                        viewdr["EqpGroupTag"] = AFCTag;
866
                                        viewdr["MainLineTag"] = "M";
867
                                    }
868
                                    // 연결된 모든 P1들의 AGT값 치환
869
                                    foreach (string pipe in lstnewpipe)
870
                                    {
871
                                        viewpathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipe));
872
                                        foreach (DataRow viewdr in viewpathItemRows)
873
                                        {
874
                                            viewdr["EqpGroupTag"] = AFCTag;
875
                                        }
876
                                    }
877
                                }
878
                            }                               
879
                        }   
880
                    }
881
                }
882
                
883
                //P3을 제외한 P1
884
                airFinCoolerRows = PipeSystemNetwork.Select("AFC Like 'P1%'");
885
                foreach (DataRow dataRow in airFinCoolerRows)
886
                {
887
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"].ToString()));
888
                    
889
                    if (pathItemRows.Count() > 0)
890
                    {
891
                        List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
892
                        List<string> lstpsn = new List<string>();
893
                        List<string> lstAll = new List<string>();
894
                        string EqpGroupTag = string.Empty;
895
                        foreach (string viewOID in lstViewPipeSystemNetwork_OID)
896
                        {
897
                            if (dataRow["OID"].ToString() == viewOID)
898
                            {
899
                                lstAll.Add(viewOID);
900
                                continue;
901
                            }
902

    
903
                            //P3이면
904
                            DataRow viewPSN = null;
905
                            if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).Count() > 0)
906
                                viewPSN = PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P3'", viewOID)).First();
907
                            
908
                            if (viewPSN != null)
909
                            {
910
                                //P3의 AGT를 가져와 P1에 입력
911
                                if(string.IsNullOrEmpty(EqpGroupTag))
912
                                    EqpGroupTag = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", viewOID)).First().Field<string>("EqpGroupTag");
913

    
914
                                foreach (DataRow dr in pathItemRows)
915
                                {
916
                                    dr["EqpGroupTag"] = EqpGroupTag;
917

    
918
                                    //P1의 AGT와 같은 모든 AGT를 P3의 AGT로 변경하기위해 
919
                                    if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstpsn.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
920
                                    {
921
                                        //AND MainLineTag = ''
922
                                        if (PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' ", dr.Field<string>("ViewPipeSystemNetwork_OID"))).Count() > 0)
923
                                        {
924
                                            lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
925
                                            lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
926
                                        }
927
                                    }
928
                                }
929
                            }                            
930
                        }
931

    
932
                        while (lstpsn.Count() != 0)
933
                        {                            
934
                            DataRow[] rule4pathItems = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", lstpsn[0]));
935
                            foreach (DataRow dr in rule4pathItems)
936
                            {
937
                                if (!string.IsNullOrEmpty(dr.Field<string>("ViewPipeSystemNetwork_OID")) && !lstAll.Contains(dr.Field<string>("ViewPipeSystemNetwork_OID")))
938
                                {
939
                                    DataRow viewPSN = null;
940

    
941
                                    if (airFinCoolerRows.Where(x => x.Field<string>("OID") == dr.Field<string>("ViewPipeSystemNetwork_OID")).Count() > 0)
942
                                        viewPSN = airFinCoolerRows.Where(x => x.Field<string>("OID") == dr.Field<string>("ViewPipeSystemNetwork_OID")).First();
943
                                                                        
944
                                    if (viewPSN != null)
945
                                    {
946
                                        lstpsn.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
947
                                        lstAll.Add(dr.Field<string>("ViewPipeSystemNetwork_OID"));
948
                                    }
949
                                }                                
950

    
951
                                dr["EqpGroupTag"] = EqpGroupTag;
952

    
953
                            }
954
                            lstpsn.Remove(lstpsn[0]);
955
                        }
956
                    }
957
                    
958
                }
959

    
960
                foreach(DataRow dr in PipeSystemNetwork.Rows)
961
                {
962
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}' AND MainLineTag = 'M'", dr["OID"].ToString()));
963
                    if(pathItemRows.Count() > 0)
964
                    {
965
                        if(dr["Type"].ToString() == "HD2")
966
                        {
967
                            List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
968
                            foreach(string viewpsn in lstViewPipeSystemNetwork_OID)
969
                            {                              
970
                                if (PipeSystemNetwork.Select(string.Format("OID = '{0}' AND AFC = 'P2'", viewpsn)).Count() > 0)
971
                                {
972
                                    foreach(DataRow dataRow in pathItemRows.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID") == viewpsn))
973
                                    {
974
                                        dataRow["EGTConnectedPoint"] = "1";
975
                                    }
976
                                }
977
                            }
978
                        }
979
                        else if(dr["Type"].ToString() == "E2B" || dr["Type"].ToString() == "B2E" || dr["Type"].ToString() == "E2E")
980
                        {
981
                            PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dr["OID"].ToString());
982
                            string EGFlowDirection = string.Empty;
983
                            if (PSNItem.Groups.First().Items.First().Equipment != null)
984
                            {
985
                                if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).Count() > 0)
986
                                {
987
                                    EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.First().Items.First().Equipment.Name.Contains(x.Name)).First();
988
                                    if (equipmentAirFinCoolerItem != null)
989
                                        EGFlowDirection = "O";
990
                                }
991
                            }
992
                            
993
                            if (string.IsNullOrEmpty(EGFlowDirection) && PSNItem.Groups.Last().Items.Last().Equipment != null)
994
                            {
995
                                if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).Count() > 0)
996
                                {
997
                                    EquipmentAirFinCoolerItem equipmentAirFinCoolerItem = EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && PSNItem.Groups.Last().Items.Last().Equipment.Name.Contains(x.Name)).First();
998
                                    if(equipmentAirFinCoolerItem != null)
999
                                        EGFlowDirection = "I";
1000
                                }
1001
                            }
1002

    
1003
                            if (!string.IsNullOrEmpty(EGFlowDirection))
1004
                            {
1005
                                List<string> lstViewPipeSystemNetwork_OID = pathItemRows.Select(x => x.Field<string>("ViewPipeSystemNetwork_OID")).Distinct().ToList();
1006
                                string lastP1 = string.Empty;
1007

    
1008
                                foreach (string viewpsn in lstViewPipeSystemNetwork_OID)
1009
                                {
1010
                                    if (viewpsn == dr["OID"].ToString())
1011
                                        continue;
1012

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

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

    
1018
                                    if (rows != null)
1019
                                    {
1020
                                        lastP1 = viewpsn;
1021
                                        if (EGFlowDirection.Equals("I")) // To         
1022
                                            break;
1023
                                    }
1024
                                }
1025

    
1026
                                if (!string.IsNullOrEmpty(lastP1))
1027
                                {
1028
                                    bool bCheck = false;
1029
                                    if (EGFlowDirection.Equals("O")) // From
1030
                                    {
1031
                                        foreach (DataRow dataRow in pathItemRows)
1032
                                        {
1033
                                            if (bCheck)
1034
                                            {
1035
                                                dataRow["EqpGroupTag"] = string.Empty;
1036
                                                dataRow["MainLineTag"] = string.Empty;
1037
                                                dataRow["EGTConnectedPoint"] = 0;
1038
                                                dataRow["EGFlowDirection"] = string.Empty;
1039
                                            }
1040

    
1041
                                            if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
1042
                                            {
1043
                                                bCheck = true;
1044
                                                dataRow["EGTConnectedPoint"] = 1;
1045
                                            }
1046
                                        }
1047
                                    }
1048
                                    else
1049
                                    {
1050
                                        foreach (DataRow dataRow in pathItemRows)
1051
                                        {
1052
                                            if (dataRow.Field<string>("ViewPipeSystemNetwork_OID").Equals(lastP1))
1053
                                            {
1054
                                                dataRow["EGTConnectedPoint"] = 1;
1055
                                                break;
1056
                                            }
1057
                                            
1058
                                            dataRow["EqpGroupTag"] = string.Empty;
1059
                                            dataRow["MainLineTag"] = string.Empty;
1060
                                            dataRow["EGTConnectedPoint"] = 0;
1061
                                            dataRow["EGFlowDirection"] = string.Empty;
1062

    
1063
                                        }
1064
                                    }
1065
                                }
1066
                            }                          
1067
                        }
1068
                    }
1069
                }
1070

    
1071
                //psn data 정리
1072
                foreach(DataRow pipesystem in PipeSystemNetwork.Rows)
1073
                {
1074
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", pipesystem["OID"].ToString()));
1075
                    string EGTag = string.Empty;
1076
                    string HasMLTags = "False";
1077

    
1078
                    foreach (DataRow dataRow in pathItemRows)
1079
                    {
1080
                        if (string.IsNullOrEmpty(EGTag) && !string.IsNullOrEmpty(dataRow.Field<string>("EqpGroupTag")))
1081
                            EGTag = dataRow.Field<string>("EqpGroupTag");
1082

    
1083
                        if (HasMLTags.Equals("False") && !string.IsNullOrEmpty(dataRow.Field<string>("MainLineTag")) && dataRow.Field<string>("MainLineTag").Equals("M"))
1084
                            HasMLTags = "True";
1085

    
1086
                        if (!string.IsNullOrEmpty(EGTag) && HasMLTags == "True")
1087
                            break;
1088
                    }
1089

    
1090
                    pipesystem["EGTag"] = EGTag;
1091
                    pipesystem["HasMLTags"] = HasMLTags;
1092
                }
1093
            }
1094
            catch (Exception ex)
1095
            {
1096
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
1097
            }
1098
            //}
1099
        }
1100

    
1101
        private void UpdateValveGrouping()
1102
        {
1103
            try
1104
            {
1105
                #region ValveGrouping Info
1106
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
1107
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
1108
                foreach (DataRow row in dtValveGroupung.Rows)
1109
                {
1110
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
1111
                    {
1112
                        OID = row["OID"].ToString(),
1113
                        GroupType = row["GroupType"].ToString(),
1114
                        TagIdentifier = row["TagIdentifier"].ToString(),
1115
                        AttributeName = row["AttributeName"].ToString(),
1116
                        SppidSymbolName = row["SppidSymbolName"].ToString()
1117
                    });
1118
                }
1119
                #endregion
1120

    
1121

    
1122
                int vgTagNum = 1;
1123
                DataRow[] tagpathItemRows = PathItems.Select(string.Format("GROUPTAG Like '%\\%'"));
1124
                foreach (DataRow drPathitem in tagpathItemRows)
1125
                {
1126
                    string[] valvetag = drPathitem["GROUPTAG"].ToString().Split(new string[] { "\\" }, StringSplitOptions.None);
1127
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1128
                    ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == valvetag[0]).FirstOrDefault();
1129
                    if (valveitem == null || valveitem.GroupType == "Scope Break")
1130
                        continue;
1131
                    Dictionary<int, List<DataRow>> keyValuePairs = new Dictionary<int, List<DataRow>>();
1132
                    List<Item> valveGroupingItem = new List<Item>();
1133
                    int bCnt = 0;
1134

    
1135
                    
1136
                    List<DataRow> lstitem = new List<DataRow>();
1137
                    foreach (DataRow dr in pathItemRows)
1138
                    {
1139
                        if (dr["GROUPTAG"].ToString() == "Scope Break")
1140
                        {
1141
                            dr["GROUPTAG"] = string.Empty;
1142
                            keyValuePairs.Add(bCnt, lstitem.ToList());
1143
                            bCnt++;
1144
                            lstitem.Clear();
1145
                            continue;
1146
                        }
1147

    
1148
                        if (!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1149
                        {
1150
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString()));
1151
                          
1152
                           
1153
                                if (rows.First()["SubType"].ToString() != "Bypass" && rows.First()["SubType"].ToString() != "Vent_Drain")
1154
                                {
1155
                                    if (lstitem.ToList().Where(x => !string.IsNullOrEmpty(x.Field<string>("GROUPTAG"))).Count() > 0)
1156
                                    {
1157
                                        lstitem.Add(dr);
1158
                                        keyValuePairs.Add(bCnt, lstitem.ToList());
1159
                                        lstitem.Clear();
1160
                                    }
1161
                                    else
1162
                                    {
1163
                                        keyValuePairs.Add(bCnt, lstitem.ToList());
1164
                                        lstitem.Clear();
1165
                                        lstitem.Add(dr);
1166
                                    }
1167
                                    bCnt++;
1168

    
1169
                                }
1170
                                else
1171
                                    lstitem.Add(dr);
1172
                            
1173
                        }
1174
                        else
1175
                            lstitem.Add(dr);
1176
                    }
1177

    
1178
                    if (lstitem.Count > 0)
1179
                    {
1180
                        keyValuePairs.Add(bCnt, lstitem);
1181
                    }
1182

    
1183
                    if (keyValuePairs.Count() == 0)
1184
                        continue;
1185

    
1186
                    string VGTag = string.Empty;
1187
                    if (valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
1188
                    {
1189
                        VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1190
                        vgTagNum++;
1191
                    }
1192
                    else
1193
                    {
1194
                        //if(string.IsNullOrEmpty(valvetag[1]))
1195
                        //    VGTag = valveitem.TagIdentifier + string.Format("-{0}", string.Format("{0:D5}", vgTagNum));
1196
                        //else
1197
                        VGTag = valveitem.TagIdentifier + "-" + valvetag[1];
1198
                    }
1199

    
1200
                    foreach (KeyValuePair<int, List<DataRow>> keyValuePair in keyValuePairs)
1201
                    {
1202
                        if (keyValuePair.Value.Where(x => x.Field<string>("OID") == drPathitem.Field<string>("OID")).Count() > 0)
1203
                        {
1204
                            foreach (DataRow dr in keyValuePair.Value)
1205
                            {
1206
                                dr["GROUPTAG"] = VGTag;
1207

    
1208
                                if(!string.IsNullOrEmpty(dr["BranchTopologySet_OID"].ToString()))
1209
                                {
1210
                                    if(TopologySet.Select(string.Format("OID = '{0}'", dr["BranchTopologySet_OID"].ToString())).First().Field<string>("SubType") == "Bypass")
1211
                                    {
1212
                                        DataRow[] rows = keyValuePair.Value.Where(x => x.Field<string>("ViewPipeSystemNetwork_OID").Equals(dr["ViewPipeSystemNetwork_OID"].ToString())).ToArray();
1213
                                        foreach(DataRow path in rows)
1214
                                        {
1215
                                            DataRow topology = TopologySet.Select(string.Format("OID = '{0}'", path["BranchTopologySet_OID"].ToString())).First();
1216
                                            if (topology.Field<string>("SubType").Equals("Bypass"))
1217
                                            {
1218
                                                DataRow[] drPathItem = PathItems.Select(string.Format("TopologySet_OID = '{0}'", topology.Field<string>("OID")));
1219
                                                foreach(DataRow pathitem in drPathItem)
1220
                                                {
1221
                                                    pathitem["GROUPTAG"] = VGTag;
1222
                                                }
1223
                                            }
1224
                                        }
1225
                                    }
1226
                                }
1227
                            }
1228
                        }
1229
                    }
1230
                    if(valveitem.GroupType.Contains("PSV"))
1231
                    {
1232
                        DataRow[] psnRows = PipeSystemNetwork.Select(string.Format("OID = '{0}'", drPathitem["PipeSystemNetwork_OID"].ToString()));
1233
                        foreach (DataRow row in psnRows)
1234
                            row["Pocket"] = "Yes";
1235
                    }                    
1236
                }
1237

    
1238
                tagpathItemRows = PathItems.Select(string.Format("GROUPTAG = 'Scope Break'"));
1239
                foreach (DataRow drPathitem in tagpathItemRows)
1240
                {
1241
                    drPathitem["GROUPTAG"] = string.Empty;
1242
                }
1243
            }
1244
            catch (Exception ex)
1245
            {
1246
                MessageBox.Show(ex.Message, "ID2 ", MessageBoxButtons.OK, MessageBoxIcon.Error);
1247
            }
1248
        }
1249

    
1250
        private void SetTopologyData()
1251
        {
1252
            // 13번 excel
1253
            foreach (Group group in groups)
1254
            {
1255
                LineNumber prevLineNumber = null;
1256
                for (int i = 0; i < group.Items.Count; i++)
1257
                {
1258
                    Item item = group.Items[i];
1259
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1260
                    if (lineNumber == null)
1261
                    {
1262
                        if (prevLineNumber != null)
1263
                        {
1264
                            if (!prevLineNumber.IsCopy)
1265
                            {
1266
                                prevLineNumber = prevLineNumber.Copy();
1267
                                prevLineNumber.MissingLineNumber1 = true;
1268
                                item.Document.LineNumbers.Add(prevLineNumber);
1269
                                //item.LineNumber.MissingLineNumber1 = true;
1270
                            }
1271
                            item.Owner = prevLineNumber.UID;
1272
                        }
1273
                    }
1274
                    else
1275
                        prevLineNumber = lineNumber;
1276
                }
1277

    
1278
                prevLineNumber = null;
1279
                for (int i = group.Items.Count - 1; i > -1; i--)
1280
                {
1281
                    Item item = group.Items[i];
1282
                    LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
1283
                    if (lineNumber == null)
1284
                    {
1285
                        if (prevLineNumber != null)
1286
                        {
1287
                            if (!prevLineNumber.IsCopy)
1288
                            {
1289
                                prevLineNumber = prevLineNumber.Copy();
1290
                                prevLineNumber.MissingLineNumber1 = true;
1291
                                item.Document.LineNumbers.Add(prevLineNumber);
1292
                                //item.LineNumber.MissingLineNumber1 = true;                                
1293
                            }
1294

    
1295
                            item.Owner = prevLineNumber.UID;
1296
                        }
1297
                    }
1298
                    else
1299
                        prevLineNumber = lineNumber;
1300
                }
1301

    
1302
                if (prevLineNumber == null)
1303
                {
1304
                    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
1305
                    Random random = new Random();
1306

    
1307
                    LineNumber cLineNumber = null;
1308

    
1309
                    if (lineNumbers.Count == 0)
1310
                    {
1311
                        var _groups = groups.Where(w => w != group).ToList();
1312
                        while (cLineNumber == null)
1313
                        {
1314
                            int _index = random.Next(_groups.Count - 1);
1315
                            List<LineNumber> _lineNumbers = groups[_index].Document.LineNumbers.FindAll(x => !x.IsCopy);
1316
                            if (_lineNumbers.Count != 0)
1317
                            {
1318
                                _index = random.Next(_lineNumbers.Count - 1);
1319

    
1320
                                // Copy
1321
                                cLineNumber = _lineNumbers[_index].Copy();
1322
                            }
1323
                        }
1324
                    }
1325
                    else
1326
                    {
1327
                        int index = random.Next(lineNumbers.Count - 1);
1328

    
1329
                        // Copy
1330
                        cLineNumber = lineNumbers[index].Copy();
1331
                    }
1332

    
1333
                    cLineNumber.MissingLineNumber2 = true;
1334
                    group.Document.LineNumbers.Add(cLineNumber);
1335

    
1336
                    foreach (Item item in group.Items)
1337
                    {
1338
                        item.Owner = cLineNumber.UID;                        
1339
                    }
1340
                }
1341

    
1342
                //if (prevLineNumber == null)
1343
                //{
1344
                //    List<LineNumber> lineNumbers = group.Document.LineNumbers.FindAll(x => !x.IsCopy);
1345
                //    Random random = new Random();
1346
                //    int index = random.Next(lineNumbers.Count - 1);
1347

    
1348
                //    // Copy
1349
                //    LineNumber cLineNumber = lineNumbers[index].Copy();
1350
                //    group.Document.LineNumbers.Add(cLineNumber);
1351

    
1352
                //    foreach (Item item in group.Items)
1353
                //    {
1354
                //        item.Owner = cLineNumber.UID;
1355
                //        item.Document.MissingLineNumber2 = true;
1356
                //    }
1357
                //}
1358
            }
1359

    
1360
            foreach (Document document in Documents)
1361
            {
1362
                foreach (Item item in document.Items)
1363
                {
1364
                    item.TopologyData = string.Empty;
1365
                    item.PSNPipeLineID = string.Empty;
1366
                    List<string> pipeLineID = new List<string>();
1367
                    LineNumber lineNumber = document.LineNumbers.Find(x => x.UID == item.Owner);
1368
                    
1369
                    if (lineNumber != null)
1370
                    {
1371
                        item.LineNumber = lineNumber;
1372

    
1373
                        foreach (DataRow row in topologyRuleDT.Rows)
1374
                        {
1375
                            string uid = row["UID"].ToString();
1376
                            //if (uid == "-")
1377
                            //    pipeLineID.Add(item.TopologyData);//item.TopologyData += "-"; 
1378
                            if (uid != "-")
1379
                            {
1380
                                Attribute itemAttr = item.Attributes.Find(x => x.Name == uid);
1381

    
1382
                                Attribute attribute = lineNumber.Attributes.Find(x => x.DisplayName == uid);
1383
                                if (attribute != null && !string.IsNullOrEmpty(attribute.Value))
1384
                                {
1385
                                    pipeLineID.Add(attribute.Value);//item.TopologyData += attribute.Value;
1386
                                                                    //if (uid.Equals("Tag Seq No") && attribute.Value.ToString().Substring(attribute.Value.ToString().Length - 1, 1).Equals("V"))
1387
                                                                    //{
1388
                                    if (item.LineNumber.MissingLineNumber1 && item.LineNumber.MissingLineNumber2)
1389
                                    {
1390

    
1391
                                    }
1392

    
1393
                                 
1394
                                    //    //if (item.Document.MissingLineNumber1)
1395
                                    //    //    item.MissingLineNumber1 = true;
1396
                                    //    //else if (item.Document.MissingLineNumber2)
1397
                                    //    //    item.MissingLineNumber2 = true;
1398
                                    //}
1399
                                }
1400
                            }
1401
                        }
1402
                        
1403
                        if (topologyRuleDT.Select(string.Format("UID = '{0}'", "InsulationPurpose")) == null)
1404
                        {
1405
                            Attribute insulAttr = item.LineNumber.Attributes.Find(x => x.Name == "InsulationPurpose");
1406
                            if (insulAttr != null && !string.IsNullOrEmpty(insulAttr.Value))
1407
                                pipeLineID.Add(insulAttr.Value); //item.PSNPipeLineID = item.TopologyData + "-" + insulAttr.Value;
1408
                                                                 //else
1409
                                                                 //    item.PSNPipeLineID = item.TopologyData;
1410
                        }
1411

    
1412
                        item.PSNPipeLineID = string.Join("-", pipeLineID);
1413
                        item.TopologyData = string.Join("-", pipeLineID);
1414
                        
1415
                    }
1416
                    else
1417
                    {
1418
                        item.TopologyData = "Empty LineNumber";
1419
                        item.LineNumber = new LineNumber();
1420
                    }
1421
                }
1422
            }
1423

    
1424
            int emptyIndex = 1;
1425
            foreach (Group group in groups)
1426
            {
1427
                List<Item> groupItems = group.Items.FindAll(x => x.TopologyData == "Empty LineNumber");
1428
                if (groupItems.Count > 0)
1429
                {
1430
                    foreach (var item in groupItems)
1431
                        item.TopologyData += string.Format("-{0}", emptyIndex);
1432
                    emptyIndex++;
1433
                }
1434
            }
1435

    
1436
        }
1437

    
1438
        private void ConnectByOPC()
1439
        {
1440
            try
1441
            {
1442
                foreach (Group group in groups.FindAll(x => x.Items.Last().SubItemType == SubItemType.OPC))
1443
                {
1444
                    Item opcItem = group.Items.Last();
1445
                    DataRow[] fromRows = opcDT.Select(string.Format("FromOPCUID = '{0}'", opcItem.UID));
1446
                    if (fromRows.Length.Equals(1))
1447
                    {
1448
                        DataRow opcRow = fromRows.First();
1449
                        string toDrawing = opcRow["ToDrawing"].ToString();
1450
                        string toOPCUID = opcRow["ToOPCUID"].ToString();
1451

    
1452
                        Document toDocument = Documents.Find(x => x.DrawingName == toDrawing);
1453
                        if (toDocument != null)
1454
                        {
1455
                            Group toGroup = toDocument.Groups.Find(x => x.Items.Find(y => y.UID == toOPCUID) != null);
1456
                            DataRow[] toRows = opcDT.Select(string.Format("ToOPCUID = '{0}'", toGroup.Items.First().UID));
1457
                            //1대1 매칭이 아닐때 걸림 (2개 이상일 때) 2021.11.07 
1458
                            if (toRows.Length > 1)
1459
                            {
1460
                                //throw new Exception("OPC error(multi connect)");
1461
                                MessageBox.Show("OPC error(multi connect)", "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1462
                                return;
1463
                            }
1464
                            group.EndGroup = toGroup;
1465
                            toGroup.StartGroup = group;
1466
                        }
1467
                    }
1468
                }
1469
            }
1470
            catch (Exception ex)
1471
            {
1472
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1473
                //MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1474
            }
1475
        }
1476

    
1477
        private void SetPSNItem()
1478
        {
1479
            Dictionary<Group, string> groupDic = new Dictionary<Group, string>();
1480
            foreach (Group group in groups)
1481
                groupDic.Add(group, Guid.NewGuid().ToString());
1482

    
1483
            foreach (Group group in groups)
1484
            {
1485
                string groupKey = groupDic[group];
1486
                if (group.StartGroup != null)
1487
                {
1488
                    string otherKey = groupDic[group.StartGroup];
1489
                    ChangeGroupID(otherKey, groupKey);
1490
                }
1491
            }
1492

    
1493
            // PSN 정리
1494
            foreach (var item in groupDic)
1495
            {
1496
                Group group = item.Key;
1497
                string uid = item.Value;
1498
                PSNItem PSNItem = PSNItems.Find(x => x.UID == uid);
1499
                if (PSNItem == null)
1500
                {
1501
                    PSNItem = new PSNItem(PSNItems.Count, Revision) { UID = uid };
1502
                    PSNItems.Add(PSNItem);
1503
                }
1504
                PSNItem.Groups.Add(group);
1505
                foreach (Item groupItem in group.Items)
1506
                    groupItem.PSNItem = PSNItem;
1507
            }
1508

    
1509
            // Sort PSN
1510
            foreach (PSNItem PSNItem in PSNItems)
1511
            {
1512
                List<Group> _groups = new List<Group>();
1513

    
1514
                Stack<Group> stacks = new Stack<Group>();
1515
                stacks.Push(PSNItem.Groups.First());
1516
                while (stacks.Count > 0)
1517
                {
1518
                    Group stack = stacks.Pop();
1519
                    if (_groups.Contains(stack))
1520
                        continue;
1521

    
1522
                    if (_groups.Count == 0)
1523
                        _groups.Add(stack);
1524
                    else
1525
                    {
1526
                        if (stack.StartGroup != null && _groups.Contains(stack.StartGroup))
1527
                        {
1528
                            int index = _groups.IndexOf(stack.StartGroup);
1529
                            _groups.Insert(index + 1, stack);
1530
                        }
1531
                        else if (stack.EndGroup != null && _groups.Contains(stack.EndGroup))
1532
                        {
1533
                            int index = _groups.IndexOf(stack.EndGroup);
1534
                            _groups.Insert(index, stack);
1535
                        }
1536
                    }
1537

    
1538
                    if (stack.StartGroup != null)
1539
                        stacks.Push(stack.StartGroup);
1540
                    if (stack.EndGroup != null)
1541
                        stacks.Push(stack.EndGroup);
1542
                }
1543

    
1544
                PSNItem.Groups.Clear();
1545
                PSNItem.Groups.AddRange(_groups);
1546
            }
1547

    
1548
            void ChangeGroupID(string from, string to)
1549
            {
1550
                if (from.Equals(to))
1551
                    return;
1552

    
1553
                List<Group> changeItems = new List<Group>();
1554
                foreach (var _item in groupDic)
1555
                    if (_item.Value.Equals(from))
1556
                        changeItems.Add(_item.Key);
1557
                foreach (var _item in changeItems)
1558
                    groupDic[_item] = to;
1559
            }
1560
        }
1561

    
1562
        private void SetPSNType()
1563
        {
1564
            foreach (PSNItem PSNItem in PSNItems)
1565
            {
1566
                Group firstGroup = PSNItem.Groups.First();
1567
                Group lastGroup = PSNItem.Groups.Last();
1568

    
1569
                Item firstItem = firstGroup.Items.First();
1570
                Item lastItem = lastGroup.Items.Last();
1571

    
1572
                PSNItem.StartType = GetPSNType(firstItem, true);
1573
                PSNItem.EndType = GetPSNType(lastItem, false);
1574

    
1575
            }
1576

    
1577
            PSNType GetPSNType(Item item, bool bFirst = true)
1578
            {
1579
                PSNType type = PSNType.None;
1580

    
1581
                if (item.ItemType == ItemType.Line)
1582
                {
1583
                    Group group = groups.Find(x => x.Items.Contains(item));
1584
                    if (bFirst && item.Relations[0].Item != null && !group.Items.Contains(item.Relations[0].Item))
1585
                    {
1586
                        Item connItem = item.Relations[0].Item;
1587
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1588
                            type = PSNType.Branch;
1589
                        else if (connItem.ItemType == ItemType.Symbol)
1590
                            type = PSNType.Symbol;
1591
                    }
1592
                    else if (!bFirst && item.Relations[1].Item != null && !group.Items.Contains(item.Relations[1].Item))
1593
                    {
1594
                        Item connItem = item.Relations[1].Item;
1595
                        if (connItem.ItemType == ItemType.Line && !IsConnected(item, connItem))
1596
                            type = PSNType.Branch;
1597
                        else if (connItem.ItemType == ItemType.Symbol)
1598
                            type = PSNType.Symbol;
1599
                    }
1600
                }
1601
                else if (item.ItemType == ItemType.Symbol)
1602
                {
1603
                    if (item.SubItemType == SubItemType.Nozzle)
1604
                        type = PSNType.Equipment;
1605
                    else if (item.SubItemType == SubItemType.Header)
1606
                        type = PSNType.Header;
1607
                    else if (item.SubItemType == SubItemType.OPC)
1608
                        type = PSNType.OPC;
1609
                }
1610

    
1611
                return type;
1612
            }
1613
        }
1614

    
1615
        private void SetBranchInfo()
1616
        {
1617
            foreach (Document document in Documents)
1618
            {
1619
                List<Item> lines = document.Items.FindAll(x => x.ItemType == ItemType.Line).ToList();
1620
                foreach (Item line in lines)
1621
                {
1622
                    double[] point = line.Relations[0].Point;
1623
                    List<Item> connLines = lines.FindAll(x => x.Relations.Find(y => y.UID == line.UID) != null && line.Relations.Find(y => y.UID == x.UID) == null);
1624
                    connLines.Sort(SortBranchLine);
1625
                    line.BranchItems.AddRange(connLines);
1626

    
1627
                    int SortBranchLine(Item a, Item b)
1628
                    {
1629
                        double[] pointA = a.Relations[0].UID == line.UID ? a.Relations[0].Point : a.Relations[1].Point;
1630
                        double distanceA = CalcPointToPointdDistance(point[0], point[1], pointA[0], pointA[1]);
1631

    
1632
                        double[] pointB = b.Relations[0].UID == line.UID ? b.Relations[0].Point : b.Relations[1].Point;
1633
                        double distanceB = CalcPointToPointdDistance(point[0], point[1], pointB[0], pointB[1]);
1634

    
1635
                        // 내림차순
1636
                        return distanceA.CompareTo(distanceB);
1637
                    }
1638
                    double CalcPointToPointdDistance(double x1, double y1, double x2, double y2)
1639
                    {
1640
                        return Math.Pow(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2), 0.5);
1641
                    }
1642
                }
1643
            }
1644
        }
1645

    
1646
        private void SetTopology()
1647
        {
1648
            try
1649
            {
1650
                #region 기본 topology 정리
1651
                foreach (PSNItem PSNItem in PSNItems)
1652
                {
1653
                    Topology topology = null;
1654
                    foreach (Group group in PSNItem.Groups)
1655
                    {
1656
                        foreach (Item item in group.Items)
1657
                        {
1658
                            if (string.IsNullOrEmpty(item.TopologyData))
1659
                                topology = null;
1660
                            else
1661
                            {
1662
                                if (topology == null)
1663
                                {
1664
                                    topology = new Topology()
1665
                                    {
1666
                                        ID = item.TopologyData
1667
                                    };
1668
                                    Topologies.Add(topology);
1669

    
1670
                                    if (!PSNItem.Topologies.Contains(topology))
1671
                                        PSNItem.Topologies.Add(topology);
1672
                                }
1673
                                else
1674
                                {
1675
                                    if (topology.ID != item.TopologyData)
1676
                                    {
1677
                                        topology = new Topology()
1678
                                        {
1679
                                            ID = item.TopologyData
1680
                                        };
1681
                                        Topologies.Add(topology);
1682

    
1683
                                        if (!PSNItem.Topologies.Contains(topology))
1684
                                            PSNItem.Topologies.Add(topology);
1685
                                    }
1686
                                }
1687

    
1688
                                item.Topology = topology;
1689
                                topology.Items.Add(item);
1690
                            }
1691
                        }
1692
                    }
1693
                }
1694
                #endregion
1695

    
1696
                #region Type
1697
                List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1698
                foreach (string id in ids)
1699
                {
1700
                    try
1701
                    {
1702

    
1703

    
1704
                        List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1705

    
1706
                        // Main
1707
                        List<Topology> mainTopologies = FindMainTopology(topologies);
1708
                        foreach (Topology topology in mainTopologies)
1709
                            topology.Type = "M";
1710

    
1711
                        // Branch
1712
                        List<Topology> branchToplogies = topologies.FindAll(x => string.IsNullOrEmpty(x.Type));
1713
                        foreach (Topology topology in branchToplogies)
1714
                            topology.Type = "B";
1715
                    }
1716
                    catch (Exception ex)
1717
                    {
1718
                        Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1719
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1720
                    }
1721
                }
1722
                #endregion
1723
            }
1724
            catch (Exception ex)
1725
            {
1726
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
1727
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
1728
            }
1729

    
1730
        }
1731

    
1732
        private void SetTopologyIndex()
1733
        {
1734
            List<string> ids = Topologies.Select(x => x.ID).Distinct().ToList();
1735
            foreach (string id in ids)
1736
            {
1737
                List<Topology> topologies = Topologies.FindAll(x => x.ID == id);
1738

    
1739
                // Main
1740
                List<Topology> mainTopologies = topologies.FindAll(x => x.Type == "M");
1741
                foreach (Topology topology in mainTopologies)
1742
                    topology.Index = mainTopologies.IndexOf(topology).ToString();
1743

    
1744
                // Branch
1745
                List<Topology> branchToplogies = topologies.FindAll(x => x.Type == "B");
1746
                foreach (Topology topology in branchToplogies)
1747
                    topology.Index = (branchToplogies.IndexOf(topology) + 1).ToString();
1748
            }
1749
        }
1750

    
1751
        private void SetPSNBypass()
1752
        {
1753
            foreach (PSNItem PSNItem in PSNItems)
1754
                PSNItem.IsBypass = IsBypass(PSNItem);
1755
        }
1756

    
1757
        private List<Topology> FindMainTopology(List<Topology> data)
1758
        {
1759
            DataTable nominalDiameterDT = DB.SelectNominalDiameter();
1760
            DataTable PMCDT = DB.SelectPSNPIPINGMATLCLASS();
1761
            //2021.11.17 안쓰네 JY
1762
            //DataTable fluidCodeDT = DB.SelectPSNFluidCode(); 
1763

    
1764
            List<Topology> main = new List<Topology>();
1765
            main.AddRange(data);
1766
            //
1767
            main = GetNozzleTopology(data);
1768
            if (main.Count == 1)
1769
                return main;
1770
            else
1771
            {
1772
                if (main.Count > 0)
1773
                    main = GetPMCTopology(main);
1774
                else
1775
                    main = GetPMCTopology(data);
1776

    
1777
                if (main.Count == 1)
1778
                    return main;
1779
                else
1780
                {
1781
                    if (main.Count > 0)
1782
                        main = GetDiaTopology(main);
1783
                    else
1784
                        main = GetDiaTopology(data);
1785

    
1786

    
1787
                    if (main.Count == 1)
1788
                        return main;
1789
                    else
1790
                    {
1791
                        if (main.Count > 0)
1792
                            main = GetItemTopology(main);
1793
                        else
1794
                            main = GetItemTopology(data);
1795
                    }
1796
                }
1797
            }
1798

    
1799
            List<Topology> GetNozzleTopology(List<Topology> topologies)
1800
            {
1801
                return topologies.FindAll(x => x.Items.Find(y => y.SubItemType == SubItemType.Nozzle) != null);
1802
            }
1803

    
1804
            List<Topology> GetPMCTopology(List<Topology> topologies)
1805
            {
1806
                List<Topology> result = new List<Topology>();
1807
                foreach (DataRow row in PMCDT.Rows)
1808
                {
1809
                    string value = row["CODE"].ToString();
1810
                    foreach (Topology topology in topologies)
1811
                    {
1812
                        foreach (Item item in topology.Items)
1813
                        {
1814
                            if (item.LineNumber == null)
1815
                                continue;
1816
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1817
                            if (attribute != null && value == attribute.Value)
1818
                            {
1819
                                result.Add(topology);
1820
                                break;
1821
                            }
1822
                        }
1823
                    }
1824

    
1825
                    if (result.Count > 0)
1826
                        break;
1827
                }
1828

    
1829
                return result;
1830
            }
1831

    
1832
            List<Topology> GetDiaTopology(List<Topology> topologies)
1833
            {
1834
                List<Topology> result = new List<Topology>();
1835
                foreach (DataRow row in nominalDiameterDT.Rows)
1836
                {
1837
                    string inchValue = row["InchStr"].ToString();
1838
                    string metricValue = row["MetricStr"].ToString();
1839
                    foreach (Topology topology in topologies)
1840
                    {
1841
                        foreach (Item item in topology.Items)
1842
                        {
1843
                            if (item.LineNumber == null)
1844
                                continue;
1845
                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1846
                            if (attribute != null && (inchValue == attribute.Value || metricValue == attribute.Value))
1847
                            {
1848
                                result.Add(topology);
1849
                                break;
1850
                            }
1851
                        }
1852
                    }
1853

    
1854
                    if (result.Count > 0)
1855
                        break;
1856
                }
1857

    
1858
                return result;
1859
            }
1860

    
1861
            List<Topology> GetItemTopology(List<Topology> topologies)
1862
            {
1863
                return new List<Topology>() { topologies.OrderByDescending(x => x.Items.Count).ToList().First() };
1864
            }
1865

    
1866
            return main;
1867
        }
1868

    
1869
        private DataTable GetOPCInfo()
1870
        {
1871
            DataTable opc = DB.SelectOPCRelations();
1872
            DataTable drawing = DB.AllDrawings();
1873

    
1874
            DataTable dt = new DataTable();
1875
            dt.Columns.Add("FromDrawing", typeof(string));
1876
            dt.Columns.Add("FromDrawingUID", typeof(string));
1877
            dt.Columns.Add("FromOPCUID", typeof(string));
1878
            dt.Columns.Add("ToDrawing", typeof(string));
1879
            dt.Columns.Add("ToDrawingUID", typeof(string));
1880
            dt.Columns.Add("ToOPCUID", typeof(string));
1881
            foreach (DataRow row in opc.Rows)
1882
            {
1883
                string fromDrawingUID = row["From_Drawings_UID"] == null ? string.Empty : row["From_Drawings_UID"].ToString();
1884
                string fromOPCUID = row["From_OPC_UID"] == null ? string.Empty : row["From_OPC_UID"].ToString();
1885
                string toDrawingUID = row["To_Drawings_UID"] == null ? string.Empty : row["To_Drawings_UID"].ToString();
1886
                string toOPCUID = row["To_OPC_UID"] == null ? string.Empty : row["To_OPC_UID"].ToString();
1887
                if (!string.IsNullOrEmpty(toOPCUID))
1888
                {
1889
                    DataRow[] fromRows = drawing.Select(string.Format("UID = '{0}'", fromDrawingUID));
1890
                    DataRow[] toRows = drawing.Select(string.Format("UID = '{0}'", toDrawingUID));
1891
                    if (fromRows.Length.Equals(1) && toRows.Length.Equals(1))
1892
                    {
1893
                        string fromDrawingName = Path.GetFileNameWithoutExtension(fromRows.First()["NAME"].ToString());
1894
                        string toDrawingName = Path.GetFileNameWithoutExtension(toRows.First()["NAME"].ToString());
1895

    
1896
                        DataRow newRow = dt.NewRow();
1897
                        newRow["FromDrawing"] = fromDrawingName;
1898
                        newRow["FromDrawingUID"] = fromDrawingUID;
1899
                        newRow["FromOPCUID"] = fromOPCUID;
1900
                        newRow["ToDrawing"] = toDrawingName;
1901
                        newRow["ToDrawingUID"] = toDrawingUID;
1902
                        newRow["ToOPCUID"] = toOPCUID;
1903

    
1904
                        dt.Rows.Add(newRow);
1905
                    }
1906
                }
1907
            }
1908

    
1909
            return dt;
1910
        }
1911

    
1912
        private DataTable GetTopologyRule()
1913
        {
1914
            DataTable dt = DB.SelectTopologyRule();
1915

    
1916
            return dt;
1917
        }
1918

    
1919
        private bool IsConnected(Item item1, Item item2)
1920
        {
1921
            if (item1.Relations.Find(x => x.UID.Equals(item2.UID)) != null &&
1922
                item2.Relations.Find(x => x.UID.Equals(item1.UID)) != null)
1923
                return true;
1924
            else
1925
                return false;
1926
        }
1927

    
1928
        private void SaveNozzleAndEquipment()
1929
        {
1930
            List<Item> nozzles = new List<Item>();
1931
            List<Equipment> equipments = new List<Equipment>();
1932
            foreach (Document document in Documents)
1933
            {
1934
                nozzles.AddRange(document.Items.FindAll(x => x.SubItemType == SubItemType.Nozzle));
1935
                equipments.AddRange(document.Equipments);
1936
            }
1937

    
1938

    
1939
            DataTable nozzleDT = new DataTable();
1940
            nozzleDT.Columns.Add("OID", typeof(string));
1941
            nozzleDT.Columns.Add("ITEMTAG", typeof(string));
1942
            nozzleDT.Columns.Add("XCOORDS", typeof(string));
1943
            nozzleDT.Columns.Add("YCOORDS", typeof(string));
1944
            nozzleDT.Columns.Add("Equipment_OID", typeof(string));
1945
            nozzleDT.Columns.Add("FLUID", typeof(string));
1946
            nozzleDT.Columns.Add("NPD", typeof(string));
1947
            nozzleDT.Columns.Add("PMC", typeof(string));
1948
            nozzleDT.Columns.Add("ROTATION", typeof(string));
1949
            nozzleDT.Columns.Add("FlowDirection", typeof(string));
1950

    
1951
            foreach (Item item in nozzles)
1952
            {
1953
                DataRow row = nozzleDT.NewRow();
1954
                row["OID"] = item.UID;
1955

    
1956
                Relation relation = item.Relations.Find(x => equipments.Find(y => y.UID == x.UID) != null);
1957
                if (relation != null)
1958
                {
1959
                    Equipment equipment = equipments.Find(x => x.UID == relation.UID);
1960
                    equipment.Nozzles.Add(item);
1961
                    row["ITEMTAG"] = string.Format("N{0}", string.Format("{0:D3}", equipment.Nozzles.Count + 100));
1962
                    row["Equipment_OID"] = equipment.UID;
1963
                    item.Equipment = equipment;
1964
                }
1965
                row["XCOORDS"] = (item.POINT[0] / DrawingWidth).ToString();
1966
                row["YCOORDS"] = (item.POINT[1] / DrawingHeight).ToString();
1967
                Attribute fluidAttr = item.LineNumber.Attributes.Find(x => x.Name == "FluidCode");
1968
                row["FLUID"] = fluidAttr != null ? fluidAttr.Value : string.Empty;
1969
                Attribute npdAttr = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
1970
                row["NPD"] = npdAttr != null ? npdAttr.Value : string.Empty;
1971
                Attribute pmcAttr = item.LineNumber.Attributes.Find(x => x.Name == "PipingMaterialsClass");
1972
                row["PMC"] = pmcAttr != null ? pmcAttr.Value : string.Empty;
1973

    
1974
                double angle = Math.PI * 2 - Convert.ToDouble(item.ANGLE);
1975
                if (angle >= Math.PI * 2)
1976
                    angle = angle - Math.PI * 2;
1977
                row["ROTATION"] = angle.ToString();
1978

    
1979
                if (item.Topology.Items.First().Equals(item))
1980
                    row["FlowDirection"] = "Outlet";
1981
                else if (item.Topology.Items.Last().Equals(item))
1982
                    row["FlowDirection"] = "Inlet";
1983
                else
1984
                    row["FlowDirection"] = string.Empty;
1985

    
1986
                nozzleDT.Rows.Add(row);
1987
            }
1988

    
1989
            DataTable equipDT = new DataTable();
1990
            equipDT.Columns.Add("OID", typeof(string));
1991
            equipDT.Columns.Add("ITEMTAG", typeof(string));
1992
            equipDT.Columns.Add("XCOORDS", typeof(string));
1993
            equipDT.Columns.Add("YCOORDS", typeof(string));
1994

    
1995
            foreach (Equipment equipment in equipments)
1996
            {
1997
                DataRow row = equipDT.NewRow();
1998
                row["OID"] = equipment.UID;
1999
                if (!string.IsNullOrEmpty(EquipTagNoAttributeName))
2000
                {
2001
                    Attribute attribute = equipment.Attributes.Find(x => x.Name == EquipTagNoAttributeName);
2002
                    if (attribute != null)
2003
                        equipment.ItemTag = attribute.Value;
2004
                }
2005
                else
2006
                    equipment.ItemTag = equipment.Name;
2007

    
2008
                row["ITEMTAG"] = equipment.ItemTag;
2009
                List<double> xList = equipment.POINT.Select(x => x[0]).ToList();
2010
                row["XCOORDS"] = (xList.Sum() / (double)xList.Count) / DrawingWidth;
2011

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

    
2015
                equipDT.Rows.Add(row);
2016
            }
2017

    
2018
            Equipment = equipDT;
2019
            Nozzle = nozzleDT;
2020
        }
2021

    
2022
        private void SavePSNData()
2023
        {
2024
            try
2025
            {
2026
                DataTable pathItemsDT = new DataTable();
2027
                pathItemsDT.Columns.Add("OID", typeof(string));
2028
                pathItemsDT.Columns.Add("SequenceData_OID", typeof(string));
2029
                pathItemsDT.Columns.Add("TopologySet_OID", typeof(string));
2030
                pathItemsDT.Columns.Add("BranchTopologySet_OID", typeof(string));
2031
                pathItemsDT.Columns.Add("PipeLine_OID", typeof(string));
2032
                pathItemsDT.Columns.Add("ITEMNAME", typeof(string));
2033
                pathItemsDT.Columns.Add("ITEMTAG", typeof(string));
2034
                pathItemsDT.Columns.Add("DESCRIPTION", typeof(string));
2035
                pathItemsDT.Columns.Add("Class", typeof(string));
2036
                pathItemsDT.Columns.Add("SubClass", typeof(string));
2037
                pathItemsDT.Columns.Add("TYPE", typeof(string));
2038
                pathItemsDT.Columns.Add("PIDNAME", typeof(string));
2039
                pathItemsDT.Columns.Add("Equipment_OID", typeof(string));
2040
                pathItemsDT.Columns.Add("NPD", typeof(string));
2041
                pathItemsDT.Columns.Add("GROUPTAG", typeof(string));
2042
                pathItemsDT.Columns.Add("PipeSystemNetwork_OID", typeof(string));
2043
                pathItemsDT.Columns.Add("ViewPipeSystemNetwork_OID", typeof(string));
2044
                pathItemsDT.Columns.Add("PipeRun_OID", typeof(string));
2045
                pathItemsDT.Columns.Add("EqpGroupTag", typeof(string));
2046
                pathItemsDT.Columns.Add("MainLineTag", typeof(string));
2047
                pathItemsDT.Columns.Add("EGTConnectedPoint", typeof(string));
2048
                pathItemsDT.Columns.Add("EGFlowDirection", typeof(string));
2049

    
2050
                DataTable sequenceDataDT = new DataTable();
2051
                sequenceDataDT.Columns.Add("OID", typeof(string));
2052
                sequenceDataDT.Columns.Add("SERIALNUMBER", typeof(string));
2053
                sequenceDataDT.Columns.Add("PathItem_OID", typeof(string));
2054
                sequenceDataDT.Columns.Add("TopologySet_OID_Key", typeof(string));
2055

    
2056
                DataTable pipeSystemNetworkDT = new DataTable();
2057
                pipeSystemNetworkDT.Columns.Add("OID", typeof(string));
2058
                pipeSystemNetworkDT.Columns.Add("Type", typeof(string));
2059
                pipeSystemNetworkDT.Columns.Add("OrderNumber", typeof(string));
2060
                pipeSystemNetworkDT.Columns.Add("Pipeline_OID", typeof(string));
2061
                pipeSystemNetworkDT.Columns.Add("FROM_DATA", typeof(string));
2062
                pipeSystemNetworkDT.Columns.Add("TO_DATA", typeof(string));
2063
                pipeSystemNetworkDT.Columns.Add("TopologySet_OID_Key", typeof(string));
2064
                pipeSystemNetworkDT.Columns.Add("PSNRevisionNumber", typeof(string));
2065
                pipeSystemNetworkDT.Columns.Add("PBS", typeof(string));
2066
                pipeSystemNetworkDT.Columns.Add("Drawings", typeof(string));
2067
                pipeSystemNetworkDT.Columns.Add("IsValid", typeof(string));
2068
                pipeSystemNetworkDT.Columns.Add("Status", typeof(string));
2069
                pipeSystemNetworkDT.Columns.Add("IncludingVirtualData", typeof(string));
2070
                pipeSystemNetworkDT.Columns.Add("PSNAccuracy", typeof(string));
2071
                pipeSystemNetworkDT.Columns.Add("Pocket", typeof(string));
2072
                pipeSystemNetworkDT.Columns.Add("EGTag", typeof(string));
2073
                pipeSystemNetworkDT.Columns.Add("HasMLTags", typeof(string));
2074
                pipeSystemNetworkDT.Columns.Add("AFC", typeof(string));
2075
                pipeSystemNetworkDT.Columns.Add("PUMP", typeof(string));
2076

    
2077
                DataTable topologySetDT = new DataTable();
2078
                topologySetDT.Columns.Add("OID", typeof(string));
2079
                topologySetDT.Columns.Add("Type", typeof(string));
2080
                topologySetDT.Columns.Add("SubType", typeof(string));
2081
                topologySetDT.Columns.Add("HeadItemTag", typeof(string));
2082
                topologySetDT.Columns.Add("TailItemTag", typeof(string));
2083
                topologySetDT.Columns.Add("HeadItemSPID", typeof(string));
2084
                topologySetDT.Columns.Add("TailItemSPID", typeof(string));
2085

    
2086
                DataTable pipelineDT = new DataTable();
2087
                pipelineDT.Columns.Add("OID", typeof(string));
2088
                pipelineDT.Columns.Add("PipeSystem_OID", typeof(string));
2089
                pipelineDT.Columns.Add("FLUID", typeof(string));
2090
                pipelineDT.Columns.Add("PMC", typeof(string));
2091
                pipelineDT.Columns.Add("SEQNUMBER", typeof(string));
2092
                pipelineDT.Columns.Add("INSULATION", typeof(string));
2093
                pipelineDT.Columns.Add("FROM_DATA", typeof(string));
2094
                pipelineDT.Columns.Add("TO_DATA", typeof(string));
2095
                pipelineDT.Columns.Add("Unit", typeof(string));
2096

    
2097
                DataTable pipesystemDT = new DataTable();
2098
                pipesystemDT.Columns.Add("OID", typeof(string));
2099
                pipesystemDT.Columns.Add("DESCRIPTION", typeof(string));
2100
                pipesystemDT.Columns.Add("FLUID", typeof(string));
2101
                pipesystemDT.Columns.Add("PMC", typeof(string));
2102
                pipesystemDT.Columns.Add("PipeLineQty", typeof(string));
2103
                pipesystemDT.Columns.Add("GroundLevel", typeof(string));
2104

    
2105
                // Set Vent/Drain Info
2106
                List<VentDrainInfo> VentDrainInfos = new List<VentDrainInfo>();
2107
                DataTable dt = DB.SelectVentDrainSetting();
2108
                foreach (DataRow row in dt.Rows)
2109
                {
2110
                    string groupID = row["GROUP_ID"].ToString();
2111
                    string desc = row["DESCRIPTION"].ToString();
2112
                    int index = Convert.ToInt32(row["INDEX"]);
2113
                    string name = row["NAME"].ToString();
2114

    
2115
                    VentDrainInfo ventDrainInfo = VentDrainInfos.Find(x => x.UID.Equals(groupID));
2116
                    if (ventDrainInfo == null)
2117
                    {
2118
                        ventDrainInfo = new VentDrainInfo(groupID);
2119
                        ventDrainInfo.Description = desc;
2120
                        VentDrainInfos.Add(ventDrainInfo);
2121
                    }
2122

    
2123
                    ventDrainInfo.VentDrainItems.Add(new VentDrainItem()
2124
                    {
2125
                        Index = index,
2126
                        Name = name
2127
                    });
2128
                }
2129
                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2130
                    ventDrainInfo.VentDrainItems = ventDrainInfo.VentDrainItems.OrderBy(x => x.Index).ToList();
2131

    
2132
                #region Keyword Info
2133
                KeywordInfo KeywordInfos = new KeywordInfo();
2134
                DataTable dtKeyword = DB.SelectKeywordsSetting();
2135
                foreach (DataRow row in dtKeyword.Rows)
2136
                {
2137
                    int index = Convert.ToInt32(row["INDEX"]);
2138
                    string name = row["NAME"].ToString();
2139
                    string keyword = row["KEYWORD"].ToString();
2140

    
2141
                    //KeywordInfo keywordInfo = new KeywordInfo();   
2142
                    KeywordInfos.KeywordItems.Add(new KeywordItem()
2143
                    {
2144
                        Index = index,
2145
                        Name = name,
2146
                        Keyword = keyword
2147
                    });
2148
                }
2149
                #endregion
2150

    
2151
                #region ValveGrouping Info
2152
                ValveGroupInfo ValveGrouping = new ValveGroupInfo();
2153
                DataTable dtValveGroupung = DB.SelectValveGroupItemsSetting();
2154
                foreach (DataRow row in dtValveGroupung.Rows)
2155
                {
2156
                    ValveGrouping.ValveGroupItems.Add(new ValveGroupItem()
2157
                    {
2158
                        OID = row["OID"].ToString(),
2159
                        GroupType = row["GroupType"].ToString(),
2160
                        TagIdentifier = row["TagIdentifier"].ToString(),
2161
                        AttributeName = row["AttributeName"].ToString(),
2162
                        SppidSymbolName = row["SppidSymbolName"].ToString()
2163
                    });
2164
                }
2165
                #endregion
2166

    
2167
                #region EquipmentNoPocket Info
2168
                EquipmentNoPocketInfo EquipmentNoPocket = new EquipmentNoPocketInfo();
2169
                DataTable dtEquipmentNoPocket = DB.SelectEquipmentNoPocketSetting();
2170
                foreach (DataRow row in dtEquipmentNoPocket.Rows)
2171
                {
2172
                    EquipmentNoPocket.EquipmentNoPocketItem.Add(new EquipmentNoPocketItem()
2173
                    {
2174
                        Index = Convert.ToInt32(row["INDEX"]),
2175
                        Type = row["TYPE"].ToString(),
2176
                        Name = row["NAME"].ToString()
2177
                    });
2178
                }
2179
                #endregion
2180

    
2181
                #region EquipmentAirFinCooler Info
2182
                EquipmentAirFinCoolerInfo EquipmentAirFinCooler = new EquipmentAirFinCoolerInfo();
2183
                DataTable dtEquipmentAirFinCooler = DB.SelectAirFinCoolerSetting();
2184
                foreach (DataRow row in dtEquipmentAirFinCooler.Rows)
2185
                {
2186
                    EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Add(new EquipmentAirFinCoolerItem()
2187
                    {
2188
                        Type = row["Type"].ToString(),
2189
                        Name = row["Name"].ToString()
2190
                    });
2191
                }
2192
                #endregion
2193

    
2194
                // key = 미입력 branch
2195
                Dictionary<Item, Item> startBranchDic = new Dictionary<Item, Item>();
2196
                Dictionary<Item, Item> endBranchDic = new Dictionary<Item, Item>();
2197
                DataTable PSNFluidDT = DB.SelectPSNFluidCode();
2198
                DataTable PSNPMCDT = DB.SelectPSNPIPINGMATLCLASS();
2199
                foreach (PSNItem PSNItem in PSNItems)
2200
                {
2201
                    try
2202
                    {
2203
                        int psnOrder = 0;
2204
                        int index = 0;
2205
                        bool bPSNStart = true;
2206
                        string sPSNData = string.Empty;
2207
                        bool bVentDrain = false;
2208

    
2209
                      List<Group> Groups = PSNItem.Groups;
2210
                        Dictionary<string, List<Item>> keyValuePairs = new Dictionary<string, List<Item>>();
2211
                        List<Item> valveGroupingItem = new List<Item>();
2212

    
2213
                        //VentDrain 검사
2214
                        if (PSNItem.Groups.Count.Equals(1))
2215
                        {
2216
                            List<VentDrainInfo> endInfos = new List<VentDrainInfo>();
2217
                            for (int g = 0; g < Groups.Count; g++)
2218
                            {
2219
                                Group group = Groups[g];
2220

    
2221
                                foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2222
                                {
2223
                                    if(!bVentDrain)
2224
                                    {
2225
                                        for (int i = 0; i < group.Items.Count; i++)
2226
                                        {
2227
                                            Item item = group.Items[i];
2228
                                            if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2229
                                                endInfos.Add(ventDrainInfo);
2230
                                            else
2231
                                            {
2232
                                                endInfos.Clear();
2233
                                                if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2234
                                                    endInfos.Add(ventDrainInfo);
2235
                                            }
2236

    
2237
                                            if (ventDrainInfo.VentDrainItems.Count().Equals(endInfos.Count()))
2238
                                            {
2239
                                                bVentDrain = true;
2240
                                                break;
2241
                                            }
2242
                                        }
2243
                                    }                                   
2244
                                }                               
2245

    
2246
                                if (!bVentDrain)
2247
                                {
2248
                                    endInfos = new List<VentDrainInfo>();
2249

    
2250
                                    foreach (VentDrainInfo ventDrainInfo in VentDrainInfos)
2251
                                    {
2252
                                        if (!bVentDrain)
2253
                                        {
2254
                                            for (int i = 0; i < group.Items.Count; i++)
2255
                                            {
2256
                                                Item item = group.Items[group.Items.Count - i - 1];
2257

    
2258
                                                if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2259
                                                    endInfos.Add(ventDrainInfo);
2260
                                                else
2261
                                                {
2262
                                                    endInfos.Clear();
2263
                                                    if (ventDrainInfo.VentDrainItems[endInfos.Count()].Name.Equals(item.Name))
2264
                                                        endInfos.Add(ventDrainInfo);
2265
                                                }
2266

    
2267
                                                if (ventDrainInfo.VentDrainItems.Count().Equals(endInfos.Count()))
2268
                                                {
2269
                                                    bVentDrain = true;
2270
                                                    break;
2271
                                                }
2272
                                            }
2273
                                        }
2274
                                    }
2275
                                }
2276
                            }
2277
                        }
2278

    
2279
                        try
2280
                        {
2281
                            foreach (Group group in PSNItem.Groups)
2282
                            {
2283
                                foreach (Item item in group.Items)
2284
                                {
2285
                                    string VgTag = string.Empty;
2286
                                    
2287
                                    if (ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).Count() > 0)
2288
                                    {
2289
                                        ValveGroupItem valveitem = ValveGrouping.ValveGroupItems.Where(x => x.SppidSymbolName == item.Name).First();
2290
                                        string value = string.Empty;
2291

    
2292
                                        if (valveitem.GroupType == "Scope Break" || valveitem.AttributeName == "NoSelection" || valveitem.AttributeName == string.Empty)
2293
                                            value = "NoSelection";
2294
                                        else
2295
                                        {
2296
                                            if(item.Attributes.Find(x => x.Name == valveitem.AttributeName) == null)
2297
                                                value = "NoSelection";
2298
                                            else
2299
                                                value = item.Attributes.Find(x => x.Name == valveitem.AttributeName).Value;
2300
                                        }
2301

    
2302
                                        if (valveitem.GroupType == "Scope Break")
2303
                                            VgTag = "Scope Break";
2304
                                        else
2305
                                            VgTag = valveitem.SppidSymbolName + "\\" + value;
2306

    
2307
                                    }
2308

    
2309
                                    string PathitemUID = string.Empty;
2310
                                    if (item.BranchItems.Count == 0)
2311
                                    {
2312
                                        PathitemUID = item.UID;
2313
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2314
                                        CreateSequenceDataDataRow(PathitemUID);
2315
                                        index++;
2316
                                    }
2317
                                    else
2318
                                    {
2319
                                        PathitemUID = item.UID + "_L1";
2320
                                        CreatePathItemsDataRow(PathitemUID, item.ID2DBType, VgTag);
2321
                                        CreateSequenceDataDataRow(PathitemUID);
2322
                                        index++;
2323
                                        for (int i = 0; i < item.BranchItems.Count; i++)
2324
                                        {
2325
                                            CreatePathItemsDataRow(string.Format(item.UID + "_B{0}", i + 1), "Branch", string.Empty, item.BranchItems[i].Topology.FullName, item.BranchItems[i]);
2326
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_B{0}", i + 1));
2327
                                            index++;
2328

    
2329
                                            CreatePathItemsDataRow(string.Format(item.UID + "_L{0}", i + 2), item.ID2DBType);
2330
                                            CreateSequenceDataDataRow(string.Format(item.UID + "_L{0}", i + 2));
2331
                                            index++;
2332

    
2333
                                            if (item.BranchItems[i].Relations[0].Item != null && item.BranchItems[i].Relations[0].Item == item)
2334
                                                startBranchDic.Add(item.BranchItems[i], item);
2335
                                            else if (item.BranchItems[i].Relations[1].Item != null && item.BranchItems[i].Relations[1].Item == item)
2336
                                                endBranchDic.Add(item.BranchItems[i], item);
2337
                                        }
2338
                                    }
2339

    
2340
                                    if (bPSNStart)
2341
                                    {
2342
                                        CreatePipeSystemNetworkDataRow();
2343
                                        sPSNData = item.TopologyData;
2344
                                        psnOrder++;
2345
                                        bPSNStart = false;
2346
                                    }
2347
                                    else
2348
                                    {
2349
                                        if (item.TopologyData != sPSNData)
2350
                                        {
2351
                                            CreatePipeSystemNetworkDataRow();
2352
                                            sPSNData = item.TopologyData;
2353
                                            psnOrder++;
2354
                                        }
2355
                                    }
2356

    
2357
                                    void CreatePathItemsDataRow(string itemOID, string itemType, string GROUPTAG = "", string branchTopologyName = "", Item branchItem = null)
2358
                                    {
2359
                                        DataRow newRow = pathItemsDT.NewRow();
2360

    
2361
                                        if (itemType == "Nozzles")
2362
                                        {
2363
                                            newRow["Equipment_OID"] = item.Equipment != null ? item.Equipment.UID : "";
2364
                                        }
2365

    
2366
                                        newRow["OID"] = itemOID;
2367
                                        newRow["SequenceData_OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2368
                                        newRow["TopologySet_OID"] = item.Topology.FullName;
2369
                                        newRow["BranchTopologySet_OID"] = branchTopologyName;
2370
                                        newRow["PipeLine_OID"] = item.PSNPipeLineID;
2371
                                        newRow["ITEMNAME"] = GetItemName(item, itemOID);
2372
                                        newRow["ITEMTAG"] = GetItemTag(item);
2373
                                        newRow["Class"] = GetClass(item, itemOID);
2374
                                        string subClass = GetSubClass(item, itemOID);
2375
                                        newRow["SubClass"] = subClass;
2376

    
2377
                                        if (item.ItemType == ItemType.Symbol)
2378
                                            newRow["TYPE"] = item.ID2DBName;
2379
                                        else if (item.ItemType == ItemType.Line)
2380
                                            newRow["TYPE"] = item.ID2DBType;
2381
                                        newRow["PIDNAME"] = group.Document.DrawingName;
2382

    
2383
                                        // NPD
2384
                                        if (item.LineNumber != null)
2385
                                        {
2386
                                            Attribute attribute = item.LineNumber.Attributes.Find(x => x.Name == "NominalDiameter");
2387
                                            if (attribute != null)
2388
                                                newRow["NPD"] = attribute.Value;
2389
                                        }
2390
                                        else
2391
                                            newRow["NPD"] = null;
2392

    
2393
                                        newRow["GROUPTAG"] = GROUPTAG;
2394
                                        newRow["PipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2395
                                        if (branchItem == null)
2396
                                            newRow["ViewPipeSystemNetwork_OID"] = PSNItem.PSN_OID();
2397
                                        else
2398
                                            newRow["ViewPipeSystemNetwork_OID"] = branchItem.PSNItem.PSN_OID();
2399

    
2400
                                        newRow["PipeRun_OID"] = item.LineNumber != null ? item.LineNumber.Name : string.Empty;
2401
                                        newRow["EGTConnectedPoint"] = 0;
2402
                                        pathItemsDT.Rows.Add(newRow);
2403
                                    }
2404

    
2405

    
2406
                                    void CreateSequenceDataDataRow(string itemOID)
2407
                                    {
2408
                                        DataRow newRow = sequenceDataDT.NewRow();
2409
                                        newRow["OID"] = string.Format(item.Topology.FullName + "_{0}", index);
2410
                                        newRow["SERIALNUMBER"] = string.Format("{0}", index);
2411
                                        newRow["PathItem_OID"] = itemOID;
2412
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2413

    
2414
                                        sequenceDataDT.Rows.Add(newRow);
2415
                                    }
2416

    
2417
                                    void CreatePipeSystemNetworkDataRow()
2418
                                    {
2419
                                        LineNumber lineNumber = item.Document.LineNumbers.Find(x => x.UID == item.Owner);
2420
                                        string FluidCode = string.Empty;
2421
                                        if (lineNumber != null)
2422
                                        {
2423
                                            List<Attribute> att = lineNumber.Attributes;
2424
                                            if (att != null)
2425
                                            {
2426
                                                List<string> oid = new List<string>();
2427
                                                FluidCode = att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault() != null ? att.Where(x => x.Name.ToUpper().Equals("FLUIDCODE")).FirstOrDefault().Value : string.Empty;
2428
                                                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;
2429
                                                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;
2430
                                                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;
2431
                                                //InsulationPurpose
2432
                                                if (!string.IsNullOrEmpty(FluidCode)) oid.Add(FluidCode);
2433
                                                if (!string.IsNullOrEmpty(PMC)) oid.Add(PMC);
2434

    
2435
                                                string PipeSystem_OID = string.Join("-", oid);
2436

    
2437
                                                if (!string.IsNullOrEmpty(SEQNUMBER)) oid.Add(SEQNUMBER);
2438
                                                if (!string.IsNullOrEmpty(INSULATION)) oid.Add(INSULATION);
2439

    
2440
                                                string OID = string.Join("-", oid);
2441
                                                string FluidCodeGL = string.Empty;
2442
                                                string PMCGL = string.Empty;
2443

    
2444

    
2445
                                                if (pipelineDT.Select(string.Format("OID = '{0}'", OID)).Count() == 0)
2446
                                                {
2447
                                                    DataRow newPipelineRow = pipelineDT.NewRow();
2448
                                                    newPipelineRow["OID"] = OID;
2449
                                                    newPipelineRow["PipeSystem_OID"] = PipeSystem_OID;
2450
                                                    newPipelineRow["FLUID"] = FluidCode;
2451
                                                    newPipelineRow["PMC"] = PMC;
2452
                                                    newPipelineRow["SEQNUMBER"] = SEQNUMBER;
2453
                                                    newPipelineRow["INSULATION"] = INSULATION;
2454
                                                    newPipelineRow["FROM_DATA"] = string.Empty;
2455
                                                    newPipelineRow["TO_DATA"] = string.Empty;
2456
                                                    newPipelineRow["Unit"] = PSNItem.GetPBSData();
2457
                                                    pipelineDT.Rows.Add(newPipelineRow);
2458
                                                }
2459

    
2460
                                                if (pipesystemDT.Select(string.Format("OID = '{0}'", PipeSystem_OID)).Count() == 0)
2461
                                                {
2462
                                                    DataRow newPipesystemRow = pipesystemDT.NewRow();
2463
                                                    newPipesystemRow["OID"] = PipeSystem_OID;
2464
                                                    newPipesystemRow["DESCRIPTION"] = string.Empty;
2465
                                                    newPipesystemRow["FLUID"] = FluidCode;
2466
                                                    newPipesystemRow["PMC"] = PMC;
2467
                                                    newPipesystemRow["PipeLineQty"] = string.Empty;
2468
                                                    string GroundLevel = string.Empty;
2469
                                                    if (!string.IsNullOrEmpty(FluidCode) && !string.IsNullOrEmpty(PMC))
2470
                                                    {
2471
                                                        FluidCodeGL = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("GroundLevel");
2472
                                                        PMCGL = PSNPMCDT.Select(string.Format("Code= '{0}'", PMC)).FirstOrDefault().Field<string>("GroundLevel");
2473
                                                        if (FluidCodeGL == "AG" && PMCGL == "AG")
2474
                                                            GroundLevel = "AG";
2475
                                                        else if (FluidCodeGL == "UG" && PMCGL == "UG")
2476
                                                            GroundLevel = "UG";
2477
                                                        else
2478
                                                            GroundLevel = "AG_UG";
2479
                                                    }
2480
                                                    newPipesystemRow["GroundLevel"] = GroundLevel;
2481

    
2482
                                                    pipesystemDT.Rows.Add(newPipesystemRow);
2483
                                                }
2484
                                            }
2485
                                        }
2486

    
2487
                                        DataRow newRow = pipeSystemNetworkDT.NewRow();
2488
                                        newRow["OID"] = PSNItem.PSN_OID();
2489

    
2490
                                        newRow["OrderNumber"] = psnOrder;
2491
                                        newRow["Pipeline_OID"] = item.PSNPipeLineID;
2492
                                        PSNItem.KeywordInfos = KeywordInfos;
2493
                                        PSNItem.Nozzle = Nozzle;
2494

    
2495
                                        string FromType = string.Empty;
2496
                                        Item From_item = new Item();
2497

    
2498
                                        string FROM_DATA = PSNItem.GetFromData(ref FromType, ref From_item);
2499
                                        string status = string.Empty;
2500
                                        status = PSNItem.Status;                                      
2501

    
2502
                                        if (PSNItem.IsKeyword)
2503
                                        {
2504
                                            PSNItem.StartType = PSNType.Equipment;
2505
                                        }
2506
                                        string ToType = string.Empty;
2507
                                        Item To_item = new Item();
2508
                                        string TO_DATA = PSNItem.GetToData(ref ToType, ref To_item);
2509
                                        if (PSNItem.IsKeyword)
2510
                                        {
2511
                                            PSNItem.EndType = PSNType.Equipment;
2512
                                        }
2513
                                                   
2514
                                        newRow["FROM_DATA"] = FROM_DATA;
2515
                                        newRow["TO_DATA"] = TO_DATA;
2516
                                       
2517
                                        newRow["Type"] = PSNItem.GetPSNType();
2518

    
2519
                                       
2520
                                        if(psnOrder == 0) //order 0일땐 그냥 붙여줌
2521
                                        {
2522
                                            if (!string.IsNullOrEmpty(PSNItem.Status)) //to에 status가 있다면
2523
                                            {
2524
                                                status += PSNItem.Status;
2525
                                            }                                            
2526
                                        }
2527
                                        else if (psnOrder > 0) //0보다 크면 
2528
                                        {
2529
                                            DataRow dr = pipeSystemNetworkDT.Select(string.Format("OID = '{0}' AND OrderNumber = {1}", PSNItem.PSN_OID(), psnOrder - 1)).FirstOrDefault();
2530
                                            if (psnOrder == 1) //1이면 0번 Order에 From Status 값만 남김 
2531
                                            {
2532
                                                dr["Status"] = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty; //status;
2533
                                            }
2534
                                            if (psnOrder > 1) // 2 -> 1 3->2 엔 status 값 삭제
2535
                                            {
2536
                                                dr["Status"] = string.Empty;
2537
                                            }
2538

    
2539
                                            status = PSNItem.Status;
2540
                                            //if (dr != null)
2541
                                            //{
2542
                                            //    newRow["FROM_DATA"] = dr.Field<string>("FROM_DATA");
2543
                                            //    newRow["TO_DATA"] = dr.Field<string>("TO_DATA");
2544
                                            //    newRow["Type"] = dr.Field<string>("Type");
2545
                                            //}
2546
                                        }
2547

    
2548
                                        
2549
                                    
2550
                                        status = !string.IsNullOrEmpty(status) ? status.Remove(0, 2) : string.Empty;
2551
                                        string[] st = status.Split(new string[] { ", " }, StringSplitOptions.None);
2552
                                        if (st.Count() > 1)
2553
                                        {
2554
                                            status = string.Join(", ", st.Distinct());                                                                                     
2555
                                        }
2556
                                        newRow["TopologySet_OID_Key"] = item.Topology.FullName;
2557
                                        newRow["PSNRevisionNumber"] = string.Format("V{0:D4}", Revision);
2558

    
2559

    
2560
                                        newRow["IsValid"] = PSNItem.IsValid;
2561
                                        newRow["Status"] = status;
2562
                                        newRow["PBS"] = PSNItem.GetPBSData();
2563

    
2564
                                        List<string> drawingNames = new List<string>();
2565
                                        foreach (Group _group in PSNItem.Groups)
2566
                                        {
2567
                                            if (!drawingNames.Contains(_group.Document.DrawingName))
2568
                                            {
2569
                                                if (drawingNames.Count == 0)
2570
                                                    newRow["Drawings"] = _group.Document.DrawingName;
2571
                                                else
2572
                                                    newRow["Drawings"] = newRow["Drawings"] + ", " + _group.Document.DrawingName;
2573
                                                drawingNames.Add(_group.Document.DrawingName);
2574
                                            }
2575
                                        }
2576

    
2577
                                        // VentDrain의 경우 제외 요청 (데이터를 아예 제거하였을 경우 후 가공에서 문제가 생김 마지막에 지우는것으로 변경)
2578
                                        if (bVentDrain)
2579
                                            newRow["IncludingVirtualData"] = "Vent_Drain";
2580
                                        else
2581
                                            newRow["IncludingVirtualData"] = "No";
2582
                                        //    return;
2583
                                        //newRow["IncludingVirtualData"] = "No";
2584
                                        newRow["PSNAccuracy"] = "100";
2585

    
2586
                                        string Pocket = "No";
2587
                                        string Condition = PSNFluidDT.Select(string.Format("Code = '{0}'", FluidCode)).FirstOrDefault().Field<string>("Condition");
2588
                                        if (Condition.Equals("Flare"))
2589
                                            Pocket = "Yes";
2590

    
2591
                                        if (item.ID2DBType == "Nozzles" && PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null) 
2592
                                        {
2593
                                          //  string itemName = From_item.Name;
2594
                                            Equipment Equipment = From_item.Equipment;
2595
                                      
2596
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name && x.Type != "Pump").FirstOrDefault();
2597
                                          
2598

    
2599
                                            if (nopocket != null)
2600
                                            {
2601
                                                DataRow bNozzle = null;
2602
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2603
                                                {
2604
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, From_item.UID)).FirstOrDefault();
2605
                                                    if (drNozzle != null)
2606
                                                    {
2607
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2608
                                                        {
2609
                                                            bNozzle = drNozzle;
2610
                                                        }
2611

    
2612
                                                        if (bNozzle == null)
2613
                                                        {
2614
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2615

    
2616
                                                            if (drNozzle != null)
2617
                                                            {
2618
                                                                bNozzle = drNozzle;
2619
                                                                foreach (DataRow it in nozzleRows)
2620
                                                                {
2621
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2622
                                                                    {
2623
                                                                        bNozzle = null;
2624
                                                                        break;
2625
                                                                    }
2626
                                                                }
2627
                                                            }
2628
                                                        }
2629
                                                    }
2630

    
2631
                                                    if (bNozzle != null)
2632
                                                        Pocket = "Yes";
2633
                                                }
2634
                                                else
2635
                                                    Pocket = "Yes";
2636
                                            }
2637
                                        }
2638
                                        
2639
                                        if (item.ID2DBType == "Nozzles" && PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null) //To는 전체
2640
                                        {
2641
                                           // string itemName = To_item.Name;
2642
                                            Equipment Equipment = To_item.Equipment;
2643
                                            EquipmentNoPocketItem nopocket = EquipmentNoPocket.EquipmentNoPocketItem.Where(x => x.Name == Equipment.Name).FirstOrDefault();
2644
                                            if (nopocket != null)
2645
                                            {
2646
                                                DataRow bNozzle = null;
2647
                                                if (nopocket.Type.Equals("Vertical Vessel"))
2648
                                                {
2649
                                                    DataRow drNozzle = Nozzle.Select(string.Format("Equipment_OID = '{0}' AND OID = '{1}'", Equipment.UID, To_item.UID)).FirstOrDefault();
2650
                                                    if(drNozzle != null)
2651
                                                    {
2652
                                                        if (drNozzle.Field<string>("Rotation").Length >= 4 && drNozzle.Field<string>("Rotation").Substring(0, 4) == "4.71")
2653
                                                        {
2654
                                                            bNozzle = drNozzle;
2655
                                                        }
2656

    
2657
                                                        if (bNozzle == null)
2658
                                                        {
2659
                                                            DataRow[] nozzleRows = Nozzle.Select(string.Format("Equipment_OID = '{0}'", Equipment.UID));
2660

    
2661
                                                            if (drNozzle != null)
2662
                                                            {
2663
                                                                bNozzle = drNozzle;
2664
                                                                foreach (DataRow it in nozzleRows)
2665
                                                                {
2666
                                                                    if (Convert.ToDecimal(drNozzle.Field<string>("Ycoords")) > Convert.ToDecimal(it.Field<string>("Ycoords")))
2667
                                                                    {
2668
                                                                        bNozzle = null;
2669
                                                                        break;
2670
                                                                    }
2671
                                                                }
2672
                                                            }
2673
                                                        }
2674
                                                    }                                                   
2675

    
2676
                                                    if (bNozzle != null)
2677
                                                        Pocket = "Yes";
2678
                                                }
2679
                                                else
2680
                                                    Pocket = "Yes";
2681
                                            }
2682
                                        }
2683
                                        
2684
                                        newRow["Pocket"] = Pocket;
2685
                                        string AFC = "P2";
2686
                                        if(PSNItem.StartType == PSNType.Equipment && From_item.Equipment != null)
2687
                                        {
2688
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2689
                                                AFC = "P1\\" + From_item.Equipment.Name;
2690
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(From_item.Equipment.Name)).Count() > 0)
2691
                                                newRow["PUMP"] = "PUMP";
2692
                                        }
2693

    
2694
                                        if (PSNItem.EndType == PSNType.Equipment && To_item.Equipment != null)
2695
                                        {
2696
                                            if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type != "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2697
                                                AFC = "P1\\" + To_item.Equipment.Name;
2698
                                            else if (EquipmentAirFinCooler.EquipmentAirFinCoolerItem.Where(x => x.Type == "Pump" && x.Name.Equals(To_item.Equipment.Name)).Count() > 0)
2699
                                                newRow["PUMP"] = "PUMP";
2700
                                        }
2701

    
2702
                                        newRow["AFC"] = AFC;
2703

    
2704
                                        newRow["EGTag"] = string.Empty;
2705
                                        newRow["HasMLTags"] = "False";
2706
                                        pipeSystemNetworkDT.Rows.Add(newRow);
2707
                                    }
2708
                                }
2709

    
2710
                            }
2711
                        
2712

    
2713
                        }
2714
                        catch (Exception ex)
2715
                        {
2716
                            Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2717
                            MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2718
                        }
2719

    
2720
                        //TopologySet 관련
2721
                        foreach (Topology topology in PSNItem.Topologies)
2722
                        {
2723
                            DataRow newRow = topologySetDT.NewRow();
2724
                            newRow["OID"] = topology.FullName;
2725
                            newRow["Type"] = topology.FullName.Split(new char[] { '-' }).Last().StartsWith("M") ? "Main" : "Branch";
2726
                            if (bVentDrain)
2727
                                newRow["SubType"] = "Vent_Drain";
2728
                            else
2729
                                newRow["SubType"] = null;
2730
                            newRow["HeadItemTag"] = GetItemTag(topology.Items.Last());
2731
                            newRow["TailItemTag"] = GetItemTag(topology.Items.First());
2732
                            newRow["HeadItemSPID"] = topology.Items.Last().UID;
2733
                            newRow["TailItemSPID"] = topology.Items.First().UID;
2734
                            topologySetDT.Rows.Add(newRow);
2735
                        }
2736

    
2737
                    }
2738
                    catch (Exception ee)
2739
                    {
2740

    
2741
                    }
2742
                }
2743

    
2744

    
2745
                foreach (var item in startBranchDic)
2746
                {
2747
                    string uid = item.Key.UID;
2748
                    string topologyName = item.Value.Topology.FullName;
2749
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2750

    
2751
                    if (rows.Length == 1)
2752
                    {
2753
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2754
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2755
                    }
2756
                    else if (rows.Length > 1)
2757
                    {
2758
                        DataRow targetRow = null;
2759
                        int index = int.MaxValue;
2760
                        foreach (DataRow row in rows)
2761
                        {
2762
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2763
                            if (split.StartsWith("L"))
2764
                            {
2765
                                int num = Convert.ToInt32(split.Remove(0, 1));
2766
                                if (index > num)
2767
                                {
2768
                                    index = num;
2769
                                    targetRow = row;
2770
                                }
2771
                            }
2772
                        }
2773

    
2774
                        if (targetRow != null)
2775
                        {
2776
                            targetRow["BranchTopologySet_OID"] = topologyName;
2777
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2778
                        }
2779
                    }
2780
                }
2781

    
2782
                foreach (var item in endBranchDic)
2783
                {
2784
                    string uid = item.Key.UID;
2785
                    string topologyName = item.Value.Topology.FullName;
2786
                    DataRow[] rows = pathItemsDT.Select(string.Format("OID LIKE '{0}%'", uid));
2787
                    if (rows.Length == 1)
2788
                    {
2789
                        rows.First()["BranchTopologySet_OID"] = topologyName;
2790
                        rows.First()["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2791
                    }
2792
                    else if (rows.Length > 1)
2793
                    {
2794
                        DataRow targetRow = null;
2795
                        int index = int.MinValue;
2796
                        foreach (DataRow row in rows)
2797
                        {
2798
                            string split = row["OID"].ToString().Split(new char[] { '_' })[1];
2799
                            if (split.StartsWith("L"))
2800
                            {
2801
                                int num = Convert.ToInt32(split.Remove(0, 1));
2802
                                if (index < num)
2803
                                {
2804
                                    index = num;
2805
                                    targetRow = row;
2806
                                }
2807
                            }
2808
                        }
2809

    
2810
                        if (targetRow != null)
2811
                        {
2812
                            targetRow["BranchTopologySet_OID"] = topologyName;
2813
                            targetRow["ViewPipeSystemNetwork_OID"] = item.Value.PSNItem.PSN_OID();
2814
                        }
2815
                    }
2816
                }
2817

    
2818
                PathItems = pathItemsDT;
2819
                SequenceData = sequenceDataDT;
2820
                PipeSystemNetwork = pipeSystemNetworkDT;
2821
                TopologySet = topologySetDT;
2822
                PipeLine = pipelineDT;
2823
                PipeSystem = pipesystemDT;
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

    
2832
        private double AccuracyCalculation(List<double> lstAcc, double acc)
2833
        {
2834
            foreach (double lacc in lstAcc)
2835
            {
2836
                acc *= lacc;
2837
            }
2838
            return acc;
2839
        }
2840

    
2841
        private void UpdateSubType()
2842
        {
2843
            try
2844
            {
2845
                foreach (PSNItem PSNItem in PSNItems)
2846
                {
2847
                    if (PSNItem.IsBypass)
2848
                    {
2849
                        foreach (Topology topology in PSNItem.Topologies)
2850
                        {
2851
                            DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2852
                            if (rows.Length.Equals(1))
2853
                                rows.First()["SubType"] = "Bypass";
2854
                        }
2855
                    }
2856

    
2857
                    if (PSNItem.StartType == PSNType.Header)
2858
                    {
2859
                        Topology topology = PSNItem.Topologies.First();
2860
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2861
                        if (rows.Length.Equals(1))
2862
                            rows.First()["SubType"] = "Header";
2863
                    }
2864
                    else if (PSNItem.EndType == PSNType.Header)
2865
                    {
2866
                        Topology topology = PSNItem.Topologies.Last();
2867
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2868
                        if (rows.Length.Equals(1))
2869
                            rows.First()["SubType"] = "Header";
2870
                    }
2871
                }
2872

    
2873

    
2874
                foreach (Topology topology in Topologies)
2875
                {
2876
                    try
2877
                    {
2878
                        DataRow[] rows = TopologySet.Select(string.Format("OID = '{0}'", topology.FullName));
2879

    
2880
                        if (rows.Count() > 0)
2881
                        {
2882
                            if (rows.Length.Equals(1) && rows.First()["SubType"] == null || string.IsNullOrEmpty(rows.First()["SubType"].ToString()))
2883
                            {
2884
                                if (topology.Items == null)
2885
                                    continue;
2886

    
2887
                                Item firstItem = topology.Items.First();
2888
                                Item lastItem = topology.Items.Last();
2889

    
2890
                                List<Relation> relations = new List<Relation>();
2891

    
2892
                                if (firstItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2893
                                    relations.AddRange(firstItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2894

    
2895
                                if (lastItem.Relations.FindAll(x => x.Item == null).Count() != 0)
2896
                                    relations.AddRange(lastItem.Relations.FindAll(x => x.Item != null && x.Item.Topology.ID != topology.ID));
2897

    
2898
                                if (relations.Count > 0)
2899
                                    rows.First()["SubType"] = "OtherSystem";
2900
                            }
2901
                        }
2902
                    }
2903
                    catch (Exception ex)
2904
                    {
2905

    
2906
                        MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2907
                    }
2908
                }
2909

    
2910
                foreach (DataRow row in TopologySet.Rows)
2911
                    if (row["SubType"] == null || string.IsNullOrEmpty(row["SubType"].ToString()))
2912
                        row["SubType"] = "Normal";
2913
            }
2914
            catch (Exception ex)
2915
            {
2916
                Log.Write(ex.Message + "\r\n" + ex.StackTrace);
2917
                MessageBox.Show(ex.Message, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Information);
2918
            }
2919
        }
2920

    
2921
        private bool IsBypass(PSNItem PSNItem)
2922
        {
2923
            bool bResult = false;
2924

    
2925
            if (PSNItem.GetPSNType() == "B2B")
2926
            {
2927
                Group firstGroup = PSNItem.Groups.First();
2928
                Group lastGroup = PSNItem.Groups.Last();
2929
                Item firstItem = firstGroup.Items.First();
2930
                Item lastItem = lastGroup.Items.Last();
2931

    
2932
                Item connectedFirstItem = GetConnectedItemByPSN(firstItem);
2933
                Item connectedLastItem = GetConnectedItemByPSN(lastItem);
2934

    
2935
                if (connectedFirstItem.LineNumber != null && connectedLastItem.LineNumber != null &&
2936
                    !string.IsNullOrEmpty(connectedFirstItem.LineNumber.Name) && !string.IsNullOrEmpty(connectedLastItem.LineNumber.Name) &&
2937
                    connectedFirstItem.LineNumber.Name == connectedLastItem.LineNumber.Name)
2938
                    bResult = true;
2939
                else if (connectedFirstItem.PSNItem == connectedLastItem.PSNItem)
2940
                    bResult = true;
2941
            }
2942

    
2943
            Item GetConnectedItemByPSN(Item item)
2944
            {
2945
                Item result = null;
2946

    
2947
                Relation relation = item.Relations.Find(x => x.Item != null && x.Item.PSNItem != item.PSNItem);
2948
                if (relation != null)
2949
                    result = relation.Item;
2950

    
2951

    
2952
                return result;
2953
            }
2954

    
2955
            return bResult;
2956
        }
2957

    
2958
        private void DeleteVentDrain()
2959
        {
2960
            DataRow[] ventdrainRows = PipeSystemNetwork.Select(" IncludingVirtualData = 'Vent_Drain'");
2961

    
2962
            foreach (DataRow dataRow in ventdrainRows)
2963
            {
2964
                dataRow.Delete();
2965
            }
2966
        }
2967

    
2968
        private void UpdateAccuracy()
2969
        {
2970
            //DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'"); 
2971
            DataRow[] statusRows = PipeSystemNetwork.Select(" Type = 'Error' OR IsValid = 'Error'");
2972
            List<double> lstAcc = null;
2973
            string Status = string.Empty;
2974

    
2975
            foreach (DataRow dataRow in statusRows)
2976
            {
2977
                lstAcc = new List<double>();
2978
                Status = dataRow.Field<string>("Status");
2979
                if (!string.IsNullOrEmpty(Status))
2980
                {
2981
                    string[] arrStatus = Status.Split(',');
2982
                    foreach (string arrstr in arrStatus)
2983
                    {
2984
                        if (arrstr.Contains(Rule1)) //Missing LineNumber_1
2985
                            lstAcc.Add(0.75);
2986

    
2987
                        if (arrstr.Contains(Rule2)) //Missing LineNumber_2
2988
                            lstAcc.Add(0.7);
2989

    
2990
                        if (arrstr.Contains(Rule3)) // OPC Disconnected
2991
                            lstAcc.Add(0.5);
2992

    
2993
                        if (arrstr.Contains(Rule4)) //Missing ItemTag or Description
2994
                            lstAcc.Add(0.65);
2995

    
2996
                        if (arrstr.Contains(Rule5)) //Line Disconnected
2997
                            lstAcc.Add(0.6);
2998
                    }
2999
                }
3000

    
3001
                string PSNAccuracy = dataRow["PSNAccuracy"].ToString();
3002
                if (PSNAccuracy == "100")
3003
                    PSNAccuracy = "1";
3004

    
3005
                PSNAccuracy = Convert.ToString(Convert.ToDecimal(AccuracyCalculation(lstAcc, Convert.ToDouble(PSNAccuracy))));
3006
                //if (PSNAccuracy != "100")
3007
                //{
3008
                //    //dataRow["IncludingVirtualData"] = "No";
3009
                dataRow["PSNAccuracy"] = PSNAccuracy;
3010
                //}
3011
            }
3012
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID" });
3013
            foreach (DataRow dr in dt.Rows)
3014
            {
3015
                string oid = dr.Field<string>("OID");
3016
                DataRow[] select = PipeSystemNetwork.Select(string.Format("OID = '{0}'", oid));
3017
                double totalDdr = 0;
3018
                foreach (DataRow ddr in select)
3019
                {
3020
                    double acc = Convert.ToDouble(ddr.Field<string>("PSNAccuracy"));
3021
                    if (acc == 100) acc = 1;
3022
                    if (totalDdr == 0) totalDdr = acc;
3023
                    else totalDdr *= acc;
3024
                }
3025

    
3026
                totalDdr *= 100;
3027

    
3028
                if (totalDdr != 100)
3029
                {
3030
                    foreach (DataRow ddr in select)
3031
                    {
3032
                        ddr["IncludingVirtualData"] = "Yes";
3033
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
3034
                        ddr["IsValid"] = "Error";
3035
                    }
3036
                }
3037
                else
3038
                {
3039
                    foreach (DataRow ddr in select)
3040
                    {
3041
                        ddr["IncludingVirtualData"] = "No";
3042
                        ddr["PSNAccuracy"] = String.Format("{0:0.00}", Math.Round(totalDdr, 2));
3043
                    }
3044
                }
3045
            }
3046

    
3047
        }
3048

    
3049
        private void UpdateKeywordForPSN()
3050
        {
3051
            #region Keyword Info
3052
            KeywordInfo KeywordInfos = new KeywordInfo();
3053
            DataTable dtKeyword = DB.SelectKeywordsSetting();
3054
            foreach (DataRow row in dtKeyword.Rows)
3055
            {
3056
                int index = Convert.ToInt32(row["INDEX"]);
3057
                string name = row["NAME"].ToString();
3058
                string keyword = row["KEYWORD"].ToString();
3059

    
3060
                //KeywordInfo keywordInfo = new KeywordInfo();   
3061
                KeywordInfos.KeywordItems.Add(new KeywordItem()
3062
                {
3063
                    Index = index,
3064
                    Name = name,
3065
                    Keyword = keyword
3066
                });
3067
            }
3068
            #endregion
3069

    
3070
            DataRow[] endofHeaderRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", "ENDOFHEADER"));
3071
            foreach (DataRow dataRow in endofHeaderRows)
3072
            {
3073
                PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3074

    
3075
                if (dataRow.Field<string>("From_Data") == "ENDOFHEADER")
3076
                {
3077
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3078
                    DataRow dr = pathItemRows.First();
3079
                    dr["CLASS"] = PSNItem.Groups.First().Items.First().ID2DBName;
3080
                    dr["TYPE"] = "End";
3081
                    dr["ITEMTAG"] = "ENDOFHEADER";
3082
                    dr["DESCRIPTION"] = "ENDOFHEADER";
3083
                }
3084

    
3085
                if (dataRow.Field<string>("To_Data") == "ENDOFHEADER")
3086
                {
3087
                    DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3088
                    DataRow dr = pathItemRows.Last();
3089
                    dr["CLASS"] = PSNItem.Groups.Last().Items.Last().ID2DBName;
3090
                    dr["TYPE"] = "End";
3091
                    dr["ITEMTAG"] = "ENDOFHEADER";
3092
                    dr["DESCRIPTION"] = "ENDOFHEADER";
3093
                }
3094
            }
3095

    
3096
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3097
            {
3098
                DataRow[] keywordRows = PipeSystemNetwork.Select(string.Format(" From_Data = '{0}' OR To_Data = '{0}'", keyitem.Keyword));
3099
                foreach (DataRow dataRow in keywordRows)
3100
                {
3101
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3102

    
3103
                    if (dataRow.Field<string>("From_Data") == keyitem.Keyword)
3104
                    {
3105
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3106

    
3107
                        //
3108
                        //if(.)
3109
                        if (PSNItem.Groups.First().Items.First().Name.Equals(keyitem.Name))
3110
                        {
3111
                            DataRow dr = pathItemRows.First();
3112
                            //dr["CLASS"] = ""; //Type
3113
                            dr["TYPE"] = "End";
3114
                            dr["ITEMTAG"] = keyitem.Keyword;
3115
                            dr["DESCRIPTION"] = keyitem.Keyword;
3116
                        }
3117

    
3118
                    }
3119

    
3120
                    if (dataRow.Field<string>("To_Data") == keyitem.Keyword)
3121
                    {
3122
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3123

    
3124
                        if (PSNItem.Groups.Last().Items.Last().Name.Equals(keyitem.Name))
3125
                        {
3126
                            DataRow dr = pathItemRows.Last();
3127
                            //dr["CLASS"] = ""; //Type
3128
                            dr["TYPE"] = "End";
3129
                            dr["ITEMTAG"] = keyitem.Keyword;
3130
                            dr["DESCRIPTION"] = keyitem.Keyword;
3131
                            //dr.Field<string>("Type")
3132
                        }
3133

    
3134
                    }
3135
                }
3136
            }
3137
        }
3138

    
3139
        private void UpdateErrorForPSN()
3140
        {
3141
            DataRow[] errorRows = PipeSystemNetwork.Select(string.Format(" Type = '{0}'", ErrorType.Error));
3142
            foreach (DataRow dataRow in errorRows)
3143
            {
3144
                try
3145
                {
3146
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3147
                   
3148
                    bool change = false;
3149
                    bool bCheck = false;
3150
                    if (!PSNItem.EnableType(PSNItem.StartType))
3151
                    {
3152
                        change = true;
3153
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3154
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3155

    
3156
                        Item item = PSNItem.Groups.First().Items.First();
3157
                        try
3158
                        {
3159
                            string FROM_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
3160

    
3161
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3162
                            {
3163
                                loopRow["FROM_DATA"] = FROM_DATA;
3164
                                if (item.ItemType == ItemType.Line)
3165
                                {
3166
                                    if (loopRow.Field<string>("OrderNumber") == "0")
3167
                                    {
3168
                                        string status = loopRow.Field<string>("Status");
3169
                                        //string isvali
3170
                                        if (string.IsNullOrEmpty(status))
3171
                                            status = "Line Disconnected";
3172
                                        else if (!status.Contains("Line Disconnected"))
3173
                                            status += ", Line Disconnected";
3174
                                        loopRow["Status"] = status;
3175
                                        if (!string.IsNullOrEmpty(status))
3176
                                            loopRow["IsValid"] = "Error";
3177
                                    }
3178
                                }
3179
                            }
3180

    
3181
                            tieInPointIndex++;
3182

    
3183
                            if (item.ItemType == ItemType.Line)
3184
                            {
3185
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);                                
3186
                            }
3187
                            else
3188
                            {
3189
                                PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).First()), insertIndex);
3190
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.First(), FROM_DATA), insertIndex);
3191

    
3192
                                bCheck = true;
3193
                            }
3194

    
3195
                            PSNItem.StartType = PSNType.Equipment;
3196
                        }
3197
                        catch (Exception ex)
3198
                        {
3199
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3200
                            return;
3201
                        }
3202
                    }
3203

    
3204
                    if (!PSNItem.EnableType(PSNItem.EndType))
3205
                    {                        
3206
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", dataRow["OID"]));
3207
                        //int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First()) + pathItemRows.Count() - 1;
3208
                        DataRow dr = pathItemRows.Last();
3209
                        if (change)
3210
                        {
3211
                            if(bCheck)
3212
                                dr = pathItemRows[pathItemRows.Count() - 3];
3213
                            else
3214
                            {
3215
                                dr = pathItemRows[pathItemRows.Count() - 2];
3216
                            }
3217
                        }
3218

    
3219
                        change = true;
3220
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3221

    
3222
                        Item item = PSNItem.Groups.Last().Items.Last();
3223
                        try
3224
                        {
3225
                            string TO_DATA = string.Format("TIEINPOINT_{0:D5}V", tieInPointIndex);
3226

    
3227
                            
3228
                            foreach (DataRow loopRow in PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())))
3229
                            {
3230
                                loopRow["TO_DATA"] = TO_DATA;
3231
                                if (item.ItemType == ItemType.Line)
3232
                                {
3233
                                    if (loopRow.Field<string>("OrderNumber") == Convert.ToString(PipeSystemNetwork.Select(string.Format("OID = '{0}'", PSNItem.PSN_OID())).Count() - 1))
3234
                                    {
3235
                                        string status = loopRow.Field<string>("Status");
3236
                                        if (string.IsNullOrEmpty(status))
3237
                                            status = "Line Disconnected";
3238
                                        else if (!status.Contains("Line Disconnected"))
3239
                                            status += ", Line Disconnected";
3240
                                        loopRow["Status"] = status;
3241
                                        if (!string.IsNullOrEmpty(status))
3242
                                            loopRow["IsValid"] = "Error";
3243
                                    }
3244
                                }
3245

    
3246
                            }                            
3247

    
3248
                            tieInPointIndex++;
3249

    
3250
                            if (item.ItemType == ItemType.Line)
3251
                            {
3252
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3253
                            }
3254
                            else
3255
                            {
3256
                                PathItems.Rows.InsertAt(createTerminatorRow(pathItemRows.Last(), TO_DATA), insertIndex);
3257
                                if(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Count() > 0)
3258
                                    PathItems.Rows.InsertAt(createLineRow(PathItems.Select(string.Format("PipeLine_OID = '{0}' AND ItemName = 'PipeRun' AND PipeSystemNetwork_OID = '{1}'", item.PSNPipeLineID, dataRow["OID"])).Last()), insertIndex);
3259
                               
3260
                            }
3261

    
3262
                            PSNItem.EndType = PSNType.Equipment;
3263
                        }
3264
                        catch (Exception ex)
3265
                        {
3266
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + item.Document.DrawingName + "\r\nUID : " + item.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3267
                            return;
3268
                        }
3269
                    }
3270

    
3271
                    dataRow["Type"] = PSNItem.GetPSNType();
3272
                    if (change)
3273
                    {
3274
                        int rowIndex = 0;
3275
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3276
                        {
3277
                            DataRow row = PathItems.Rows[i];
3278
                            if (row["PipeSystemNetwork_OID"].ToString() != dataRow["OID"].ToString())
3279
                                continue;
3280
                            string sequenceData = row["SequenceData_OID"].ToString();
3281
                            string[] split = sequenceData.Split(new char[] { '_' });
3282

    
3283
                            StringBuilder sb = new StringBuilder();
3284
                            for (int j = 0; j < split.Length - 1; j++)
3285
                                sb.Append(split[j] + "_");
3286
                            sb.Append(rowIndex++);
3287
                            row["SequenceData_OID"] = sb.ToString();
3288

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

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

    
3294
                            if (seqItemRows == null)
3295
                            {
3296
                                DataRow newRow = SequenceData.NewRow();
3297
                                newRow["OID"] = sb.ToString();
3298
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3299
                                newRow["PathItem_OID"] = row["OID"];
3300
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3301
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3302
                            }
3303
                            else
3304
                            {
3305
                                seqItemRows["OID"] = sb.ToString();
3306
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3307
                                seqItemRows["PathItem_OID"] = row["OID"];
3308
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3309
                            }
3310
                        }
3311
                    }
3312

    
3313
                    DataRow createTerminatorRow(DataRow itemRow, string DATA)
3314
                    {
3315
                        DataRow newRow = PathItems.NewRow();
3316
                        newRow["OID"] = Guid.NewGuid().ToString();
3317
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3318
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3319
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3320
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3321
                        newRow["ITEMNAME"] = "PipingComp"; //newRow["ITEMNAME"] = "End of line terminator";
3322
                        newRow["ITEMTAG"] = DATA; //itemRow["ITEMTAG"];
3323
                        newRow["DESCRIPTION"] = DATA;
3324
                        newRow["Class"] = "End of line terminator";
3325
                        newRow["SubClass"] = "End of line terminator";
3326
                        newRow["TYPE"] = "End";
3327
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3328
                        newRow["NPD"] = itemRow["NPD"];
3329
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3330
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3331
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3332
                        newRow["EGTConnectedPoint"] = "0";
3333
                        return newRow;
3334
                    }
3335

    
3336
                    DataRow createLineRow(DataRow itemRow)
3337
                    {
3338
                        DataRow newRow = PathItems.NewRow();
3339
                        newRow["OID"] = Guid.NewGuid().ToString();
3340
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3341
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3342
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3343
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3344
                        newRow["ITEMNAME"] = itemRow["ITEMNAME"];
3345
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3346
                        newRow["Class"] = itemRow["Class"];
3347
                        newRow["SubClass"] = itemRow["SubClass"];
3348
                        newRow["TYPE"] = itemRow["TYPE"];
3349
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3350
                        newRow["NPD"] = itemRow["NPD"];
3351
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3352
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3353
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3354
                        newRow["EGTConnectedPoint"] = "0";
3355
                        return newRow;
3356
                    }
3357
                }
3358
                catch (Exception ex)
3359
                {
3360

    
3361
                }
3362
            }
3363
        }
3364

    
3365
        private void InsertTeePSN()
3366
        {
3367
            DataTable dt = PipeSystemNetwork.DefaultView.ToTable(true, new string[] { "OID", "Type" });
3368
            DataRow[] branchRows = dt.Select("Type Like '%B%'");
3369
            bool change = false;
3370
            foreach (DataRow dataRow in branchRows)
3371
            {
3372
                try
3373
                {
3374
                    PSNItem PSNItem = PSNItems.Find(x => x.PSN_OID() == dataRow["OID"].ToString());
3375
                    change = false;
3376

    
3377
                    if (PSNItem.StartType == PSNType.Branch)
3378
                    {
3379
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3380
                        int insertIndex = PathItems.Rows.IndexOf(pathItemRows.First());
3381
                        Item Teeitem = PSNItem.Groups.First().Items.First();
3382
                        try
3383
                        {
3384
                            if (Teeitem.ItemType == ItemType.Line)
3385
                            {
3386
                                if (pathItemRows.First().Field<string>("SubClass") != "Tee")
3387
                                {
3388
                                    PathItems.Rows.InsertAt(createTeeRow(pathItemRows.First()), insertIndex);
3389
                                    pathItemRows.First().SetField("BranchTopologySet_OID", string.Empty);
3390
                                    pathItemRows.First().SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3391
                                    change = true;
3392
                                }
3393

    
3394
                            }
3395
                        }
3396
                        catch (Exception ex)
3397
                        {
3398
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3399
                            return;
3400
                        }
3401
                    }
3402

    
3403
                    if (PSNItem.EndType == PSNType.Branch)
3404
                    {
3405
                        //change = true;
3406
                        DataRow[] pathItemRows = PathItems.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3407

    
3408
                        Item Teeitem = PSNItem.Groups.Last().Items.Last();
3409

    
3410
                        DataRow dr = pathItemRows.Last();
3411
                        if (change)
3412
                            dr = pathItemRows[pathItemRows.Count() - 2];
3413

    
3414
                        int insertIndex = PathItems.Rows.IndexOf(dr) + 1;
3415

    
3416
                        try
3417
                        {
3418
                            if (Teeitem.ItemType == ItemType.Line)
3419
                            {
3420
                                if (dr.Field<string>("SubClass") != "Tee")
3421
                                {
3422
                                    PathItems.Rows.InsertAt(createTeeRow(dr), insertIndex);
3423
                                    change = true;
3424
                                    dr.SetField("BranchTopologySet_OID", string.Empty);
3425
                                    dr.SetField("ViewPipeSystemNetwork_OID", dataRow["OID"].ToString());
3426
                                }
3427

    
3428
                            }
3429
                        }
3430
                        catch (Exception ex)
3431
                        {
3432
                            MessageBox.Show("Please check the item.\r\nDrawingName : " + Teeitem.Document.DrawingName + "\r\nUID : " + Teeitem.UID, "ID2 " + id2Info.ProgramName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
3433
                            return;
3434
                        }
3435
                    }
3436

    
3437
                    if (change)
3438
                    {
3439
                        //DataRow[] pathItemRows = pathItemsDT.Select(string.Format("PipeSystemNetwork_OID = '{0}'", PSNItem.PSN_OID()));
3440
                        int rowIndex = 0;
3441
                        for (int i = 0; i < PathItems.Rows.Count; i++)
3442
                        {
3443
                            DataRow row = PathItems.Rows[i];
3444
                            if (row["PipeSystemNetwork_OID"].ToString() != PSNItem.PSN_OID())
3445
                                continue;
3446
                            string sequenceData = row["SequenceData_OID"].ToString();
3447
                            string[] split = sequenceData.Split(new char[] { '_' });
3448

    
3449
                            StringBuilder sb = new StringBuilder();
3450
                            for (int j = 0; j < split.Length - 1; j++)
3451
                                sb.Append(split[j] + "_");
3452
                            sb.Append(rowIndex++);
3453
                            row["SequenceData_OID"] = sb.ToString();
3454

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

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

    
3460
                            if (seqItemRows == null)
3461
                            {
3462
                                DataRow newRow = SequenceData.NewRow();
3463
                                newRow["OID"] = sb.ToString();
3464
                                newRow["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3465
                                newRow["PathItem_OID"] = row["OID"];
3466
                                newRow["TopologySet_OID_Key"] = row["TopologySet_OID"];
3467
                                SequenceData.Rows.InsertAt(newRow, Convert.ToInt32(splitseq[splitseq.Length - 1]));
3468
                            }
3469
                            else
3470
                            {
3471
                                seqItemRows["OID"] = sb.ToString();
3472
                                seqItemRows["SERIALNUMBER"] = splitseq[splitseq.Length - 1];
3473
                                seqItemRows["PathItem_OID"] = row["OID"];
3474
                                seqItemRows["TopologySet_OID_Key"] = row["TopologySet_OID"];
3475
                            }
3476
                        }
3477
                    }
3478

    
3479
                    DataRow createTeeRow(DataRow itemRow)
3480
                    {
3481
                        DataRow newRow = PathItems.NewRow();
3482
                        newRow["OID"] = Guid.NewGuid().ToString();
3483
                        newRow["SequenceData_OID"] = itemRow["SequenceData_OID"];
3484
                        newRow["TopologySet_OID"] = itemRow["TopologySet_OID"];
3485
                        newRow["BranchTopologySet_OID"] = itemRow["BranchTopologySet_OID"];
3486
                        newRow["PipeLine_OID"] = itemRow["PipeLine_OID"];
3487
                        newRow["ITEMNAME"] = "Branch"; //newRow["ITEMNAME"] = "End of line terminator";
3488
                        newRow["ITEMTAG"] = itemRow["ITEMTAG"];
3489
                        newRow["DESCRIPTION"] = "";
3490
                        newRow["Class"] = "Branch";
3491
                        newRow["SubClass"] = "Tee";
3492
                        newRow["TYPE"] = itemRow["TYPE"];
3493
                        newRow["PIDNAME"] = itemRow["PIDNAME"];
3494
                        newRow["NPD"] = itemRow["NPD"];
3495
                        newRow["PipeSystemNetwork_OID"] = itemRow["PipeSystemNetwork_OID"];
3496
                        newRow["ViewPipeSystemNetwork_OID"] = itemRow["ViewPipeSystemNetwork_OID"];
3497
                        newRow["PipeRun_OID"] = itemRow["PipeRun_OID"];
3498
                      
3499
                        newRow["EGTConnectedPoint"] = 0;
3500
                        return newRow;
3501
                    }
3502
                }
3503
                catch (Exception ex)
3504
                {
3505

    
3506
                }
3507
            }
3508
        }
3509
    }
3510

    
3511
    public class PSNItem
3512
    {
3513
        public PSNItem(int count, int Revision)
3514
        {
3515
            Groups = new List<Group>();
3516
            Topologies = new List<Topology>();
3517

    
3518
            Index = count + 1;
3519
            this.Revision = Revision;
3520
        }
3521

    
3522
        private int Revision;
3523
        public string UID { get; set; }
3524
        public List<Group> Groups { get; set; }
3525
        public List<Topology> Topologies { get; set; }
3526
        public PSNType StartType { get; set; }
3527
        public PSNType EndType { get; set; }
3528
        public int Index { get; set; }
3529
        public string IsValid { get; set; }
3530
        public bool IsKeyword { get; set; }
3531
        public string Status { get; set; }
3532
        public string IncludingVirtualData { get; set; }
3533
        public string PSNAccuracy { get; set; }
3534
        public KeywordInfo KeywordInfos = new KeywordInfo();
3535
        public DataTable Nozzle = new DataTable();
3536

    
3537
        public string PSN_OID()
3538
        {
3539
            return string.Format("V{0}-PSN-{1}", string.Format("{0:D4}", Revision), string.Format("{0:D5}", Index));
3540
        }
3541

    
3542
        public string GetPSNType()
3543
        {
3544
            string result = string.Empty;
3545

    
3546
            if (EnableType(StartType) && EnableType(EndType))
3547
            {
3548
                if (StartType == PSNType.Equipment && EndType == PSNType.Equipment)
3549
                    result = "E2E";
3550
                else if (StartType == PSNType.Branch && EndType == PSNType.Branch)
3551
                    result = "B2B";
3552
                else if (StartType == PSNType.Header && EndType == PSNType.Header)
3553
                    result = "HD2";
3554

    
3555
                else if (StartType == PSNType.Equipment && EndType == PSNType.Branch)
3556
                    result = "E2B";
3557
                else if (StartType == PSNType.Branch && EndType == PSNType.Equipment)
3558
                    result = "B2E";
3559

    
3560
                else if (StartType == PSNType.Header && EndType == PSNType.Branch)
3561
                    result = "HDB";
3562
                else if (StartType == PSNType.Branch && EndType == PSNType.Header)
3563
                    result = "HDB";
3564

    
3565
                else if (StartType == PSNType.Header && EndType == PSNType.Equipment)
3566
                    result = "HDE";
3567
                else if (StartType == PSNType.Equipment && EndType == PSNType.Header)
3568
                    result = "HDE";
3569
                else
3570
                    result = "Error";
3571
            }
3572
            else
3573
                result = "Error";
3574

    
3575
            return result;
3576

    
3577

    
3578
        }
3579

    
3580
        public bool EnableType(PSNType type)
3581
        {
3582
            bool result = false;
3583

    
3584
            if (type == PSNType.Branch ||
3585
                type == PSNType.Equipment ||
3586
                type == PSNType.Header)
3587
            {
3588
                result = true;
3589
            }
3590

    
3591
            return result;
3592
        }
3593

    
3594
        public bool IsBypass { get; set; }
3595

    
3596
        public string GetFromData(ref string Type, ref Item item)
3597
        {
3598
            Status = string.Empty;
3599
            string result = string.Empty;
3600
            if (IsKeyword)
3601
                IsKeyword = false;
3602
            try
3603
            {
3604
                item = Groups.First().Items.First();
3605

    
3606
                if (StartType == PSNType.Header)
3607
                    result = "ENDOFHEADER";
3608
                else if (StartType == PSNType.Branch)
3609
                {
3610
                    if (item.Relations.First().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.First().Item.LineNumber.Name))
3611
                    {
3612
                        result = item.Relations.First().Item.LineNumber.Name;
3613
                        if (item.Relations.First().Item.LineNumber.MissingLineNumber2)
3614
                        {
3615
                            Status += ", Missing LineNumber_2";
3616
                            IsValid = "Error";
3617
                        }
3618
                        if (item.Relations.First().Item.LineNumber.MissingLineNumber1)
3619
                        {
3620
                            Status += ", Missing LineNumber_1";
3621
                            IsValid = "Error";
3622
                        }
3623
                    }
3624
                    else
3625
                    {
3626
                        IsValid = "Error";
3627
                        result = "Empty LineNumber";
3628
                    }
3629
                }
3630
                else if (StartType == PSNType.Equipment)
3631
                {
3632
                    if (Groups.First().Items.First().Equipment != null)
3633
                        result = Groups.First().Items.First().Equipment.ItemTag;
3634
                    DataRow drNozzle = Nozzle.Select(string.Format("OID = '{0}'", Groups.First().Items.First().UID)).FirstOrDefault();
3635

    
3636
                    if (drNozzle != null)
3637
                        result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3638
                }
3639
                else
3640
                {
3641
                    
3642
                    item = Groups.First().Items.First();
3643
                    if (item.ItemType == ItemType.Symbol)
3644
                    {
3645
                        string keyword = string.Empty;
3646
                        keyword = GetFromKeywordData(ref Type, item);
3647

    
3648
                        if (string.IsNullOrEmpty(keyword))
3649
                        {
3650
                            if (item.ID2DBType.Contains("OPC's"))
3651
                                Status += ", OPC Disconnected";
3652
                            else
3653
                                Status += ", Missing ItemTag or Description";
3654

    
3655
                            result = item.ID2DBName;
3656
                            IsValid = "Error";
3657
                        }
3658
                        else
3659
                        {
3660
                            result = keyword;
3661
                            IsKeyword = true;
3662
                        }
3663

    
3664
                    }
3665
                    else if (item.ItemType == ItemType.Line)
3666
                    {
3667
                        if (item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name))
3668
                        {
3669
                            result = item.LineNumber.Name;
3670
                            if (item.LineNumber.MissingLineNumber2)
3671
                            {
3672
                                Status += ", Missing LineNumber_2";
3673
                                IsValid = "Error";
3674
                            }
3675
                            if (item.LineNumber.MissingLineNumber1)
3676
                            {
3677
                                Status += ", Missing LineNumber_1";
3678
                                IsValid = "Error";
3679
                            }
3680
                        }
3681
                        else
3682
                        {
3683
                            IsValid = "Error";
3684
                            result = "Empty LineNumber";
3685
                        }
3686
                    }
3687
                    else
3688
                        result = "Unknown";
3689
                }
3690
            }
3691
            catch (Exception ex)
3692
            {
3693

    
3694
            }
3695

    
3696
            return result;
3697
        }
3698

    
3699
        public string GetFromKeywordData(ref string Type, Item item)
3700
        {
3701
            string result = string.Empty;
3702

    
3703
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3704
            {
3705
                if (keyitem.Name.Equals(item.Name))
3706
                {
3707
                    result = keyitem.Keyword;
3708
                    Type = item.ID2DBType;
3709
                    break;
3710
                }
3711
            }
3712

    
3713
            return result;
3714
        }
3715

    
3716
        public string GetToKeywordData(ref string Type, Item item)
3717
        {
3718
            string result = string.Empty;
3719

    
3720
            foreach (KeywordItem keyitem in KeywordInfos.KeywordItems)
3721
            {
3722
                if (keyitem.Name.Equals(item.Name))
3723
                {
3724
                    result = keyitem.Keyword;
3725
                    Type = item.ID2DBType;
3726
                    break;
3727
                }
3728
            }
3729
            return result;
3730
        }
3731

    
3732
        public string GetToData(ref string ToType, ref Item item)
3733
        {
3734
            string result = string.Empty;
3735
            Status = string.Empty;
3736

    
3737
            if (IsKeyword)
3738
                IsKeyword = false;
3739

    
3740
            item = Groups.Last().Items.Last();
3741

    
3742
            if (EndType == PSNType.Header)
3743
                result = "ENDOFHEADER";
3744
            else if (EndType == PSNType.Branch)
3745
            {
3746
                if (item.Relations.Last().Item.LineNumber != null && !string.IsNullOrEmpty(item.Relations.Last().Item.LineNumber.Name))
3747
                {
3748
                    result = item.Relations.Last().Item.LineNumber.Name;
3749
                    if (item.Relations.Last().Item.LineNumber.MissingLineNumber2)
3750
                    {
3751
                        Status += ", Missing LineNumber_2";
3752
                        IsValid = "Error";
3753
                    }
3754
                    if (item.Relations.Last().Item.LineNumber.MissingLineNumber1)
3755
                    {
3756
                        Status += ", Missing LineNumber_1";
3757
                        IsValid = "Error";
3758
                    }
3759
                }
3760
                else
3761
                {
3762
                    IsValid = "Error";
3763
                    result = "Empty LineNumber";
3764
                }                
3765
            }
3766
            else if (EndType == PSNType.Equipment)
3767
            {
3768
                if (Groups.Last().Items.Last().Equipment != null)
3769
                    result = Groups.Last().Items.Last().Equipment.ItemTag;
3770

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

    
3773
                if (drNozzle != null)
3774
                    result += " [" + drNozzle.Field<string>("ITEMTAG") + "]";
3775
            }
3776
            else
3777
            {
3778
                
3779
                item = Groups.Last().Items.Last();
3780
                if (item.ItemType == ItemType.Symbol)
3781
                {
3782
                    string keyword = string.Empty;
3783
                    keyword = GetToKeywordData(ref ToType, item);
3784

    
3785
                    if (string.IsNullOrEmpty(keyword))
3786
                    {
3787
                        if (item.ID2DBType.Contains("OPC's"))
3788
                            Status += ", OPC Disconnected";
3789
                        else
3790
                            Status += ", Missing ItemTag or Description";
3791

    
3792
                        result = item.ID2DBName;
3793
                        IsValid = "Error";
3794
                    }
3795
                    else
3796
                    {
3797
                        result = keyword;
3798
                        IsKeyword = true;
3799
                    }
3800

    
3801
                }
3802
                else if (item.ItemType == ItemType.Line)
3803
                {
3804
                    if (item.LineNumber != null && !string.IsNullOrEmpty(item.LineNumber.Name))
3805
                    {
3806
                        result = item.LineNumber.Name;
3807
                        if (item.LineNumber.MissingLineNumber2)
3808
                        {
3809
                            Status += ", Missing LineNumber_2";
3810
                            IsValid = "Error";
3811
                        }
3812
                        if (item.LineNumber.MissingLineNumber1)
3813
                        {
3814
                            Status += ", Missing LineNumber_1";
3815
                            IsValid = "Error";
3816
                        }
3817
                    }
3818
                    else
3819
                    {
3820
                        IsValid = "Error";
3821
                        result = "Empty LineNumber";
3822
                    }
3823
                }
3824
                else
3825
                    result = "Unknown";
3826
            }
3827
            return result;
3828
        }
3829

    
3830
        public string GetPBSData()
3831
        {
3832
            string result = string.Empty;
3833
            List<string> PBSList = new List<string>();
3834
            if (Settings.Default.PBSSetting.Equals("Line Number"))
3835
            {
3836
                string attrValue = Settings.Default.PBSSettingValue;
3837

    
3838
                foreach (Group group in Groups)
3839
                {
3840
                    List<LineNumber> lineNumbers = group.Items.Select(x => x.LineNumber).Distinct().ToList();
3841
                    foreach (LineNumber lineNumber in lineNumbers)
3842
                    {
3843
                        Attribute attribute = lineNumber.Attributes.Find(x => x.Name == attrValue && !string.IsNullOrEmpty(x.Value));
3844
                        if (attribute != null)
3845
                        {
3846
                            string value = attribute.Value;
3847
                            if (!PBSList.Contains(value))
3848
                                PBSList.Add(value);
3849
                        }
3850
                    }
3851
                }
3852
            }
3853
            else if (Settings.Default.PBSSetting.Equals("Item Attribute"))
3854
            {
3855
                string attrValue = Settings.Default.PBSSettingValue;
3856

    
3857
                foreach (Group group in Groups)
3858
                {
3859
                    List<Item> items = group.Items.FindAll(x => x.Attributes.Find(y => y.Name == attrValue && !string.IsNullOrEmpty(y.Value)) != null);
3860
                    foreach (Item item in items)
3861
                    {
3862
                        string value = item.Attributes.Find(x => x.Name == attrValue).Value;
3863
                        if (!PBSList.Contains(value))
3864
                            PBSList.Add(value);
3865
                    }
3866
                }
3867
            }
3868
            else if (Settings.Default.PBSSetting.Equals("Drawing No"))
3869
            {
3870
                string attrValue = Settings.Default.PBSSettingValue;
3871

    
3872
                foreach (Group group in Groups)
3873
                {
3874
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3875
                    foreach (Document document in documents)
3876
                    {
3877
                        string name = document.DrawingName;
3878

    
3879
                        int startIndex = Settings.Default.PBSSettingStartValue;
3880
                        int endIndex = Settings.Default.PBSSettingEndValue;
3881

    
3882
                        string subStr = name.Substring(startIndex - 1, endIndex - startIndex + 1);
3883
                        if (!PBSList.Contains(subStr))
3884
                            PBSList.Add(subStr);
3885
                    }
3886
                }
3887
            }
3888
            else if (Settings.Default.PBSSetting.Equals("Unit Area"))
3889
            {
3890
                foreach (Group group in Groups)
3891
                {
3892
                    List<Document> documents = group.Items.Select(x => x.Document).Distinct().ToList();
3893
                    foreach (Document document in documents)
3894
                    {
3895
                        List<TextInfo> textInfos = document.TextInfos.FindAll(x => x.Area == "Unit");
3896
                        foreach (TextInfo textInfo in textInfos)
3897
                        {
3898
                            if (!PBSList.Contains(textInfo.Value))
3899
                                PBSList.Add(textInfo.Value);
3900
                        }
3901
                    }
3902
                }
3903
            }
3904

    
3905
            foreach (var item in PBSList)
3906
            {
3907
                if (string.IsNullOrEmpty(result))
3908
                    result = item;
3909
                else
3910
                    result += ", " + item;
3911
            }
3912
            return result;
3913
        }
3914
    }
3915
}
클립보드 이미지 추가 (최대 크기: 500 MB)