Imports C1.Win.C1Ribbon
Imports Microsoft.VisualBasic

Public Class MdiMain

    Dim T As String = "메인화면"

    Enum E_MenuIdx
        NONE = 0
        월별에너지사용량
        Form1 = 50
        Form2
        Form3
        Form4
        Form5
    End Enum

    Dim FileExt As String = "ECL2"

    '''현재열려있는폼의 이름을 변경한다.
    Public OpenedForm As E_MenuIdx = E_MenuIdx.NONE

    Private Sub MdiMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        If Not Prj.Opened Then
            If MsgBox(CLang.종료할래, MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, CLang.확인) = MsgBoxResult.Ok Then
                'Me.Close()
            Else
                e.Cancel = True
            End If
        Else
            Dim dlg As DialogResult = MsgBox(CLang.종료할래2, MsgBoxStyle.Information Or MsgBoxStyle.YesNoCancel, CLang.확인)
            If dlg = MsgBoxResult.Yes Then

                '//열려잇는 폼이 있다면 저장하도록한다.
                For Each ChildForm As CForm In Me.MdiChildren
                    If ChildForm.HasChanged Then ChildForm.AcceptChanged()
                Next

                '//파일을 저장한다.
                Func_Save_OD(Prj.FileName)
            ElseIf dlg = DialogResult.Cancel Then '//사용자가 취소를 했다.
                e.Cancel = True
            End If
        End If


    End Sub

    Private Sub MdiMain_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        Select Case e.KeyCode
            Case Keys.F1
                If e.Control AndAlso e.Shift Then
                    If ribbonGroup4.Visible Then
                        ribbonGroup4.Visible = Not ribbonGroup4.Visible
                    Else
                        Dim f As New LoginForm1()
                        If f.ShowDialog() = Windows.Forms.DialogResult.OK Then
                            ribbonGroup4.Visible = Not ribbonGroup4.Visible
                        End If
                    End If

                Else
                    Read_PreFile(0)
                End If
            Case Keys.F2
                Read_PreFile(1)
            Case Keys.F3
                Read_PreFile(2)
            Case Keys.F4
                Read_PreFile(3)

            Case Keys.F5
                Show_Menu(1)
            Case Keys.F6
                Show_Menu(2)
            Case Keys.F7
                Show_Menu(3)
            Case Keys.F8
                Show_Menu(4)
            Case Keys.F9
                Show_Menu(5)

            Case Keys.F11
                If e.Control Then
                    ExportCSV()
                End If

            Case Keys.F12
                Dim tblname As String = InputBox("", "")
                If tblname = "" Then Return
                Dim f As New Frm_Debug(tblname) With {
                    .TopMost = True
                }
                f.Show()
        End Select
    End Sub

    Private Sub CreateAppMenu()

        '//각버튼의 이벤트를 할당한다.
        AddHandler abt_exit.Click, Sub()
                                       Me.Close()
                                   End Sub

        AddHandler abt_new.Click, Sub()
                                      Menu_New()
                                  End Sub

        AddHandler abt_open.Click, Sub()
                                       Menu_Open()
                                   End Sub

        AddHandler abt_save.Click, Sub()
                                       Menu_Save()
                                   End Sub

        AddHandler abt_saveas.Click, Sub()
                                         Menu_SaveAs()
                                     End Sub

    End Sub


    Private Sub pinButton_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim pin As RibbonToggleButton = CType(sender, RibbonToggleButton)
        If pin.Pressed Then
            MsgBox("cli")
            '/ pin.SmallImage = My.Resources.pinned
        Else
            MsgBox("ncli")
            ' pin.SmallImage = My.Resources.unpinned
        End If
    End Sub


    Private Sub MdiMain_Load(ByVal sender As System.Object, ByVal e As EventArgs) Handles MyBase.Load
        '//프로그램이 켜질떄

        ribbonGroup4.Visible = False
        Me.Text = "총량 에너지평가 프로그램"
        Me.mbt_save.Enabled = False    '//저장버튼비활성
        Me.mbt_save2.Enabled = mbt_save.Enabled

        Me.Show()
        My.Application.DoEvents() '//화면에 표시

        Try
            Refresh_StatusInfo()

            Read_SEtting() '//환경설정을 가져온다. Splah를 변경했따.
            bt5.Visible = False

            Dim Param As String = Command.ToString
            Param = Param.Replace(Chr(34), "")

            If Param.ToLower().LastIndexOf(".ecl2") <> -1 Then
                Program = EProgram.총량평가
                FileExt = "ECL2"
            ElseIf Param.ToLower().LastIndexOf(".ecl3") <> -1 Then
                Program = EProgram.친환경평가
                FileExt = "ECL3"
            Else
                Dim F As New Frm_Intro  '//로그인화면을 표시
                If F.ShowDialog <> Windows.Forms.DialogResult.OK Then End
                If F.RadioButton1.Checked Then  '//eco2는 로그인해야함
                    Program = EProgram.총량평가
                    FileExt = "ECL2"
                Else
                    bt5.Visible = True
                    Program = EProgram.친환경평가
                    FileExt = "ECL3"
                End If
            End If

            If Program = EProgram.총량평가 Then
                Me.Text = "건축물 에너지 소비 총량제"
            Else
                Me.Text = "에너지 절약형 친환경주택"
            End If


            Me.Text &= " Ver " & _
                My.Application.Info.Version.Minor & "." & _
                My.Application.Info.Version.Build & "." & _
                My.Application.Info.Version.Revision ' & "(Beta)"

            '//기존사용한 파일목록
            Read_FilHistory()

            Me.lb_program.Text = "[" + Program.ToString() + "]"

            '//Version 정보를 확인
            '//170514 other button - btvercheck
            Work_msg("")




            CreateAppMenu()

            '//파라미터확인
            If Param <> "" Then
                If System.IO.File.Exists(Param) Then  '//해당파일이 존재하면
                    Select Case Program
                        Case EProgram.친환경평가
                            Me.Func_Open_OD(Param)
                        Case EProgram.총량평가
                            Me.Func_Open_OD(Param)
                    End Select
                End If
            End If


        Catch ex As Exception
            Dim sb As New System.Text.StringBuilder
            Dim st As New StackTrace(True)
            sb.AppendLine("(Load) 프레임 수: " + st.FrameCount.ToString())
            sb.AppendLine("현  재 메서드: " + st.GetFrame(0).GetMethod().Name)
            sb.AppendLine("호출한 메서드: " + st.GetFrame(1).GetMethod().Name)
            sb.AppendLine("진  입 메서드: " + st.GetFrame(st.FrameCount - 1).GetMethod().Name)
            sb.AppendLine()

            sb.AppendLine("-- 호출 스택 --")
            For Each sf As StackFrame In st.GetFrames()
                sb.AppendLine(
                     "  파  일: " + sf.GetFileName() +
                     "      행: " + sf.GetFileLineNumber().ToString() +
                     "      열: " + sf.GetFileColumnNumber().ToString() +
                     "  오프셋: " + sf.GetILOffset().ToString() +
                     "  메서드: " + sf.GetMethod().Name)
            Next
            MsgBox(sb.ToString(), MsgBoxStyle.Critical, "File Open Error")
        End Try



    End Sub

    ''' <summary>
    ''' 하단 상태표시창의 정보를 갱신합니다.
    ''' </summary>
    Public Sub Refresh_StatusInfo()
        Try
            'If Prj.Admin Then
            '    Me.lb_usermode.Text = "[관리자]"
            'Else
            '    Me.lb_usermode.Text = "[일반]"
            'End If
            '//템플릿 정보파일
            If Prj.EditTime = "" Then
                Me.lbl_lastedit.Text = "[최종변경]"
            Else
                Me.lbl_lastedit.Text = "[" & Prj.EditTime.Trim & "]"
            End If
            If Prj.Name = "" Then
                Me.lbl_prjname.Text = "[이름]"
                Me.lbl_prjname.ToolTip = ""
            Else
                Me.lbl_prjname.Text = "[" & Prj.Name.Trim.Replace(Space(1), "") & "]"
                Me.lbl_prjname.ToolTip = Prj.Desc
            End If
            If Prj.SFType = "" Then
                Me.lbl_FileInfo.Text = "[버젼]"
            Else
                Me.lbl_FileInfo.Text = "[" & Prj.LGVersino.Trim & "]"
            End If

            'If Prj.Password = "" Then
            '    Me.lbl_password.Text = "[비보호]"
            'Else
            '    Me.lbl_password.Text = "[보호]"
            'End If

            'Me.lbl_user.Text = "[" & Prj.UserId & "]"
            Me.lbl_mac.Text = "[" & Prj.CUrMac & "]"
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
        End Try


    End Sub

    Public Sub Func_Open_OD(ByVal FileName As String, Optional ByVal SyncServer As Boolean = False)
        '//파일을 열어서 템플릿이름을 가져온다
        If Not System.IO.File.Exists(FileName) Then
            Return
        End If

        '//열려잇는화면 닫는다.
        RibbonButton3_Click(Nothing, Nothing)

        Try
            Dim fi As New System.IO.FileInfo(FileName)
            Dim FS As System.IO.Stream
            Dim Source() As Byte = My.Computer.FileSystem.ReadAllBytes(FileName)
            Dim Desbuf() As Byte = {} '//구버젼은 암호화를 해제해야한다

            If Source.Length < 4 Then
                MsgBox("알수없거나 손상된 파일입니다", MsgBoxStyle.Critical, "확인")
                Return
            End If

            '//데이터가 암호화되었는지 체크한다.(구버젼 OD용)
            Dim isEnc As Boolean = False
            If (fi.Extension.ToLower() = (".ecl")) Then isEnc = True
            If isEnc Then
                Desbuf = DeCryptArea(Source, New Byte() {&HAC, &H29, &H55, &H42})
                FS = New IO.MemoryStream(Desbuf, True)
            Else
                FS = New IO.MemoryStream(Source, True)
            End If

            '//불러온기록 추가
            Setting.Data("presetting", "filename") = Prj.FileName

            Dim Br As New IO.BinaryReader(FS, System.Text.Encoding.Default)
            Prj.FileName = FileName
            Prj.Opened = False
            Prj.SFType = STB(Br.ReadBytes(2)) '//세이브파일구조(2)

            'If CInt(Prj.SFType) <> 9 Then
            '    If MsgBox("현재프로그램과 일치하지 않는 버젼입니다" + vbCrLf + "계속 진행하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") <> MsgBoxResult.Ok Then Return
            'End If
            'SyncServer = True ' 2011.06.15 추가 공개버전은 자동적으로 공용코드와 기상코드를 동기화

            Try

                '//버젼확인
                Prj.UIVersion = STB(Br.ReadBytes(10))
                Prj.LGVersino = STB(Br.ReadBytes(10))

                '//추가정보확인
                Prj.Name = STB(Br.ReadBytes(100))
                Prj.Desc = STB(Br.ReadBytes(256))
                Prj.MakeTime = STB(Br.ReadBytes(19))
                Prj.EditTime = STB(Br.ReadBytes(19))

                '//DS1 데이터초기화 및 오픈
                DSET1 = New DS()
                DSET1.AcceptChanges()
                Dim DS1Len As Int64 = Br.ReadInt64
                Dim DS1() As Byte = Br.ReadBytes(CInt(DS1Len))

                'System.IO.File.WriteAllBytes("c:\intel\a.xml", DS1)

                Dim Ms As New IO.MemoryStream(DS1)
                Ms.Position = 0
                Try

                    DSET1.ReadXml(Ms)
                    DSET1.AcceptChanges()
                    Ms.Close()
                Catch ex As Exception
                    MsgBox("파일이 손상되었습니다." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 Open Error")
                End Try

                '//DS1가 있다면 게속 한다
                If String.Compare(Prj.UIVersion, "2014041400") >= 0 Then
                    DSETR1 = New DSR()
                    DSETR1.AcceptChanges()
                    DS1Len = Br.ReadInt64
                    DS1 = Br.ReadBytes(CInt(DS1Len))
                    Ms = New IO.MemoryStream(DS1)
                    Try
                        DSETR1.ExtReport.ReadXml(Ms)
                        DSETR1.AcceptChanges()
                        Ms.Close()
                    Catch ex As Exception
                        MsgBox("기존 버전의 계산결과를 가져올 수 없습니다." & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds2 Open Error")
                    End Try
                End If


                Prj.IsError = False
            Catch ex As Exception
                MsgBox("파일의 저장형태를 알 수 없습니다" + vbCrLf + ex.Message.ToString, MsgBoxStyle.Critical, "불러오기실패")
                Prj.IsError = True
            End Try

            Br.Close()
            FS.Close()

            If Not Prj.IsError Then
                Prj.Opened = True
                Frm_Work.Label1.Text = "데이터를 확인하고 있습니다"
                Frm_Work.Show()

                If DSET1.tbl_buha.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_buha.Rows.Add(New String() {"0", "(없음)"})
                If DSET1.tbl_bunbae.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_bunbae.Rows.Add(New String() {"0", "(없음)"})
                If DSET1.tbl_kongjo.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_kongjo.Rows.Add(New String() {"0", "(없음)"})
                'If DSET1.tbl_kongkub.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_kongkub.Rows.Add(New String() {"0", "(없음)"})
                If DSET1.tbl_myoun.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_myoun.Rows.Add(New String() {"0", "(없음)"})
                If DSET1.tbl_nanbangkiki.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_nanbangkiki.Rows.Add(New String() {"0", "(없음)"})
                If DSET1.tbl_nangbangkiki.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_nangbangkiki.Rows.Add(New String() {"0", "(없음)"})
                If DSET1.tbl_nbunbae.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_nbunbae.Rows.Add(New String() {"0", "(없음)"})
                If DSET1.tbl_new.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_new.Rows.Add(New String() {"0", "(없음)"})
                If DSET1.tbl_profile_od.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_profile_od.Rows.Add(New String() {"0", "(없음)"})
                If DSET1.tbl_weather_od.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_weather_od.Rows.Add(New String() {"0", "(없음)"})
                If DSET1.tbl_yk.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_yk.Rows.Add(New String() {"0", "(없음)"})
                If DSET1.tbl_ReqInfo.Rows.Count < 1 Then
                    Dim newdreq As DS.tbl_ReqInfoRow = DSET1.tbl_ReqInfo.Newtbl_ReqInfoRow()
                    DSET1.tbl_ReqInfo.Addtbl_ReqInfoRow(newdreq)
                End If

                If DSETR1.ExtReport.Rows.Count < 1 Then
                    Dim newdr As DSR.ExtReportRow = DSETR1.ExtReport.NewExtReportRow
                    For i As Integer = 1 To 82
                        newdr("c" + i.ToString("000")) = "-"
                    Next
                    DSETR1.ExtReport.AddExtReportRow(newdr)
                End If

                For Each Drow As DS.tbl_nangbangkikiRow In DSET1.tbl_nangbangkiki.Rows
                    If Drow.냉동기방식 = "0" Then Drow.냉동기방식 = "압축식"
                Next
                For Each Drow As DS.tbl_kongjoRow In DSET1.tbl_kongjo.Rows
                    If Drow.공조방식 = "0" Then Drow.공조방식 = "정풍량"
                Next

                For Each drow As DS.tbl_newRow In DSET1.tbl_new.Rows
                    If drow.신재생냉난방구분 = "" Then drow.신재생냉난방구분 = drow.지열냉난방구분
                Next


                '//save file (weather, profile)
                DSET1.tbl_common_od.Clear()
                DSET1.tbl_profile_od.Clear()
                DSET1.tbl_weather_od.Clear()
                DSET1.weather_cha_od.Clear()
                DSET1.weather_group.Clear()
                DSET1.weather_ilsa_od.Clear()
                DSET1.weather_supdo_od.Clear()
                DSET1.weather_temp_od.Clear()
                DSET1.weather_water.Clear() '//230324
                DSET1.weather_wind.Clear()
                DSET1.weather_river.Clear()

                Dim fn0 As String = AppDomain.CurrentDomain.BaseDirectory + "\common.dat"
                Dim fn1 As String = AppDomain.CurrentDomain.BaseDirectory + "\profile.dat"
                Dim fn2 As String = AppDomain.CurrentDomain.BaseDirectory + "\weather{0}.dat"

                If System.IO.File.Exists(fn0) Then
                    Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn0, ""))
                    If (buffer(0) = &H90) Then '//암호화된파일
                        Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                        Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                        Dim ms0 As New System.IO.MemoryStream(newbuffer)
                        DSET1.tbl_common_od.ReadXml(ms0)
                    Else
                        '//아닌파일
                        DSET1.tbl_common_od.ReadXml(String.Format(fn0, ""))
                    End If
                End If

                If System.IO.File.Exists(fn1) Then
                    Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn1, ""))
                    If (buffer(0) = &H90) Then '//암호화된파일
                        Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                        Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                        Dim ms0 As New System.IO.MemoryStream(newbuffer)
                        DSET1.tbl_profile_od.ReadXml(ms0)
                    Else
                        '//아닌파일
                        DSET1.tbl_profile_od.ReadXml(String.Format(fn1, ""))
                    End If
                End If
                If System.IO.File.Exists(String.Format(fn2, "")) Then
                    Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, ""))
                    If (buffer(0) = &H90) Then '//암호화된파일
                        Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                        Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                        Dim ms0 As New System.IO.MemoryStream(newbuffer)
                        DSET1.tbl_weather_od.ReadXml(ms0)
                    Else
                        '//아닌파일
                        DSET1.tbl_weather_od.ReadXml(String.Format(fn2, ""))
                    End If

                End If
                If System.IO.File.Exists(String.Format(fn2, "_ch")) Then
                    Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, "_ch"))
                    If (buffer(0) = &H90) Then '//암호화된파일
                        Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                        Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                        Dim ms0 As New System.IO.MemoryStream(newbuffer)
                        DSET1.weather_cha_od.ReadXml(ms0)
                    Else
                        '//아닌파일
                        DSET1.weather_cha_od.ReadXml(String.Format(fn2, "_ch"))
                    End If


                End If
                If System.IO.File.Exists(String.Format(fn2, "_gr")) Then
                    Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, "_gr"))
                    If (buffer(0) = &H90) Then '//암호화된파일
                        Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                        Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                        Dim ms0 As New System.IO.MemoryStream(newbuffer)
                        DSET1.weather_group.ReadXml(ms0)
                    Else
                        '//아닌파일
                        DSET1.weather_group.ReadXml(String.Format(fn2, "_gr"))
                    End If
                End If

                If System.IO.File.Exists(String.Format(fn2, "_is")) Then

                    Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, "_is"))
                    If (buffer(0) = &H90) Then '//암호화된파일
                        Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                        Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                        Dim ms0 As New System.IO.MemoryStream(newbuffer)
                        DSET1.weather_ilsa_od.ReadXml(ms0)
                    Else
                        '//아닌파일
                        DSET1.weather_ilsa_od.ReadXml(String.Format(fn2, "_is"))
                    End If

                End If


                If System.IO.File.Exists(String.Format(fn2, "_sd")) Then

                    Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, "_sd"))
                    If (buffer(0) = &H90) Then '//암호화된파일
                        Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                        Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                        Dim ms0 As New System.IO.MemoryStream(newbuffer)
                        DSET1.weather_supdo_od.ReadXml(ms0)
                    Else
                        '//아닌파일
                        DSET1.weather_supdo_od.ReadXml(String.Format(fn2, "_sd"))
                    End If

                End If
                If System.IO.File.Exists(String.Format(fn2, "_tp")) Then

                    Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, "_tp"))
                    If (buffer(0) = &H90) Then '//암호화된파일
                        Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                        Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                        Dim ms0 As New System.IO.MemoryStream(newbuffer)
                        DSET1.weather_temp_od.ReadXml(ms0)
                    Else
                        '//아닌파일
                        DSET1.weather_temp_od.ReadXml(String.Format(fn2, "_tp"))
                    End If

                End If

                If System.IO.File.Exists(String.Format(fn2, "_water")) Then

                    Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, "_water"))
                    If (buffer(0) = &H90) Then '//암호화된파일
                        Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                        Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                        Dim ms0 As New System.IO.MemoryStream(newbuffer)
                        DSET1.weather_water.ReadXml(ms0)
                    Else
                        '//아닌파일
                        DSET1.weather_water.ReadXml(String.Format(fn2, "_water"))
                    End If

                End If

                If System.IO.File.Exists(String.Format(fn2, "_wind")) Then

                    Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, "_wind"))
                    If (buffer(0) = &H90) Then '//암호화된파일
                        Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                        Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                        Dim ms0 As New System.IO.MemoryStream(newbuffer)
                        DSET1.weather_wind.ReadXml(ms0)
                    Else
                        '//아닌파일
                        DSET1.weather_wind.ReadXml(String.Format(fn2, "_wind"))
                    End If

                End If

                If System.IO.File.Exists(String.Format(fn2, "_river")) Then

                    Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, "_river"))
                    If (buffer(0) = &H90) Then '//암호화된파일
                        Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                        Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                        Dim ms0 As New System.IO.MemoryStream(newbuffer)
                        DSET1.weather_river.ReadXml(ms0)
                    Else
                        '//아닌파일
                        DSET1.weather_river.ReadXml(String.Format(fn2, "_river"))
                    End If

                End If

                DSET1.tbl_common_od.AcceptChanges()
                DSET1.tbl_profile_od.AcceptChanges()
                DSET1.tbl_weather_od.AcceptChanges()
                DSET1.weather_cha_od.AcceptChanges()
                DSET1.weather_group.AcceptChanges()
                DSET1.weather_ilsa_od.AcceptChanges()
                DSET1.weather_supdo_od.AcceptChanges()
                DSET1.weather_temp_od.AcceptChanges()

                DSET1.weather_water.AcceptChanges() '//230324
                DSET1.weather_wind.AcceptChanges()
                DSET1.weather_river.AcceptChanges()

                DSET1.AcceptChanges()

                Frm_Work.Close()



                '//모든자료는 내장된 자료만을 사용한다
                SyncServer = False

                '//구버젼파일이고 인터넷이 연결되었을경우 업데이트를 한다.
                If isEnc AndAlso Pub.CheckInternet() Then
                    Read_Profile_OD()
                    If SyncServer Then     '//공용및 기상데이터 자동싱크
                        'Read_WeatherData_OD()  '//disable 230324
                        Read_CommonCode_OD()
                        Read_Profile_OD()
                        'Read_WatherGroup() '//disable 230324
                    End If
                End If

                CalcO = New CalculatorOD(Prj.LGVersino)    '//계삭식클래스 초기화
                Me.mbt_save.Enabled = True
                Me.mbt_save2.Enabled = Me.mbt_save.Enabled
                Refresh_StatusInfo()  '//화면하단의 정보창표시

                Menu_시작화면()

                '//현재 연 파일명을 기록해준다.
                Me.Save_FilHistory(Prj.FileName)
                Me.Read_FilHistory()

                CalcO.Validation()    '//null보정

                '//팡리명이 너무길면안되니 경로를 뺴고 딱 파일명만 보여줍니다.
                'Me.lbl_filename.Text = Prj.FileName.Substring(Prj.FileName.LastIndexOf("\") + 1)

                '//Version 정보를 확인
                'Work_msg("데이터 버젼확인중")
                'Dim MyVersion As String '= Format(My.Application.Info.Version.Minor, "0000") & Format(My.Application.Info.Version.Build, "0000")
                'Dim L As New ArinLogin.ArinLOgin
                'Dim VersionInfo As ArinLogin.ArinLOgin.sVersionInfo = Nothing
                ''/공용코드버젼확인
                'Try
                '    MyVersion = DSET1.tbl_Desc.Rows(0)("versionc").ToString
                '    If MyVersion = "" Then MyVersion = "20100101"
                'Catch ex As Exception
                '    MyVersion = "20100101"
                'End Try
                'Try

                '    VersionInfo = L.Get_LastVersion("CO")   '//버젼을 가져오는데  eco 버젼만 가져오게 바꺼야겟죵 ^^ 구분자를 넣도록 합시닷!
                '    If VersionInfo.Ver <> "0" AndAlso (CInt(VersionInfo.Ver) > CInt(MyVersion)) Then   '//0은 없거나 관리안함의 뜻이므로 넘어간다.
                '        Dim Msg As New System.Text.StringBuilder
                '        Msg.AppendLine("새로운 버젼이 확인되었습니다" & vbCrLf)
                '        Msg.AppendLine("현재버젼:" & MyVersion & " 신규버젼:" & VersionInfo.Ver)
                '        Msg.AppendLine("----------------------------------")
                '        Msg.AppendLine(VersionInfo.Desc)
                '        Msg.AppendLine("----------------------------------")
                '        If VersionInfo.Link.Trim = "" Then VersionInfo.Link = "http://홈페이지주소"
                '        ' Msg.AppendLine("신규버젼을 확인하기위한 페이지를 여시겠습니까?")
                '        If MsgBox(Msg.ToString, MsgBoxStyle.Information, "버젼확인") = MsgBoxResult.Ok Then
                '            SyncServer = True
                '            'Shell("explorer " & VersionInfo.Link, AppWinStyle.NormalFocus)
                '            ' End
                '        End If
                '    End If
                'Catch ex As Exception
                '    MsgBox("공용코드 에러" & ex.Message.ToString)
                'End Try


                '//프로파일버젼업체크 140420
                'Try
                '    MyVersion = DSET1.tbl_Desc.Rows(0)("versionp").ToString
                '    If MyVersion = "" Then MyVersion = "20100101"
                'Catch ex As Exception
                '    MyVersion = "20100101"
                'End Try
                'Try

                '    VersionInfo = L.Get_LastVersion("PO")   '//버젼을 가져오는데  eco 버젼만 가져오게 바꺼야겟죵 ^^ 구분자를 넣도록 합시닷!
                '    If VersionInfo.Ver <> "0" AndAlso (CInt(VersionInfo.Ver) > CInt(MyVersion)) Then   '//0은 없거나 관리안함의 뜻이므로 넘어간다.
                '        Dim Msg As New System.Text.StringBuilder
                '        Msg.AppendLine("새로운 버젼이 확인되었습니다" & vbCrLf)
                '        Msg.AppendLine("현재버젼:" & MyVersion & " 신규버젼:" & VersionInfo.Ver)
                '        Msg.AppendLine("----------------------------------")
                '        Msg.AppendLine(VersionInfo.Desc)
                '        Msg.AppendLine("----------------------------------")
                '        If VersionInfo.Link.Trim = "" Then VersionInfo.Link = "http://홈페이지주소"
                '        ' Msg.AppendLine("신규버젼을 확인하기위한 페이지를 여시겠습니까?")
                '        If MsgBox(Msg.ToString, MsgBoxStyle.Information, "버젼확인") = MsgBoxResult.Ok Then
                '            SyncServer = True
                '            'Shell("explorer " & VersionInfo.Link, AppWinStyle.NormalFocus)
                '            ' End
                '        End If
                '    End If
                'Catch ex As Exception
                '    MsgBox("표준프로파일(OD) 에러" & ex.Message.ToString)
                'End Try

                '/기상데이터버젼확인
                'Try
                '    MyVersion = DSET1.tbl_Desc.Rows(0)("versionw").ToString
                '    If MyVersion = "" Then MyVersion = "20100101"
                'Catch ex As Exception
                '    MyVersion = "20100101"
                'End Try
                'Try
                '    'MyVersion = dset1.tbl_Desc.Rows(0)("versionw").ToString
                '    VersionInfo = L.Get_LastVersion("W")   '//버젼을 가져오는데  eco 버젼만 가져오게 바꺼야겟죵 ^^ 구분자를 넣도록 합시닷!
                '    If VersionInfo.Ver <> "0" AndAlso (CInt(VersionInfo.Ver) > CInt(MyVersion)) Then   '//0은 없거나 관리안함의 뜻이므로 넘어간다.
                '        Dim Msg As New System.Text.StringBuilder
                '        Msg.AppendLine("새로운 버젼이 확인되었습니다" & vbCrLf)
                '        Msg.AppendLine("현재버젼:" & MyVersion & " 신규버젼:" & VersionInfo.Ver)
                '        Msg.AppendLine("----------------------------------")
                '        Msg.AppendLine(VersionInfo.Desc)
                '        Msg.AppendLine("----------------------------------")
                '        If VersionInfo.Link.Trim = "" Then VersionInfo.Link = "http://홈페이지주소"
                '        ' Msg.AppendLine("신규버젼을 확인하기위한 페이지를 여시겠습니까?")
                '        If MsgBox(Msg.ToString, MsgBoxStyle.Information, "버젼확인") = MsgBoxResult.Ok Then
                '            SyncServer = True
                '            'Shell("explorer " & VersionInfo.Link, AppWinStyle.NormalFocus)
                '            ' End
                '        End If
                '    End If
                'Catch ex As Exception

                'End Try

                'Me.Refresh_MenuItems("")

                '/Dim fi As New System.IO.FileInfo(Prj.FileName)
                lbl_filename.Text = "[" + fi.Name + "]"
                Work_msg("")
            Else
                '//파일불러오기 실패로인해서 다음처리를 하지않는다.
                lbl_filename.Text = "[ERROR]"
            End If
        Catch ex As Exception
            Dim sb As New System.Text.StringBuilder
            Dim st As New StackTrace(True)
            sb.AppendLine("    프레임 수: " + st.FrameCount.ToString())
            sb.AppendLine("현  재 메서드: " + st.GetFrame(0).GetMethod().Name)
            sb.AppendLine("호출한 메서드: " + st.GetFrame(1).GetMethod().Name)
            sb.AppendLine("진  입 메서드: " + st.GetFrame(st.FrameCount - 1).GetMethod().Name)
            sb.AppendLine()

            sb.AppendLine("-- 호출 스택 --")
            For Each sf As StackFrame In st.GetFrames()
                sb.AppendLine(
                     "  파  일: " + sf.GetFileName() +
                     "      행: " + sf.GetFileLineNumber().ToString() +
                     "      열: " + sf.GetFileColumnNumber().ToString() +
                     "  오프셋: " + sf.GetILOffset().ToString() +
                     "  메서드: " + sf.GetMethod().Name)
            Next
            MsgBox(sb.ToString(), MsgBoxStyle.Critical, "File Open Error")
        End Try

    End Sub


    Private GroupList_Zone As ArrayList
    Private GroupList_nanbangkiki As ArrayList
    Private GroupList_NanbangKongkub As ArrayList
    Private GroupList_Kongjo As ArrayList
    Private GroupList_NanbangBunbae As ArrayList
    Private GroupList_Naengbankiki As ArrayList
    Private GroupList_New As ArrayList
    Private GroupList_Yk As ArrayList
    Private GroupList_Bunbae As ArrayList

    Private Sub Save_FilHistory(ByVal filename As String)
        Dim Path As String = filename.Substring(0, filename.LastIndexOf("\"))
        Dim Name As String = filename.Substring(filename.LastIndexOf("\"))
        Path = Path.ToUpper.Replace(My.Application.Info.DirectoryPath.ToUpper, ".\")
        Path = Path.Replace("\\", "\")
        Name = Name.Trim(CChar("\"))

        '//현재 리스트가 존재하는지확인
        Dim Exist As Boolean = False
        For i As Integer = 0 To 4
            If PreFile(i).ToLower.Trim = filename.ToLower.Trim Then
                PreFile(i) = Path & "\" & Name
                Exist = True
                Exit For
            End If
        Next

        If Exist = False Then    '//미뤄서 1번에 넣도록 한다.
            PreFile(4) = PreFile(3)
            PreFile(3) = PreFile(2)
            PreFile(2) = PreFile(1)
            PreFile(1) = PreFile(0)
            PreFile(0) = filename
        End If
        For i As Integer = 1 To 5
            Setting.Data("presetting2", "filename" & i) = PreFile(i - 1)
        Next
        Read_FilHistory() '//저장한후에는 다시 읽어오도록한다.
    End Sub

    ''' <summary>
    ''' 기존에 사용한 파일 목록을 가져온다.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Read_FilHistory()

        Dim listItem As RibbonListItem = New RibbonListItem(New RibbonLabel("최근 사용한 파일"))
        listItem.AllowSelection = False
        c1Ribbon1.ApplicationMenu.RightPaneItems.Clear()
        c1Ribbon1.ApplicationMenu.RightPaneItems.Add(listItem)
        c1Ribbon1.ApplicationMenu.RightPaneItems.Add(New RibbonListItem(New RibbonSeparator()))



        Dim Path As String
        Dim Name As String
        '//현재 리스트가 존재하는지확인

        Dim filelist As New List(Of String)
        For i As Integer = 1 To 10
            Dim Filename As String = ""

            Filename = Setting.Read("presetting2", "filename" & i, "")

            Filename = Filename.Replace(".\", My.Application.Info.DirectoryPath & "\")
            PreFile(i - 1) = Filename

            Path = "" : Name = ""
            If Filename.Trim <> "" Then
                Path = Filename.Substring(0, Filename.LastIndexOf("\")) & "\"
                Path = Path.Replace("\\", "\")
                Name = Filename.Substring(Filename.LastIndexOf("\"))
                Name = Name.Trim(CChar("\"))
            End If

            If (String.IsNullOrEmpty(Name)) Then Continue For


            listItem = New RibbonListItem()
            listItem.AllowSelection = True

            If filelist.IndexOf(Path + Name) = -1 Then
                filelist.Add(Path + Name)
            Else
                Continue For
            End If

            Dim but As New RibbonButton(Name)
            but.Tag = Path + Name
            but.Enabled = True
            but.Visible = True
            but.SelectableInListItem = True
            but.ToolTip = Path + Name

            'c1Ribbon1.ApplicationMenu.LeftPaneItems.Add(but)

            If but.Text.Length > 15 Then
                but.Text = but.Text.Substring(0, 15) + "..."
            End If
            AddHandler but.Click, AddressOf clickHistitem

            listItem.Items.Add(but)
            c1Ribbon1.ApplicationMenu.RightPaneItems.Add(listItem)
        Next

    End Sub

    Sub clickHistitem(sender As Object, e As System.EventArgs)
        Dim but As RibbonButton = sender
        Dim filename As String = but.Tag.ToString()

        If MsgBox("다음 파일을 불러오겠습니까?" + vbCrLf + filename, MsgBoxStyle.Question Or MsgBoxStyle.YesNo, "확인") <> MsgBoxResult.Yes Then Return

        Func_Open_OD(filename)
    End Sub


    ''' <summary>
    ''' 이 메뉴를 단독으로 호출하려면 우선 열려있는 폼의 데이터를 완료시켜주세요 menu 에서 호출하는 경우 미리 작동됩니다.
    ''' </summary>
    ''' <param name="FileName"></param>
    Private Sub Func_Save_OD(ByVal FileName As String, Optional msg As Boolean = True)

        DSET1.AcceptChanges()
        DSETR1.AcceptChanges()

        '//파일을 열어서 템플릿이름을 가져온다
        Dim Fs As New IO.FileStream(FileName, IO.FileMode.Create)
        Dim Bw As New IO.BinaryWriter(Fs, System.Text.Encoding.Default)

        Prj.SFType = "10" '// EcoODNew 버전

        '//세이브파일구조번호저장(2)
        Bw.Write(System.Text.Encoding.Default.GetBytes(Prj.SFType))

        '//저장순서는 ReadMe.txt 참조
        Dim UIVer() As Byte = System.Text.Encoding.Default.GetBytes("2017062000")
        Bw.Write(UIVer)

        Dim LGVer() As Byte = System.Text.Encoding.Default.GetBytes("2017062000")
        Bw.Write(LGVer)

        '//템플릿 이름 저장(100한글 50자)
        Dim Name() As Byte = System.Text.Encoding.Default.GetBytes(Prj.Name)
        ReDim Preserve Name(99)
        Bw.Write(Name)

        '//템플릿 설명 저장(256 한글 128자)
        Dim Desc() As Byte = System.Text.Encoding.Default.GetBytes(Prj.Desc)
        ReDim Preserve Desc(255)
        Bw.Write(Desc)

        '//템플릿 생성시간
        Bw.Write(System.Text.Encoding.Default.GetBytes(Prj.MakeTime))

        '//템플릿 최종변경시간(항상현재시간을 저장한다)
        Bw.Write(System.Text.Encoding.Default.GetBytes(CStr(Format(Now, "yyyy-MM-dd HH:mm:ss"))))

        'Select Case Prj.SFType
        '    Case "01"   '//암호 8바이트추가한다.
        '        If Prj.Password.Length > 8 Then
        '            MsgBox("암호의길이가 8을 초과합니다" & vbCrLf & "암호는 저장되지않습니다", MsgBoxStyle.Information, "확인")
        '            Prj.Password = ""
        '        End If
        '        Dim Pass() As Byte = System.Text.Encoding.Default.GetBytes(Prj.Password)
        '        ReDim Preserve Pass(7)
        '        Bw.Write(Pass)

        'End Select

        '//1번쨰 데이터소스를 저장합니다.
        Dim Pos1 As Int64 = Bw.BaseStream.Position
        DSET1.WriteXml(Fs)
        Dim Pos1e As Int64 = Bw.BaseStream.Position
        Dim Dse1Len As Int64 = Pos1e - Pos1   '//데이터셋의 길이
        Bw.BaseStream.Position = Pos1   '//처음위치로이동
        Bw.Write(Dse1Len)   '//데이터셋길이저장
        DSET1.WriteXml(Fs)   '//데이터셋다시저장

        '//계산결과를 저장한다(ExtReport) - 170414
        Dim Pos2 As Int64 = Bw.BaseStream.Position
        DSETR1.ExtReport.WriteXml(Fs)
        Dim Pos2e As Int64 = Bw.BaseStream.Position
        Dim Dse2Len As Int64 = Pos2e - Pos2  '//데이터셋의 길이
        Bw.BaseStream.Position = Pos2   '//처음위치로이동
        Bw.Write(Dse2Len)   '//데이터셋길이저장
        DSETR1.ExtReport.WriteXml(Fs)   '//데이터셋다시저장

ENDSTAT:  '//오류발생시 강제종료를 위한 분기문
        Bw.Flush()
        Bw.Close()
        Fs.Close()

        '//파일열때랑 저장할때(새이름포함) 이름이 바뀔수잇으므로 해당 이벤트에만 화면을 갱신할거에요~
        'Me.lbl_filename.Text = Prj.FileName.Substring(Prj.FileName.LastIndexOf("\") + 1)

        'Dim 암호화 As Boolean = False
        'If 암호화 Then
        '    Dim Desbuf() As Byte = {}
        '    Dim Source() As Byte = My.Computer.FileSystem.ReadAllBytes(Prj.FileName)
        '    Desbuf = DeCryptArea(Source, New Byte() {&HAC, &H29, &H55, &H42})
        '    My.Computer.FileSystem.WriteAllBytes(Prj.FileName, Desbuf, False)
        'End If

        If msg Then
            MsgBox("파일이 저장되었습니다", MsgBoxStyle.Information, "확인")
        End If


        'Me.bt_desc.PerformClick()

        'Bw.Write(CStr(Prj.UIVersion))
        'Bw.Write(CStr(Prj.LGVersino))
        'Bw.Write(CStr(IIf(Prj.Name = "", "프로젝트이름", Prj.Name)))
        'Bw.Write(CStr(IIf(Prj.Desc = "", "프로젝트설명", Prj.Desc)))
        ''//템플릿 생성시간
        'Bw.Write(CStr(Format(Now, "yyyy-MM-dd HH:mm:ss")))
        'DSET.WriteXml(Fs)
    End Sub



#Region "Show_Menu"

    Private Sub Menu_시작화면()
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Show_Menu(1)
    End Sub

#End Region

    Private Sub Read_SEtting()
        Work_msg("설정을 확인하는중")

        '프로젝트 버젼정보
        Prj.MaxUI = "20091231"
        Prj.MaxLG = "20091231"
        Prj.Admin = True
        Prj.Password = ""   '//암호는 기본해제되어있음

        Try
            For Each A As Net.NetworkInformation.NetworkInterface In ArinNet.MyNet.GetMacArray
                If A.NetworkInterfaceType <> Net.NetworkInformation.NetworkInterfaceType.Loopback Then
                    Prj.CUrMac = A.GetPhysicalAddress.ToString
                End If
            Next

            Dim ipentry As Net.IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName)
            For Each C As Net.IPAddress In ipentry.AddressList
                If C.ToString.Length <= 15 AndAlso C.ToString.Length > 4 Then
                    Prj.CUrIP = C.ToString
                    Exit For
                End If
            Next

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error - Network")
        End Try


        '//데이터디렉토리정보를 확인한다 이곳에서 데이터베이스및 기타 설정파일을 저장하게한다 
        '//이는 인터넷설치버젼의경우 사용자폴더로 들어가기떄문이다
        Work_msg("데이터폴더를 확인합니다")
        Try
            If DataDir.Exists = False Then DataDir.Create() '//데이터폴더가없다면 생성
            If TemplateDir.Exists = False Then
                TemplateDir.Create()
                'If System.IO.File.Exists(My.Application.Info.DirectoryPath & "\template\sample.tpl") = True Then
                '    My.Computer.FileSystem.CopyFile(My.Application.Info.DirectoryPath & "\template\sample.tpl", TemplateDir.FullName & "\sample.tpl", True)
                'End If
            End If

            Work_msg("기본정보를 설정합니다")
            Setting = New arUtil.Setting() ' CEnergy.MyINI(DataDir.FullName & "\arinwaret4.ini")
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error - Setting")
        End Try

        Work_msg("")
        Me.Activate()
    End Sub

    Private Sub Read_PreFile(ByVal i As Short)
        'If Prj.LoginTime = "" Then
        '    MsgBox("먼저 로그인을 하세요", MsgBoxStyle.Information, "확인")
        '    Return
        'End If
        If PreFile(i).Trim <> "" Then
            If MsgBox(PreFile(i) & "파일을 불러오시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "불러오기") <> MsgBoxResult.Ok Then Return
            Dim Filename As String = PreFile(i)
            If System.IO.File.Exists(Filename) = True Then
                Me.Func_Open_OD(Filename)
            Else
                MsgBox("해당 파일이 존재하지 않습니다." + vbCrLf + PreFile(i), MsgBoxStyle.Critical, "확인")
            End If
        End If
    End Sub

#Region "Top Menu"

    Private Sub Menu_Open()
        '.Filter = "템플릿파일(*.ecl;*.ecl2)|*.ecl;*.ecl2|모든파일(*.*)|*.*",
        'Od.InitialDirectory = TemplteDir.FullName
        Dim Od As New OpenFileDialog With {
            .FileName = Prj.FileName,
            .Filter = "템플릿파일(*." + FileExt + ")|*." + FileExt + "|모든파일(*.*)|*.*",
        .FilterIndex = 0
        }


        If Od.ShowDialog <> Windows.Forms.DialogResult.OK Then Return


        Func_Open_OD(Od.FileName)
    End Sub

    Private Sub Menu_New()
        '물어야하니 if
        If MsgBox("새파일을 작성하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") <> MsgBoxResult.Ok Then Return '//ok 안하면 빠져나가기
        Dim new_string As String = ""

        new_string = "\basefile\new." + FileExt

        '//원본샘플파일
        Dim Srcfile As New System.IO.FileInfo(My.Application.Info.DirectoryPath & new_string)
        If Srcfile.Exists = False Then
            MsgBox("원본샘플파일(" + new_string + ")이 존재하지않습니다", MsgBoxStyle.Critical, "확인")
            Return
        End If

        Dim SD As New SaveFileDialog With {
            .FileName = "new" & Format(Now, "mmdd") & "." + FileExt,
            .Filter = "데이터파일(*." + FileExt + ")|*." + FileExt
        }

        '//저장할 파일명을 입력안하면 빠져나가기
        If SD.ShowDialog <> Windows.Forms.DialogResult.OK Then Return

        '//복사해서 열어주기
        If System.IO.File.Exists(SD.FileName) Then System.IO.File.Delete(SD.FileName)
        Srcfile.CopyTo(SD.FileName)
        Me.Func_Open_OD(SD.FileName, True)
    End Sub

#End Region


    '''현재열려있는 메뉴를 닫습니다.
    Private Sub Close_menu()
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If

        If Me.OpenedForm <> E_MenuIdx.NONE Then
            MsgBox("현재열려있는폼 :" + Me.OpenedForm.ToString())

        End If
    End Sub

    '''메뉴인덱스에해당하는 폼을 반환합니다.
    Private Function GetFormfromMenuIDX(nidx As E_MenuIdx) As CForm
        Dim f As CForm
        Select Case nidx
            Case E_MenuIdx.Form1
                f = Frm_1_Basic
            Case E_MenuIdx.Form2
                f = Frm_2_Build
            Case E_MenuIdx.Form3
                f = Frm_3_Mach
            Case E_MenuIdx.Form5
                f = Frm_5_New
            Case Else
                f = Nothing
        End Select
        Return f
    End Function
    Private Function GetMenuIDX(tagstring As String) As E_MenuIdx
        Dim v As Array = [Enum].GetValues(GetType(E_MenuIdx))
        For i As Integer = 0 To v.Length - 1
            Dim val As Integer = v(i)
            Dim str As String = [Enum].GetName(GetType(E_MenuIdx), val)
            If str = tagstring Then
                Return val
            End If
        Next
        Return E_MenuIdx.NONE
    End Function

    Dim CurFormName As String = "Nothing" '//2011.06.03 신규추가

    Public Sub Func_Calc_OD()
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        DSET1.AcceptChanges()
        DSETR1.AcceptChanges()


        If DSET1.tbl_Desc.Rows.Count < 1 Then
            MsgBox("일반사항정보가 입력되지 않았습니다", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인")
            Return
        End If

        Dim drArea As DS.tbl_DescRow = DSET1.tbl_Desc.Rows(0)
        If drArea.IsbuildareaNull() OrElse drArea.buildarea = "0" Then
            MsgBox("지역정보가 입력되지 않았습니다", MsgBoxStyle.Critical, "확인")
            Return
        End If

        '//
        If DSET1.tbl_type.Select("code <> '0'").Length < 1 Then
            MsgBox("층별개요가 입력되지 않았습니다", MsgBoxStyle.Critical, "확인")
            Return
        End If
        If DSET1.tbl_yk.Select("code <> '0'").Length < 1 Then
            MsgBox("열관류율이 입력되지 않았습니다", MsgBoxStyle.Critical, "확인")
            Return
        End If
        If DSET1.tbl_myoun.Select("code <> '0'").Length < 1 Then
            MsgBox("입력면 정보가 입력되지 않았습니다", MsgBoxStyle.Critical, "확인")
            Return
        End If
        If DSET1.tbl_nanbangkiki.Select("code <> '0'").Length + DSET1.tbl_nangbangkiki.Select("code <> '0'").Length < 1 Then
            MsgBox("냉난방기기 정보가 입력되지 않았습니다", MsgBoxStyle.Critical, "확인")
            Return
        End If

        '//난방기기데이터검사 170628 0005
        For Each dr As DS.tbl_nanbangkikiRow In DSET1.tbl_nanbangkiki.Select("code <> '0'")
            If dr.열생산기기방식 = "히트펌프" Then
                Dim 정격보일러COP As String = dr.정격보일러COP
                If 정격보일러COP = "" Then 정격보일러COP = "0"
                Dim fcop As Decimal = TOSG(정격보일러COP)
                If fcop <= 0 Then
                    MsgBox("히트펌프의 성적계수가 입력되지 않았습니다", MsgBoxStyle.Critical, "확인")
                    Return
                End If
            Else
                '정격보일러효율
                Dim 정격보일러효율 As String = dr.정격보일러효율
                If 정격보일러효율 = "" Then 정격보일러효율 = "0"
                Dim fcop As Decimal = TOSG(정격보일러효율)
                If fcop <= 0 AndAlso dr.열생산기기방식 <> "지역난방" Then
                    MsgBox(dr.열생산기기방식 + "의 기기효율이 입력되지 않았습니다", MsgBoxStyle.Critical, "확인")
                    Return
                End If
            End If
        Next

        'If Frm_Calc.ShowDialog <> Windows.Forms.DialogResult.OK Then Return
        Dim Type As CalculatorOD.ECalc = CalculatorOD.ECalc.All

        If MsgBox("계산을 시작하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") <> MsgBoxResult.Ok Then Return

        Work_msg("준비중...")
        Frm_Work.ProgressBar1.Visible = True
        Frm_Work.ProgressBar1.Maximum = 12
        Frm_Work.ProgressBar1.Minimum = 0
        Frm_Work.ProgressBar1.Value = 0
        'Frm_Work.TopMost = True
        Frm_Work.Show()


        CalcO = New CalculatorOD(Prj.LGVersino)    '//계삭식클래스 초기화

        Dim St As Date = Now    '//계산시작
        Dim calcOK As Boolean = False

        Try
            calcOK = CalcO.Start(Type, Log)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
            Log.AppendLine(ex.Message + ex.StackTrace)
            calcOK = False
        End Try

        If calcOK Then   '//파라미터 True 라면 소요량이 추가로 게산된다.
            CalcO.Summary.All()
        Else
            Frm_Work.Dispose()
            MsgBox("계산이 완료되지 않았습니다", MsgBoxStyle.Information, "확인")
            If Log.ToString <> "" Then
                Dim fn As String = AppDomain.CurrentDomain.BaseDirectory + "\\Error.txt"
                My.Computer.FileSystem.WriteAllText(fn, Log.ToString, False)
                Shell("notepad " + fn, AppWinStyle.NormalFocus)
            End If
            Return  '/리턴문에의해서 밑에 줄은 실행이 되지않습니다.
        End If

        Dim Et As Date = Now    '//게산종료
        Frm_Work.Dispose()
        If Log.ToString <> "" Then '//이건 오류발생시 로그를 기록하게한건데..작동안한거보니 어딘가에서 사용이 꺼져잇나보네요. 그리중요한건 아님.
            Dim fn As String = AppDomain.CurrentDomain.BaseDirectory + "\\Error.txt"
            My.Computer.FileSystem.WriteAllText(fn, Log.ToString, False)
            Shell("notepad " + fn, AppWinStyle.NormalFocus)
        Else

            Func_Calc_OD_ExtReport()

            Frm_v20091231_Report.Visible = False
            Frm_v20091231_Report.Show()
            Frm_v20091231_Report.Visible = False
            'MsgBox("계산완료" & vbCrLf & CType(Et - St, System.TimeSpan).ToString, MsgBoxStyle.Information, "경과시간")
            Frm_v20091231_Report.Visible = True
        End If
    End Sub


    ''' <summary>
    ''' 17-05-14 소요량 평가서 값 계산
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Func_Calc_OD_ExtReport()

        Dim IDX As Integer = 0

        Dim Total2 As Double = 0.0
        Dim Total1 As Double = 0.0
        For Each Dr0 As DS.tbl_typeRow In DSET1.tbl_type.Rows
            Dim multi As Double = 1.0
            Select Case Dr0.시설용도
                Case "0011" '교육연구시설(초중고)"
                    multi = 1.12
                Case "0012" '교육연구시설(etc)
                    multi = 0.98
            End Select
            Total1 += Dr0.면적 * multi
            Total2 += Dr0.면적
        Next
        Dim addmulti As Double = 0
        If Total2 <> 0 Then
            addmulti = Total1 / Total2
        Else
            addmulti = 1.0
        End If


        DSETR1.ExtReport.Clear()
        Dim NewDR As DSR.ExtReportRow = DSETR1.ExtReport.NewExtReportRow

        '//c001 = 냉.난방면적 => 2.층별개요 - 비주거면적 합
        Dim P(100) As String
        For i As Integer = 0 To P.GetUpperBound(0)
            P(i) = ""
        Next


        Dim _C001 As Single = 0
        For Each dr As DS.tbl_typeRow In DSET1.tbl_type.Rows
            If Not dr.Is면적Null Then _C001 += dr.면적
        Next

        P(0) = _C001.ToString("N2") + "(㎡)"



        '//C002 =  지상층연면적 = 2.연면적- 지상층
        '//C003 =  지상층연면적 = 2.연면적- 지하층
        '//c004 = 층고
        '//c005 = 천장고
        '//c006 = 지상층수
        '//c007 = 지하층수
        Dim _C002 As Single = 0
        Dim _C003 As Single = 0
        'Dim C004 As String = ""
        'Dim C005 As String = ""
        'Dim C006 As String = ""
        'Dim C007 As String = ""
        If DSET1.tbl_Desc.Rows.Count > 0 Then
            Dim drDesc As DS.tbl_DescRow = DSET1.tbl_Desc.Rows(0)
            If IsNumeric(drDesc.buildm23) Then _C002 = TOSG(T, drDesc.buildm23)
            If IsNumeric(drDesc.buildm21) Then _C003 = TOSG(T, drDesc.buildm21)
            If Not drDesc.Is층고Null() Then P(3) = drDesc.층고 + "(m)"
            If Not drDesc.Is천장고Null() Then P(4) = drDesc.천장고 + "(m)"
            If Not drDesc.Isbuilds2Null() Then P(5) = drDesc.builds2 + "층"
            If Not drDesc.Isbuilds1Null() Then P(6) = drDesc.builds1 + "층"
        End If

        P(1) = _C002.ToString("N2") + "(㎡)"
        P(2) = _C003.ToString("N2") + "(㎡)"

        '//C008 ~ C0015 ( 입력면의 면적 합 및 열관류율)
        'Dim C008, C009, C010, C011, C012, C013, C014, C015 As String
        'C008 = ""
        'C009 = ""
        'C010 = ""
        'C011 = ""
        'C012 = ""
        'C013 = ""
        'C014 = ""
        'C015 = ""
        Dim 벽체면적합 As Single = 0
        Dim 창문면적합 As Single = 0
        Dim 지붕면적합 As Single = 0
        Dim 바닥면적합 As Single = 0
        Dim 벽체열관류율합 As Single = 0
        Dim 창문열관류율합 As Single = 0
        Dim 지붕열관류율합 As Single = 0
        Dim 바닥열관류율합 As Single = 0
        For Each dr면 As DS.tbl_myounRow In DSET1.tbl_myoun.Select("code <> '0' and isnull(열관류율2,'') <> ''")
            Dim 열관류코드 As String = dr면.열관류율2

            For Each dr열 As DS.tbl_ykRow In DSET1.tbl_yk.Select("code='" + 열관류코드 + "'")
                Select Case CInt(dr열.면형태)
                    Case 0  '//외벽,벽체
                        벽체면적합 += TOSG(T, dr면.건축부위면적)
                        벽체열관류율합 += TOSG(T, dr면.열관류율) * TOSG(T, dr면.건축부위면적)
                    Case 3  '//내벽,벽체
                        벽체면적합 += TOSG(T, dr면.건축부위면적)
                        벽체열관류율합 += TOSG(T, dr면.열관류율) * TOSG(T, dr면.건축부위면적) * 0.7
                    Case 1  '//외벽,지붕
                        지붕면적합 += TOSG(T, dr면.건축부위면적)
                        지붕열관류율합 += TOSG(T, dr면.열관류율) * TOSG(T, dr면.건축부위면적)
                    Case 4 '//내벽,지붕
                        지붕면적합 += TOSG(T, dr면.건축부위면적)
                        지붕열관류율합 += TOSG(T, dr면.열관류율) * TOSG(T, dr면.건축부위면적) * 0.7
                    Case 2  '//외벽,바닥
                        바닥면적합 += TOSG(T, dr면.건축부위면적)
                        바닥열관류율합 += TOSG(T, dr면.열관류율) * TOSG(T, dr면.건축부위면적)
                    Case 5  '//내벽,바닥
                        바닥면적합 += TOSG(T, dr면.건축부위면적)
                        바닥열관류율합 += TOSG(T, dr면.열관류율) * TOSG(T, dr면.건축부위면적) * 0.7
                    Case 7, 10, 12  '//외부창
                        창문면적합 += TOSG(T, dr면.건축부위면적)
                        창문열관류율합 += TOSG(T, dr면.열관류율) * TOSG(T, dr면.건축부위면적)
                    Case 8, 11, 13 '//내부창
                        창문면적합 += TOSG(T, dr면.건축부위면적)
                        창문열관류율합 += TOSG(T, dr면.열관류율) * TOSG(T, dr면.건축부위면적) * 0.8
                End Select
            Next
        Next

        P(7) = 벽체면적합.ToString("N2")
        P(8) = 창문면적합.ToString("N2")
        P(9) = 지붕면적합.ToString("N2")
        P(10) = 바닥면적합.ToString("N2")

        If 벽체면적합 > 0 Then
            P(11) = (벽체열관류율합 / 벽체면적합).ToString("N3")
        End If

        If 창문면적합 > 0 Then
            P(12) = (창문열관류율합 / 창문면적합).ToString("N3")
        End If

        If 지붕면적합 > 0 Then
            P(13) = (지붕열관류율합 / 지붕면적합).ToString("N3")
        End If

        If 바닥면적합 > 0 Then
            P(14) = (바닥열관류율합 / 바닥면적합).ToString("N3")
        End If


        '//기계 - 난방
        Dim 난방_MAX_기기용량합 As Single = 0
        Dim 난방_MAX_기기명칭 As String = ""
        Dim 난방_MAX_기기방식 As String = ""
        Dim 난방_MAX_연료방식 As String = ""
        Dim 난방_SUM_기기용량합 As Single = 0

        Dim 난방_용량가중효율 As Single = 0
        Dim 난방_용량가중COP As Single = 0

        Dim 난방_용량가중효율_MAX_기기용량 As String = 0
        Dim 난방_SUM_펌프동력 As Single = 0
        Dim 난방_SUM_전기_기기용량 As Single = 0
        Dim 난방_SUM_전체_기기용량 As Single = 0

        Dim 급탕_MAX_기기용량합 As Single = 0
        Dim 급탕_MAX_기기명칭 As String = ""
        Dim 급탕_MAX_기기방식 As String = ""
        Dim 급탕_MAX_연료방식 As String = ""

        Dim 급탕_SUM_기기용량합 As Single = 0

        Dim 급탕_용량가중효율 As Single = 0
        Dim 급탕_용량가중COP As Single = 0

        Dim 급탕_용량가중효율_MAX_기기용량 As String = 0
        Dim 급탕_SUM_펌프동력 As Single = 0
        Dim 급탕_SUM_전기_기기용량 As Single = 0
        Dim 급탕_SUM_전체_기기용량 As Single = 0

        For Each dr As DS.tbl_nanbangkikiRow In DSET1.tbl_nanbangkiki.Select("code <> '0'")

            난방_SUM_전체_기기용량 += TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
            급탕_SUM_전체_기기용량 += TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)

            '//보일러,지역난방,전기보일러,히트펌프
            Dim 난방기기용량합 As Single = 0
            Dim 급탕기기용량합 As Single = 0

            If dr.난방급탕구분 = "난방용" Then
                난방_SUM_기기용량합 += TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
                난방_SUM_펌프동력 += TOSG(T, dr.펌프동력)
                난방기기용량합 = TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)

                If 난방기기용량합 > 난방_MAX_기기용량합 Then
                    난방_MAX_기기용량합 = 난방기기용량합
                    난방_MAX_기기명칭 = dr.설명
                    난방_MAX_기기방식 = dr.열생산기기방식
                    난방_MAX_연료방식 = dr.사용연료
                End If



                Select Case dr.열생산기기방식
                    Case "히트펌프"

                        If dr.사용연료 = "전기" Then
                            난방_SUM_전기_기기용량 += 난방기기용량합
                        End If

                        If 난방기기용량합 > 난방_용량가중효율_MAX_기기용량 Then
                            난방_용량가중효율_MAX_기기용량 = 난방기기용량합
                            난방_용량가중COP = dr.정격보일러COP
                        End If
                    Case "지역난방"
                        If 난방기기용량합 > 난방_용량가중효율_MAX_기기용량 Then
                            난방_용량가중효율_MAX_기기용량 = 난방기기용량합
                            난방_용량가중효율 = dr.정격보일러효율
                        End If
                    Case "전기보일러"

                        If dr.사용연료 = "전기" Then
                            난방_SUM_전기_기기용량 += 난방기기용량합
                        End If

                        If 난방기기용량합 > 난방_용량가중효율_MAX_기기용량 Then
                            난방_용량가중효율_MAX_기기용량 = 난방기기용량합
                            난방_용량가중효율 = dr.정격보일러효율
                        End If
                    Case "보일러"
                        If 난방기기용량합 > 난방_용량가중효율_MAX_기기용량 Then
                            난방_용량가중효율_MAX_기기용량 = 난방기기용량합
                            난방_용량가중COP = dr.정격보일러COP
                        End If
                End Select

            ElseIf dr.난방급탕구분 = "급탕용" Then

                급탕_SUM_기기용량합 += TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
                급탕_SUM_펌프동력 += TOSG(T, dr.펌프동력)
                급탕기기용량합 = TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
                If 급탕기기용량합 > 급탕_MAX_기기용량합 Then
                    급탕_MAX_기기용량합 = 급탕기기용량합
                    급탕_MAX_기기명칭 = dr.설명
                    급탕_MAX_기기방식 = dr.열생산기기방식
                    급탕_MAX_연료방식 = dr.사용연료
                End If

                Select Case dr.열생산기기방식
                    Case "히트펌프"

                        If dr.사용연료 = "전기" Then
                            급탕_SUM_전기_기기용량 += 급탕기기용량합
                        End If

                        If 급탕기기용량합 > 급탕_용량가중효율_MAX_기기용량 Then
                            급탕_용량가중효율_MAX_기기용량 = 급탕기기용량합
                            급탕_용량가중COP = dr.정격보일러COP
                        End If
                    Case "지역난방"
                        If 급탕기기용량합 > 급탕_용량가중효율_MAX_기기용량 Then
                            급탕_용량가중효율_MAX_기기용량 = 급탕기기용량합
                            급탕_용량가중효율 = dr.정격보일러효율
                        End If
                    Case "전기보일러"

                        If dr.사용연료 = "전기" Then
                            급탕_SUM_전기_기기용량 += 급탕기기용량합
                        End If

                        If 급탕기기용량합 > 급탕_용량가중효율_MAX_기기용량 Then
                            급탕_용량가중효율_MAX_기기용량 = 급탕기기용량합
                            급탕_용량가중효율 = dr.정격보일러효율
                        End If
                    Case "보일러"
                        If 급탕기기용량합 > 급탕_용량가중효율_MAX_기기용량 Then
                            급탕_용량가중효율_MAX_기기용량 = 급탕기기용량합
                            급탕_용량가중효율 = dr.정격보일러효율
                        End If
                End Select

            ElseIf dr.난방급탕구분 = "난방급탕용" Then
                난방_SUM_기기용량합 += TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
                난방_SUM_펌프동력 += TOSG(T, dr.펌프동력)
                난방기기용량합 = TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)

                급탕_SUM_기기용량합 += TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
                급탕_SUM_펌프동력 += TOSG(T, dr.펌프동력)
                급탕기기용량합 = TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)

                If 난방기기용량합 > 난방_MAX_기기용량합 Then
                    난방_MAX_기기용량합 = 난방기기용량합
                    난방_MAX_기기명칭 = dr.설명
                    난방_MAX_기기방식 = dr.열생산기기방식
                    난방_MAX_연료방식 = dr.사용연료


                End If

                If 급탕기기용량합 > 급탕_MAX_기기용량합 Then
                    급탕_MAX_기기용량합 = 급탕기기용량합
                    급탕_MAX_기기명칭 = dr.설명
                    급탕_MAX_기기방식 = dr.열생산기기방식
                    급탕_MAX_연료방식 = dr.사용연료
                End If

                Select Case dr.열생산기기방식
                    Case "히트펌프"

                        If dr.사용연료 = "전기" Then
                            급탕_SUM_전기_기기용량 += 급탕기기용량합
                            난방_SUM_전기_기기용량 += 난방기기용량합
                        End If

                        If 난방기기용량합 > 난방_용량가중효율_MAX_기기용량 Then
                            난방_용량가중효율_MAX_기기용량 = 난방기기용량합
                            난방_용량가중COP = dr.정격보일러COP
                        End If
                        If 급탕기기용량합 > 급탕_용량가중효율_MAX_기기용량 Then
                            급탕_용량가중효율_MAX_기기용량 = 급탕기기용량합
                            급탕_용량가중COP = dr.정격보일러COP
                        End If
                    Case "지역난방"
                        If 난방기기용량합 > 난방_용량가중효율_MAX_기기용량 Then
                            난방_용량가중효율_MAX_기기용량 = 난방기기용량합
                            난방_용량가중효율 = dr.정격보일러효율
                        End If
                        If 급탕기기용량합 > 급탕_용량가중효율_MAX_기기용량 Then
                            급탕_용량가중효율_MAX_기기용량 = 급탕기기용량합
                            급탕_용량가중효율 = dr.정격보일러효율
                        End If

                    Case "전기보일러"

                        If dr.사용연료 = "전기" Then
                            급탕_SUM_전기_기기용량 += 급탕기기용량합
                            난방_SUM_전기_기기용량 += 난방기기용량합
                        End If

                        If 난방기기용량합 > 난방_용량가중효율_MAX_기기용량 Then
                            난방_용량가중효율_MAX_기기용량 = 난방기기용량합
                            난방_용량가중효율 = dr.정격보일러효율
                        End If
                        If 급탕기기용량합 > 급탕_용량가중효율_MAX_기기용량 Then
                            급탕_용량가중효율_MAX_기기용량 = 급탕기기용량합
                            급탕_용량가중효율 = dr.정격보일러효율
                        End If

                    Case "보일러"

                        If 난방기기용량합 > 난방_용량가중효율_MAX_기기용량 Then
                            난방_용량가중효율_MAX_기기용량 = 난방기기용량합
                            난방_용량가중효율 = dr.정격보일러효율
                        End If
                        If 급탕기기용량합 > 급탕_용량가중효율_MAX_기기용량 Then
                            급탕_용량가중효율_MAX_기기용량 = 급탕기기용량합
                            급탕_용량가중효율 = dr.정격보일러효율
                        End If

                End Select

            End If
        Next

        P(82) = 난방_MAX_기기명칭
        P(15) = 난방_SUM_기기용량합.ToString("N2") + "(㎾)"
        If 난방_MAX_기기방식 = "히트펌프" Then
            '//동일연룍방식 찾기
            Dim SUM_가중_분자 As Double = 0
            Dim SUM_가중_분모 As Double = 0
            For Each dr As DS.tbl_nanbangkikiRow In DSET1.tbl_nanbangkiki.Select("code <> '0' and 열생산기기방식='" + 난방_MAX_기기방식 + "' and 사용연료='" + 난방_MAX_연료방식 + "'")
                SUM_가중_분자 += dr.정격보일러COP * TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
                SUM_가중_분모 += TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
            Next

            If SUM_가중_분모 <= 0 Then
                P(16) = "(COP)"
            Else
                P(16) = (SUM_가중_분자 / SUM_가중_분모).ToString("N2") + "(COP)" ' 난방_용량가중COP.ToString("N2") + "(COP)"
            End If

        Else
            '//동일연룍방식 찾기
            Dim SUM_가중_분자 As Double = 0
            Dim SUM_가중_분모 As Double = 0
            For Each dr As DS.tbl_nanbangkikiRow In DSET1.tbl_nanbangkiki.Select("code <> '0' and 열생산기기방식='" + 난방_MAX_기기방식 + "' and 사용연료='" + 난방_MAX_연료방식 + "'")
                SUM_가중_분자 += dr.정격보일러효율 * TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
                SUM_가중_분모 += TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
            Next
            If SUM_가중_분모 <= 0 Then
                P(16) = "(%)"
            Else
                P(16) = (SUM_가중_분자 / SUM_가중_분모).ToString("N2") + "(%)"   'P(16) = 난방_용량가중효율.ToString("N2") + "(%)"
            End If
        End If

        'P(17) = "" '//??
        P(17) = 난방_SUM_펌프동력.ToString("N2") + "(㎾)"
        P(18) = ((난방_SUM_전기_기기용량 / 난방_SUM_기기용량합) * 100).ToString("N2") + "(%)"

        P(83) = 급탕_MAX_기기명칭
        P(20) = 급탕_SUM_기기용량합.ToString("N2") + "(㎾)"
        If 급탕_MAX_기기방식 = "히트펌프" Then
            '//동일연룍방식 찾기
            Dim SUM_가중_분자 As Double = 0
            Dim SUM_가중_분모 As Double = 0
            For Each dr As DS.tbl_nanbangkikiRow In DSET1.tbl_nanbangkiki.Select("code <> '0' and 열생산기기방식='" + 급탕_MAX_기기방식 + "' and 사용연료='" + 급탕_MAX_연료방식 + "'")
                SUM_가중_분자 += dr.정격보일러COP * TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
                SUM_가중_분모 += TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
            Next

            If SUM_가중_분모 <= 0 Then
                P(22) = "(COP)"
            Else
                P(22) = (SUM_가중_분자 / SUM_가중_분모).ToString("N2") + "(COP)"   'P(22) = 급탕_용량가중COP.ToString("N2") + "(COP)"
            End If


        Else
            '//동일연룍방식 찾기
            '//동일연룍방식 찾기
            Dim SUM_가중_분자 As Double = 0
            Dim SUM_가중_분모 As Double = 0
            For Each dr As DS.tbl_nanbangkikiRow In DSET1.tbl_nanbangkiki.Select("code <> '0' and 열생산기기방식='" + 급탕_MAX_기기방식 + "' and 사용연료='" + 급탕_MAX_연료방식 + "'")
                SUM_가중_분자 += dr.정격보일러효율 * TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
                SUM_가중_분모 += TOSG(T, dr.보일러정격출력) * TOSG(T, dr.보일러대수)
            Next

            If SUM_가중_분모 <= 0 Then
                P(22) = "(%)"
            Else
                P(22) = (SUM_가중_분자 / SUM_가중_분모).ToString("N2") + "(%)"   'P(22) = 급탕_용량가중효율.ToString("N2") + "(%)""
            End If



        End If
        P(23) = "" '//??
        P(24) = 급탕_SUM_펌프동력.ToString("N2") + "(㎾)"
        P(25) = ((급탕_SUM_전기_기기용량 / 급탕_SUM_기기용량합) * 100).ToString("N2") + "(%)"


        '//냉방설비
        Dim 냉방_MAX_기기용량합방식 As String = ""
        Dim 냉방_MAX_기기용량합 As Single = 0
        Dim 냉방_MAX_연료방식 As String = 0
        Dim 냉방_SUM_기기용량합 As Single = 0
        Dim 냉방_용량가중_열성능비 As String = ""
        Dim 냉방_SUM_냉수펌프 As Single = 0
        Dim 냉방_SUM_냉각수펌프 As Single = 0
        Dim 냉방_SUM_압축식 As Single = 0
        Dim 냉방_SUM_냉동기방식 As Single = 0

        For Each dr As DS.tbl_nangbangkikiRow In DSET1.tbl_nangbangkiki.Select("code <> '0'")
            Dim 기기용량합 As Single = TOSG(dr.냉동기용량) * TOSG(dr.대수)
            If 기기용량합 > 냉방_MAX_기기용량합 Then
                냉방_MAX_기기용량합 = 기기용량합
                냉방_MAX_기기용량합방식 = dr.냉동기방식
                냉방_MAX_연료방식 = dr.사용연료
            End If
            냉방_SUM_기기용량합 += 기기용량합 'TOSG(T, dr.냉동기용량)
            냉방_용량가중_열성능비 = dr.열성능비 '//오류있음
            냉방_SUM_냉수펌프 += TOSG(T, dr.냉수펌프동력)
            냉방_SUM_냉각수펌프 += TOSG(T, dr.냉각수펌프동력)
            If dr.냉동기방식 = "압축식" Then
                냉방_SUM_압축식 += 기기용량합
            End If
            냉방_SUM_냉동기방식 += 기기용량합
        Next
        P(84) = 냉방_MAX_기기용량합방식
        P(26) = 냉방_SUM_기기용량합.ToString("N2") + "(㎾)"

        Dim 냉방_용량가중_분자 As Double = 0
        Dim 냉방_용량가중_분모 As Double = 0
        For Each dr As DS.tbl_nangbangkikiRow In DSET1.tbl_nangbangkiki.Select("code <> '0' and 냉동기방식='" + 냉방_MAX_기기용량합방식 + "' and 사용연료='" + 냉방_MAX_연료방식 + "'")
            냉방_용량가중_분자 += TOSG(dr.열성능비) * TOSG(dr.냉동기용량) * TOSG(dr.대수)
            냉방_용량가중_분모 += TOSG(dr.냉동기용량) * TOSG(dr.대수)
        Next
        If (냉방_용량가중_분자 < 0) Then
            P(27) = "(COP)"
        Else
            P(27) = (냉방_용량가중_분자 / 냉방_용량가중_분모).ToString("N2") + "(COP)" ' 냉방_용량가중_열성능비 + "(COP)"
        End If


        P(28) = "" '//??
        P(29) = 냉방_SUM_냉수펌프.ToString("N2") + "(㎾)"
        P(30) = 냉방_SUM_냉각수펌프.ToString("N2") + "(㎾)"
        P(31) = ((냉방_SUM_압축식 / 냉방_SUM_냉동기방식) * 100).ToString("N2") + "(%)"

        '//공조설비
        Dim 공조_MAX_급기풍량 As Single = 0
        Dim 공조_MAX_급기풍량방식 As String = ""
        Dim 공조_SUM_급기풍량 As Single = 0
        Dim 공조_SUM_배기풍량 As Single = 0
        Dim 공조_용량가중효율_급기 As Single = 0
        Dim 공조_용량가중효율_배기 As Single = 0
        Dim 공조_SUM_급기팬동력 As Single = 0
        Dim 공조_SUM_배기팬동력 As Single = 0
        Dim 공조_열회수율_난방 As Single = 0
        Dim 공조_열회수율_냉방 As Single = 0

        '급기 : 급기팬동력이 0 이 아닐때에 (급기풍량*급기정압/9.8) / (급기팬동력*102*3600)의 효율을 산출하여 급기풍량가중평균값
        '배기 : 배기팬동력이 0 이 아닐때에 (배기풍량*배기정압/9.8) / (배기팬동력*102*3600)의 효율을 산출하여 배기풍량가중평균값"

        Dim K1 As Single = 0
        Dim K2 As Single = 0
        Dim N1 As Single = 0
        Dim N2 As Single = 0
        Dim Sum_급기풍량 As Single = 0
        Dim Sum_배기풍량 As Single = 0
        Dim Sum_난방회수율 As Single = 0
        Dim Sum_냉방회수율 As Single = 0
        For Each dr As DS.tbl_kongjoRow In DSET1.tbl_kongjo.Select("code <> '0'")
            Dim 급기풍량 As Single = TOSG(T, dr.급기풍량) * TOSG(T, dr.대수)
            Dim 급기정압 As Single = TOSG(T, dr.총압력손실급기팬)
            Dim 급기팬동력 As Single = TOSG(T, dr.급기팬동력) * TOSG(T, dr.대수)

            Dim 배기풍량 As Single = TOSG(T, dr.배기풍량) * TOSG(T, dr.대수)
            Dim 배기정압 As Single = TOSG(T, dr.총압력손실배기팬)
            Dim 배기팬동력 As Single = TOSG(T, dr.배기팬동력) * TOSG(T, dr.대수)

            Dim 난방회수율 As Single = TOSG(T, dr.열회수율)
            Dim 냉방회수율 As Single = TOSG(T, dr.열회수율_냉방)

            '//열교환기유형이 없는경우 회수율값 초기화
            If dr.열교환기유형 = "0" OrElse dr.열교환기유형 = "열회수불가" Then
                난방회수율 = 0
                냉방회수율 = 0
            End If

            N1 += 난방회수율 * 급기풍량
            N2 += 냉방회수율 * 급기풍량

            If 급기팬동력 > 0 Then
                K1 += ((급기풍량 * 급기정압 / 9.8) / (급기팬동력 * 102 * 3600)) * 급기풍량
            End If

            If 배기팬동력 > 0 Then
                K2 += ((배기풍량 * 배기정압 / 9.8) / (배기팬동력 * 102 * 3600)) * 배기풍량
            End If

            If 급기풍량 > 공조_MAX_급기풍량 Then
                공조_MAX_급기풍량 = 급기풍량
                공조_MAX_급기풍량방식 = dr.공조방식
            End If
            공조_SUM_급기풍량 += TOSG(T, dr.급기풍량) * TOSG(T, dr.대수)
            공조_SUM_배기풍량 += TOSG(T, dr.배기풍량) * TOSG(T, dr.대수)
            공조_SUM_급기팬동력 += TOSG(T, dr.급기팬동력) * TOSG(T, dr.대수)
            공조_SUM_배기팬동력 += TOSG(T, dr.배기팬동력) * TOSG(T, dr.대수)

            If dr.열교환기유형 <> "0" OrElse dr.열교환기유형 <> "열회수불가" Then
                Sum_급기풍량 += 급기풍량
                Sum_배기풍량 += 배기풍량

                Sum_난방회수율 += 난방회수율
                Sum_냉방회수율 += 냉방회수율
            End If



        Next

        If Sum_급기풍량 > 0 Then 공조_용량가중효율_급기 = ((K1 / Sum_급기풍량) * 100).ToString("N2")
        If Sum_배기풍량 > 0 Then 공조_용량가중효율_배기 = ((K2 / Sum_배기풍량) * 100).ToString("N2")

        If Sum_난방회수율 > 0 Then 공조_열회수율_난방 = (N1 / Sum_급기풍량).ToString("N2") '//170827 *100제거
        If Sum_냉방회수율 > 0 Then 공조_열회수율_냉방 = (N2 / Sum_급기풍량).ToString("N2")

        P(85) = 공조_MAX_급기풍량방식

        P(32) = "급기:" & 공조_SUM_급기풍량.ToString("N0") & "(CMH)" & vbCrLf & _
                "배기:" & 공조_SUM_배기풍량.ToString("N0") & "(CMH)"
        P(33) = ""

        P(34) = "급기:" & 공조_용량가중효율_급기.ToString("N2") & "(%)" & vbCrLf & _
                "배기:" & 공조_용량가중효율_배기.ToString("N2") & "(%)"
        P(35) = ""

        P(36) = "급기:" & 공조_SUM_급기팬동력.ToString("N2") & "(㎾)" & vbCrLf & _
                "배기:" & 공조_SUM_배기팬동력.ToString("N2") & "(㎾)"
        P(37) = ""

        'P(36) = 공조_SUM_급기팬동력.ToString("N2")
        'P(37) = 공조_SUM_배기팬동력.ToString("N2")

        P(38) = "난방:" & 공조_열회수율_난방.ToString("N2") & "(%)" & vbCrLf & _
                "냉방:" & 공조_열회수율_냉방.ToString("N2") & "(%)"
        P(39) = ""

        '//조명기기
        Dim 조명_MAX_조명기기종류 As String = ""
        Dim 조명_MAX_조명전력대수합 As Single = 0
        Dim 조명_SUM_전력대수 As Single = 0
        Dim 조명_SUM_LED전력대수 As Single = 0
        Dim 조명_SUM_전력 As Single = 0
        Dim 조명_SUM_대수 As Single = 0
        Dim 조명_SUM_LED대수 As Single = 0
        Dim 조명_SUM_사용면적 As Single = 0

        For Each dr As DS.tbl_typeRow In DSET1.tbl_type.Select("code<>'0'", "code")
            조명_SUM_사용면적 += TOSG(T, dr.면적)
        Next

        For Each dr As DS.tbl_lightRow In DSET1.tbl_light.Select("code <> '0'")
            조명_SUM_전력 += TOSG(T, dr.조명전력)
            Dim 조명전력대수합 As Single = TOSG(T, dr.조명전력) * TOSG(T, dr.대수)

            조명_SUM_전력대수 += 조명전력대수합

            If dr.조명종류 = "LED등" Then
                조명_SUM_LED전력대수 += 조명전력대수합
                조명_SUM_LED대수 += TOSG(T, dr.대수)
            End If

            조명_SUM_대수 += TOSG(T, dr.대수)
            If 조명전력대수합 > 조명_MAX_조명전력대수합 Then
                조명_MAX_조명전력대수합 = 조명전력대수합
                조명_MAX_조명기기종류 = dr.조명종류
            End If

            ' 조명_SUM_사용면적 += TOSG(T, dr.조명면적)
        Next
        P(40) = 조명_MAX_조명기기종류
        P(41) = (조명_SUM_LED전력대수 / 1000).ToString("N2") + "(㎾)"
        P(42) = (조명_SUM_전력대수 / 1000).ToString("N2") + "(㎾)"
        P(43) = 조명_SUM_사용면적.ToString("N2") + "(㎡)"
        P(44) = (조명_SUM_전력대수 / 조명_SUM_사용면적).ToString("N2") + "(W/㎡)"

        '//신재생
        Dim 태양열_MAX_면적합_집열기유형 As String = ""
        Dim 태양열_MAX_면적합_집열판기울기 As String = ""
        Dim 태양열_MAX_면적합_방위 As String = ""
        Dim 태양열_MAX_면적합_집열효율 As String = ""
        Dim 태양열_MAX_면적합 As Single = 0
        Dim 태양열_SUM_면적 As Single = 0

        Dim Grp_E As New Dictionary(Of String, Single)
        '//group sum
        For Each dr As DS.tbl_new_energyRow In DSET1.tbl_new_energy.Select("code <> '0'")
            If Grp_E.ContainsKey(dr.집열기유형) Then
                Dim oldValue As Single = Grp_E.Item(dr.집열기유형)
                Grp_E.Item(dr.집열기유형) = oldValue + TOSG(T, dr.집열판면적)
            Else
                Grp_E.Add(dr.집열기유형, TOSG(T, dr.집열판면적))
            End If
        Next


        For Each dr As System.Collections.Generic.KeyValuePair(Of String, Single) In Grp_E
            태양열_SUM_면적 += TOSG(T, dr.Value)
            If dr.Value > 태양열_MAX_면적합 Then
                태양열_MAX_면적합 = dr.Value
                태양열_MAX_면적합_집열기유형 = dr.Key
            End If
        Next

        If Not String.IsNullOrEmpty(태양열_MAX_면적합_집열기유형) Then
            Dim dr As DS.tbl_new_energyRow = DSET1.tbl_new_energy.Select("집열기유형 = '" + 태양열_MAX_면적합_집열기유형 + "'")(0)
            태양열_MAX_면적합_집열판기울기 = "45도" ' dr.집열판기울기
            태양열_MAX_면적합_방위 = dr.집열판방위
            태양열_MAX_면적합_집열효율 = dr.집열효율
        End If

        If Not String.IsNullOrEmpty(태양열_MAX_면적합_집열기유형) Then
            P(45) = 태양열_MAX_면적합_집열기유형
            P(46) = 태양열_SUM_면적.ToString("N2") + "(㎡)"
            P(47) = 태양열_MAX_면적합_집열판기울기
            P(48) = 태양열_MAX_면적합_방위
            If (태양열_MAX_면적합_집열기유형 = "성능치입력") Then P(49) = 태양열_MAX_면적합_집열효율 + "(%)"
        End If


        Dim 태양광_MAX_면적합_모듈종류 As String = ""
        Dim 태양광_MAX_면적합_모듈기울기 As String = ""
        Dim 태양광_MAX_면적합_모듈방위 As String = ""
        Dim 태양광_MAX_면적합_모듈효율 As String = ""
        Dim 태양광_MAX_면적합 As Single = 0
        Dim 태양광_SUM_면적 As Single = 0

        '//group sum
        Dim Grp_L As New Dictionary(Of String, Single)
        For Each dr As DS.tbl_new_lightRow In DSET1.tbl_new_light.Select("code <> '0'")
            If Grp_L.ContainsKey(dr.태양광모듈종류) Then
                Dim oldValue As Single = Grp_L.Item(dr.태양광모듈종류)
                Grp_L.Item(dr.태양광모듈종류) = oldValue + TOSG(T, dr.태양광모듈면적)
            Else
                Grp_L.Add(dr.태양광모듈종류, TOSG(T, dr.태양광모듈면적))
            End If
        Next

        For Each dr As System.Collections.Generic.KeyValuePair(Of String, Single) In Grp_L
            태양광_SUM_면적 += TOSG(T, dr.Value)
            If TOSG(T, dr.Value) > 태양광_MAX_면적합 Then
                태양광_MAX_면적합 = TOSG(T, dr.Value)
                태양광_MAX_면적합_모듈종류 = dr.Key

            End If
        Next

        If Not String.IsNullOrEmpty(태양광_MAX_면적합_모듈종류) Then
            Dim dr As DS.tbl_new_lightRow = DSET1.tbl_new_light.Select("태양광모듈종류 = '" + 태양광_MAX_면적합_모듈종류 + "'")(0)
            태양광_MAX_면적합_모듈기울기 = dr.태양광모듈기울기
            태양광_MAX_면적합_모듈방위 = dr.태양광모듈방위
            태양광_MAX_면적합_모듈효율 = dr.태양광모듈효율
        End If


        If Not String.IsNullOrEmpty(태양광_MAX_면적합_모듈종류) Then
            P(50) = 태양광_MAX_면적합_모듈종류
            P(51) = 태양광_SUM_면적.ToString("N2") + "(㎡)"
            P(52) = 태양광_MAX_면적합_모듈기울기
            P(53) = 태양광_MAX_면적합_모듈방위
            If (태양광_MAX_면적합_모듈종류 = "성능치입력") Then P(54) = (태양광_MAX_면적합_모듈효율) + "(%)"
        End If


        Dim 지열_SUM_가스히트펌프 As String = ""
        Dim 지열_SUM_전기히트펌프 As String = ""

        Dim 지열_MAX_종류 As String = ""
        Dim 지열_난방용량 As Single = 0
        Dim 지열_난방효율 As Single = 0 '//오류
        Dim 지열_냉방용량 As Single = 0
        Dim 지열_냉방효율 As Single = 0 '//오류
        Dim 지열_급탕용량 As Single = 0
        Dim 지열_급탕효율 As Single = 0 '//오류
        Dim 지열_순환펌프동력 As Single = 0
        Dim 지열_SUM_지열히트펌프용량 As Single = 0

        If DSET1.tbl_new_ground.Select("code <> '0'").Length > 0 Then
            For Each dr As DS.tbl_new_groundRow In DSET1.tbl_new_ground.Select("code <> '0'")
                If dr.가동연료 = "난방유" OrElse dr.가동연료 = "천연가스" OrElse dr.가동연료 = "액화가스" Then
                    지열_SUM_가스히트펌프 += dr.지열히트펌프용량
                Else
                    지열_SUM_전기히트펌프 += dr.지열히트펌프용량
                End If
            Next

            If 지열_SUM_가스히트펌프 > 지열_SUM_전기히트펌프 Then
                지열_MAX_종류 = "가스히트펌프"
            ElseIf 지열_SUM_가스히트펌프 = 지열_SUM_전기히트펌프 Then
                Dim dr As DS.tbl_new_groundRow = DSET1.tbl_new_ground.Select("code <> '0'", "지열히트펌프용량 desc")(0)
                If dr.가동연료 = "전기" Then
                    지열_MAX_종류 = "전기히트펌프"
                Else
                    지열_MAX_종류 = "가스히트펌프"
                End If
            Else
                지열_MAX_종류 = "전기히트펌프"
            End If

            For Each dr As DS.tbl_new_groundRow In DSET1.tbl_new_ground.Select("code <> '0'")
                지열_SUM_지열히트펌프용량 += TOSG(T, dr.지열히트펌프용량)

                If dr.지열냉난방구분 = "난방용" Then
                    지열_난방용량 += TOSG(T, dr.지열히트펌프용량)
                    지열_난방효율 += TOSG(T, dr.지열히트펌프용량) * TOSG(T, dr.열성능비난방)
                End If
                If dr.지열냉난방구분 = "급탕용" Then
                    지열_급탕용량 += TOSG(T, dr.지열히트펌프용량)
                    지열_급탕효율 += TOSG(T, dr.지열히트펌프용량) * TOSG(T, dr.열성능비난방)
                End If
                If dr.지열냉난방구분 = "난방급탕용" Then
                    지열_난방용량 += TOSG(T, dr.지열히트펌프용량)
                    지열_급탕용량 += TOSG(T, dr.지열히트펌프용량)

                    지열_난방효율 += TOSG(T, dr.지열히트펌프용량) * TOSG(T, dr.열성능비난방)
                    지열_급탕효율 += TOSG(T, dr.지열히트펌프용량) * TOSG(T, dr.열성능비난방)
                End If
                If dr.지열냉난방구분 = "냉방용" Then
                    지열_냉방용량 += TOSG(T, dr.지열히트펌프용량)
                    지열_냉방효율 += TOSG(T, dr.지열히트펌프용량) * TOSG(T, dr.열성능비냉방)
                End If
                지열_순환펌프동력 += TOSG(T, dr.펌프용량1차)
            Next
        End If


        If Not String.IsNullOrEmpty(지열_MAX_종류) Then
            P(55) = 지열_MAX_종류

            If (지열_난방용량 > 0) Then
                P(56) = 지열_난방용량.ToString("N2") + "(kW)" + vbCrLf + _
                          (지열_난방효율 / 지열_SUM_지열히트펌프용량).ToString("N2") + "(COP)"
            End If

            If (지열_냉방용량 > 0) Then
                P(57) = 지열_냉방용량.ToString("N2") + "(kW)" + vbCrLf + _
                (지열_냉방효율 / 지열_SUM_지열히트펌프용량).ToString("N2") + "(COP)"
            End If

            If (지열_급탕용량 > 0) Then
                P(58) = 지열_급탕용량.ToString("N2") + "(kW)" + vbCrLf + _
                (지열_급탕효율 / 지열_SUM_지열히트펌프용량).ToString("N2") + "(COP)"
            End If

            If (지열_순환펌프동력 > 0) Then
                P(59) = 지열_순환펌프동력.ToString("N0") + "(W)"
            End If

        End If


        '//단위면적당 요구량, 소요량, 1차에너지소요량
        '//난방,급탕,냉방,조명,환기,합계
        '//65,66,67
        '//68,69,70

        IDX = 60

        Dim r신재생에너지 As Decimal
        Dim r난방에너지 As Decimal
        Dim r냉방에너지 As Decimal
        Dim r급탕에너지 As Decimal
        Dim r조명에너지 As Decimal
        Dim r환기에너지 As Decimal
        Dim r합계 As Decimal


        Dim Dr2 As DSR.Graph_ReqUseRow
        For Gubun As Short = 0 To 2
            Select Case Gubun

                Case 2  '//에너지요구량

                    r신재생에너지 = 0
                    r난방에너지 = Result1o.E요구량(0).난방면적 * addmulti
                    r급탕에너지 = Result1o.E요구량(0).급탕면적 * addmulti
                    r냉방에너지 = Result1o.E요구량(0).냉방면적 * addmulti
                    r조명에너지 = Result1o.E요구량(0).조명면적 * addmulti
                    r환기에너지 = 0 * addmulti
                    r합계 = r난방에너지 + r냉방에너지 + r급탕에너지 + r조명에너지



                    If r난방에너지 = 0 Then
                        P(64) = ""
                    Else
                        P(64) = r난방에너지.ToString("N1")
                    End If

                    If r냉방에너지 = 0 Then
                        P(65) = ""
                    Else
                        P(65) = r냉방에너지.ToString("N1")
                    End If

                    If r급탕에너지 = 0 Then
                        P(66) = ""
                    Else
                        P(66) = r급탕에너지.ToString("N1")
                    End If


                    If r조명에너지 = 0 Then
                        P(67) = ""
                    Else
                        P(67) = r조명에너지.ToString("N1")
                    End If

                    If r환기에너지 = 0 Then
                        P(68) = ""
                    Else
                        P(68) = r환기에너지.ToString("N1")
                    End If


                    P(69) = r합계.ToString("N1")

                Case 1  '//에너지소요량

                    Dim Sum As Decimal = Result1o.생산E(0).태양광전력생산량 / (Result1o.일차E소요량(0).난방전력 + Result1o.일차E소요량(0).냉방전력 + Result1o.일차E소요량(0).급탕전력 + Result1o.일차E소요량(0).조명전력 + Result1o.일차E소요량(0).환기전력)
                    Dim 난방 As Decimal = Sum * Result1o.일차E소요량(0).난방전력  '//아마게산이안도잇으니 여기값들이 0이잇을거에요.
                    Dim 냉방 As Decimal = Sum * Result1o.일차E소요량(0).냉방전력
                    Dim 조명 As Decimal = Sum * Result1o.일차E소요량(0).조명전력
                    Dim 급탕 As Decimal = Sum * Result1o.일차E소요량(0).급탕전력
                    Dim 환기 As Decimal = Sum * Result1o.일차E소요량(0).환기전력
                    Dim 난방면적 As Decimal = 0
                    Dim 냉방면적 As Decimal = 0
                    Dim 조명면적 As Decimal = 0
                    Dim 급탕면적 As Decimal = 0
                    Dim 환기면적 As Decimal = 0
                    If Result1o.사용면적.H <> 0 Then
                        난방면적 = TOSG(T, IIf(난방 = 0, 0, 난방 / Result1o.사용면적.H))
                    End If
                    If Result1o.사용면적.C <> 0 Then
                        냉방면적 = TOSG(T, IIf(냉방 = 0, 0, 냉방 / Result1o.사용면적.C))
                    End If
                    If Result1o.사용면적.L <> 0 Then
                        조명면적 = TOSG(T, IIf(조명 = 0, 0, 조명 / Result1o.사용면적.L))
                    End If
                    If Result1o.사용면적.W <> 0 Then
                        급탕면적 = TOSG(T, IIf(급탕 = 0, 0, 급탕 / Result1o.사용면적.W))
                    End If
                    If Result1o.사용면적.V <> 0 Then
                        환기면적 = TOSG(T, IIf(환기 = 0, 0, 환기 / Result1o.사용면적.V))
                    End If

                    Dim 면적 As Decimal = 난방면적 + 냉방면적 + 조명면적 + 급탕면적 + 환기면적

                    r신재생에너지 = -1 * (Result1o.생산E(0).면적당생산량태양열 + Result1o.생산E(0).신재생면적당열생산량 + Result1o.생산E(0).면적당생산량지열) - 면적

                    r난방에너지 = Result1o.E소요량(0).난방면적 * addmulti
                    r냉방에너지 = Result1o.E소요량(0).냉방면적 * addmulti
                    r급탕에너지 = Result1o.E소요량(0).급탕면적 * addmulti
                    r조명에너지 = Result1o.E소요량(0).조명면적 * addmulti
                    r환기에너지 = Result1o.E소요량(0).환기면적 * addmulti
                    r합계 = r난방에너지 + r냉방에너지 + r급탕에너지 + r조명에너지 + r환기에너지

                    If r신재생에너지 = 0 Then
                        P(91) = ""
                    Else
                        P(91) = (r신재생에너지 * -1).ToString("N1")
                    End If

                    If r난방에너지 = 0 Then
                        P(70) = ""
                    Else
                        P(70) = r난방에너지.ToString("N1")
                    End If

                    If r냉방에너지 = 0 Then
                        P(71) = ""
                    Else
                        P(71) = r냉방에너지.ToString("N1")
                    End If

                    If r급탕에너지 = 0 Then
                        P(72) = ""
                    Else
                        P(72) = r급탕에너지.ToString("N1")
                    End If

                    If r조명에너지 = 0 Then
                        P(73) = ""
                    Else
                        P(73) = r조명에너지.ToString("N1")
                    End If

                    If r환기에너지 = 0 Then
                        P(74) = ""
                    Else
                        P(74) = r환기에너지.ToString("N1")
                    End If

                    P(75) = r합계.ToString("N1")

                Case 0  '//1차에너지소요량

                    If Pub.Program = EProgram.총량평가 Then

                        Dim Sum As Decimal = Result1o.생산E(0).태양광전력생산량 / (Result1o.일차E소요량(0).난방전력 + Result1o.일차E소요량(0).냉방전력 + Result1o.일차E소요량(0).급탕전력 + Result1o.일차E소요량(0).조명전력 + Result1o.일차E소요량(0).환기전력)
                        Dim 난방 As Decimal = Sum * Result1o.일차E소요량(0).난방전력  '//아마게산이안도잇으니 여기값들이 0이잇을거에요.
                        Dim 냉방 As Decimal = Sum * Result1o.일차E소요량(0).냉방전력
                        Dim 조명 As Decimal = Sum * Result1o.일차E소요량(0).조명전력
                        Dim 급탕 As Decimal = Sum * Result1o.일차E소요량(0).급탕전력
                        Dim 환기 As Decimal = Sum * Result1o.일차E소요량(0).환기전력
                        Dim 난방면적 As Decimal = 0
                        Dim 냉방면적 As Decimal = 0
                        Dim 조명면적 As Decimal = 0
                        Dim 급탕면적 As Decimal = 0
                        Dim 환기면적 As Decimal = 0
                        If Result1o.사용면적.H <> 0 Then
                            난방면적 = TOSG(T, IIf(난방 = 0, 0, 난방 / Result1o.사용면적.H))
                        End If
                        If Result1o.사용면적.C <> 0 Then
                            냉방면적 = TOSG(T, IIf(냉방 = 0, 0, 냉방 / Result1o.사용면적.C))
                        End If
                        If Result1o.사용면적.L <> 0 Then
                            조명면적 = TOSG(T, IIf(조명 = 0, 0, 조명 / Result1o.사용면적.L))
                        End If
                        If Result1o.사용면적.W <> 0 Then
                            급탕면적 = TOSG(T, IIf(급탕 = 0, 0, 급탕 / Result1o.사용면적.W))
                        End If
                        If Result1o.사용면적.V <> 0 Then
                            환기면적 = TOSG(T, IIf(환기 = 0, 0, 환기 / Result1o.사용면적.V))
                        End If

                        Dim 전기 As Decimal = 난방면적 + 냉방면적 + 조명면적 + 급탕면적 + 환기면적

                        r신재생에너지 = -1 * (Result1o.생산E(0).면적당생산량태양열 + Result1o.생산E(0).신재생면적당열생산량 + Result1o.생산E(0).면적당생산량지열 + 전기 * 2.75)

                        If Program = EProgram.총량평가 Then
                            r난방에너지 = Result1o.일차E소요량(0).난방면적 * 1.0 * addmulti '//171021 
                            r냉방에너지 = Result1o.일차E소요량(0).냉방면적 * 1.0 * addmulti '//171021 
                            r급탕에너지 = Result1o.일차E소요량(0).급탕면적 * 1.0 * addmulti '//171021 
                            r조명에너지 = Result1o.일차E소요량(0).조명면적 * 1.0 * addmulti '//171021 
                            r환기에너지 = Result1o.일차E소요량(0).환기면적 * 1.0 * addmulti '//171021 
                        Else
                            r난방에너지 = Result1o.일차E소요량(0).난방면적 * 1.0 '//171021 
                            r냉방에너지 = Result1o.일차E소요량(0).냉방면적 * 1.0 '//171021 
                            r급탕에너지 = Result1o.일차E소요량(0).급탕면적 * 1.0 '//171021 
                            r조명에너지 = Result1o.일차E소요량(0).조명면적 * 1.0 '//171021 
                            r환기에너지 = Result1o.일차E소요량(0).환기면적 * 1.0 '//171021 
                        End If

                        r합계 = r난방에너지 + r냉방에너지 + r급탕에너지 + r조명에너지 + r환기에너지


                        If r난방에너지 = 0 Then
                            P(76) = ""
                        Else
                            P(76) = r난방에너지.ToString("N1")
                        End If

                        If r냉방에너지 = 0 Then
                            P(77) = ""
                        Else
                            P(77) = r냉방에너지.ToString("N1")
                        End If

                        If r급탕에너지 = 0 Then
                            P(78) = ""
                        Else
                            P(78) = r급탕에너지.ToString("N1")
                        End If

                        If r조명에너지 = 0 Then
                            P(79) = ""
                        Else
                            P(79) = r조명에너지.ToString("N1")
                        End If
                        If r환기에너지 = 0 Then
                            P(80) = ""
                        Else
                            P(80) = r환기에너지.ToString("N1")
                        End If
                        If r신재생에너지 = 0 Then
                            P(89) = ""
                        Else
                            P(89) = (r신재생에너지 * -1).ToString("N1")
                        End If

                        P(81) = r합계.ToString("N1")
                    Else

                        '//친환경
                        Dim Sum As Decimal = Result1o.생산E(0).태양광전력생산량 / (Result1o.일차E소요량(0).난방전력 + Result1o.일차E소요량(0).냉방전력 + Result1o.일차E소요량(0).급탕전력 + Result1o.일차E소요량(0).조명전력 + Result1o.일차E소요량(0).환기전력)
                        Dim 난방 As Decimal = Sum * Result1o.일차E소요량(0).난방전력  '//아마게산이안도잇으니 여기값들이 0이잇을거에요.
                        Dim 냉방 As Decimal = Sum * Result1o.일차E소요량(0).냉방전력
                        Dim 조명 As Decimal = Sum * Result1o.일차E소요량(0).조명전력
                        Dim 급탕 As Decimal = Sum * Result1o.일차E소요량(0).급탕전력
                        Dim 환기 As Decimal = Sum * Result1o.일차E소요량(0).환기전력
                        Dim 난방면적 As Decimal = 0
                        Dim 냉방면적 As Decimal = 0
                        Dim 조명면적 As Decimal = 0
                        Dim 급탕면적 As Decimal = 0
                        Dim 환기면적 As Decimal = 0
                        If Result1o.사용면적.H <> 0 Then
                            난방면적 = TOSG(T, IIf(난방 = 0, 0, 난방 / Result1o.사용면적.H))
                        End If
                        If Result1o.사용면적.C <> 0 Then
                            냉방면적 = TOSG(T, IIf(냉방 = 0, 0, 냉방 / Result1o.사용면적.C))
                        End If
                        If Result1o.사용면적.L <> 0 Then
                            조명면적 = TOSG(T, IIf(조명 = 0, 0, 조명 / Result1o.사용면적.L))
                        End If
                        If Result1o.사용면적.W <> 0 Then
                            급탕면적 = TOSG(T, IIf(급탕 = 0, 0, 급탕 / Result1o.사용면적.W))
                        End If
                        If Result1o.사용면적.V <> 0 Then
                            환기면적 = TOSG(T, IIf(환기 = 0, 0, 환기 / Result1o.사용면적.V))
                        End If




                        Dim 전기 As Decimal = 난방면적 + 냉방면적 + 조명면적 + 급탕면적 + 환기면적

                        r신재생에너지 = -1 * (Result1o.생산E(0).면적당생산량태양열 + Result1o.생산E(0).신재생면적당열생산량 + Result1o.생산E(0).면적당생산량지열 + 전기 * 2.75)

                        r난방에너지 = Result1o.일차E소요량(0).난방면적
                        'If (Result1o.사용면적.H_WF = 0) Then
                        '    r난방에너지 = 0
                        'Else
                        '    r난방에너지 = Result1o.일차E소요량(0).난방면적2 * Result1o.사용면적.H / Result1o.사용면적.H_WF
                        'End If

                        r냉방에너지 = Result1o.일차E소요량(0).냉방면적

                        r급탕에너지 = Result1o.일차E소요량(0).급탕면적 '//등급용 170707 2332
                        'If (Result1o.사용면적.W_WF = 0) Then
                        '    r급탕에너지 = 0
                        'Else
                        '    r급탕에너지 = Result1o.일차E소요량(0).급탕면적2 * Result1o.사용면적.W / Result1o.사용면적.W_WF
                        'End If


                        r조명에너지 = Result1o.일차E소요량(0).조명면적
                        r환기에너지 = Result1o.일차E소요량(0).환기면적
                        r합계 = r난방에너지 + r냉방에너지 + r급탕에너지 + r조명에너지 + r환기에너지

                        If r난방에너지 = 0 Then
                            P(76) = ""
                        Else
                            P(76) = r난방에너지.ToString("N1")
                        End If

                        If r냉방에너지 = 0 Then
                            P(77) = ""
                        Else
                            P(77) = r냉방에너지.ToString("N1")
                        End If

                        If r급탕에너지 = 0 Then
                            P(78) = ""
                        Else
                            P(78) = r급탕에너지.ToString("N1")
                        End If


                        If r조명에너지 = 0 Then
                            P(79) = ""
                        Else
                            P(79) = r조명에너지.ToString("N1")
                        End If
                        If r환기에너지 = 0 Then
                            P(80) = ""
                        Else
                            P(80) = r환기에너지.ToString("N1")
                        End If
                        If r신재생에너지 = 0 Then
                            P(89) = ""
                        Else
                            P(89) = (r신재생에너지 * -1).ToString("N1")
                        End If

                        P(81) = r합계.ToString("N1")

                    End If

            End Select
        Next






        '  P(89) = "" '//


        Dim Sum1 As Decimal = Result1o.생산E(0).태양광전력생산량 / (Result1o.일차E소요량(0).난방전력 + Result1o.일차E소요량(0).냉방전력 + Result1o.일차E소요량(0).급탕전력 + Result1o.일차E소요량(0).조명전력 + Result1o.일차E소요량(0).환기전력)
        Dim 난방1 As Decimal = Sum1 * Result1o.일차E소요량(0).난방전력  '//아마게산이안도잇으니 여기값들이 0이잇을거에요.
        Dim 냉방1 As Decimal = Sum1 * Result1o.일차E소요량(0).냉방전력
        Dim 조명1 As Decimal = Sum1 * Result1o.일차E소요량(0).조명전력
        Dim 급탕1 As Decimal = Sum1 * Result1o.일차E소요량(0).급탕전력
        Dim 환기1 As Decimal = Sum1 * Result1o.일차E소요량(0).환기전력

        Dim 난방면적1 As Decimal = 0
        Dim 냉방면적1 As Decimal = 0
        Dim 조명면적1 As Decimal = 0
        Dim 급탕면적1 As Decimal = 0
        Dim 환기면적1 As Decimal = 0
        If Result1o.사용면적.H <> 0 Then
            난방면적1 = TOSG(T, IIf(난방1 = 0, 0, 난방1 / Result1o.사용면적.H))
        End If
        If Result1o.사용면적.C <> 0 Then
            냉방면적1 = TOSG(T, IIf(냉방1 = 0, 0, 냉방1 / Result1o.사용면적.C))
        End If
        If Result1o.사용면적.L <> 0 Then
            조명면적1 = TOSG(T, IIf(조명1 = 0, 0, 조명1 / Result1o.사용면적.L))
        End If
        If Result1o.사용면적.W <> 0 Then
            급탕면적1 = TOSG(T, IIf(급탕1 = 0, 0, 급탕1 / Result1o.사용면적.W))
        End If
        If Result1o.사용면적.V <> 0 Then
            환기면적1 = TOSG(T, IIf(환기1 = 0, 0, 환기1 / Result1o.사용면적.V))
        End If

        Dim 면적1 As Decimal = 난방면적1 + 냉방면적1 + 조명면적1 + 급탕면적1 + 환기면적1

        '//신재생 _소요량
        P(92) = (-1 * (Result1o.생산E(0).면적당생산량태양열 + Result1o.생산E(0).면적당생산량지열) - 면적1).ToString()

        'Console.WriteLine("exp report ==========")
        For i As Integer = 1 To 99
            NewDR("c" + i.ToString("000")) = P(i - 1)
            'Console.WriteLine("P[{0}]={1}", i, P(i - 1))
        Next

        DSETR1.ExtReport.AddExtReportRow(NewDR)
        DSETR1.ExtReport.AcceptChanges()
    End Sub



#Region "미사용메뉴"

    Private Sub 부분부하율()
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        'Me.Toggle_Menu_Color(E_MenuIdx.부분부하율)
        Select Case Prj.UIVersion
            Case "2009123100", StartVersion
                Frm_V20091231_buha.ControlBox = True
                Frm_V20091231_buha.ShowDialog()
                'Show_menu(New Frm_V20091231_buha)

            Case Else
                MsgBox(CLang.미지원UI버젼, MsgBoxStyle.Information, "확인")
        End Select
    End Sub

    Private Sub 기상데이터서버업로드()
        MsgBox("이 기능은 지원되지 않습니다.")
        'If MsgBox("정말로 서버의 데이터를 수정하시겠습니까?" & vbCrLf &
        '          "서버의 기상데이터가 삭제되고 현재데이터가 씌여집니다." & vbCrLf &
        '          "이작업은 되돌릴 수없습니다", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") <> MsgBoxResult.Ok Then Return

        'Dim pass As String = InputBox("암호입력")
        'If pass <> "raytrace" Then Return

        'Dim Cn As New SqlClient.SqlConnection(My.Settings.cs)
        'Cn.Open()
        'Dim CMd As New SqlClient.SqlCommand("delete from tbl_weather", Cn)
        'CMd.ExecuteNonQuery()
        'CMd.CommandText = "delete from weather_cha" : CMd.ExecuteNonQuery()
        'CMd.CommandText = "delete from weather_ilsa" : CMd.ExecuteNonQuery()
        'CMd.CommandText = "delete from weather_temp" : CMd.ExecuteNonQuery()
        'CMd.CommandText = "delete from weather_supdo" : CMd.ExecuteNonQuery()
        'CMd.Dispose()
        'Cn.Close()
        'Cn.Dispose()

        'Dim Taw As New DSTableAdapters.tbl_weatherTableAdapter
        'Dim Ta1 As New DSTableAdapters.weather_chaTableAdapter
        'Dim Ta2 As New DSTableAdapters.weather_ilsaTableAdapter
        'Dim Ta3 As New DSTableAdapters.weather_supdoTableAdapter
        'Dim Ta4 As New DSTableAdapters.weather_tempTableAdapter
        'Dim Rcnt As Integer = 0
        'For Each Dr As DS.tbl_weatherRow In DSET1.tbl_weather.Rows
        '    Rcnt += Taw.Insert(Dr.code, Dr.건물위치, Dr.난방기, Dr.냉방기, Dr.m01, Dr.m02, Dr.m03, Dr.m04, Dr.m05, Dr.m06, Dr.m07, Dr.m08, Dr.m09, Dr.m10, Dr.m11, Dr.m12)
        'Next
        'For Each Dr As DS.weather_chaRow In DSET1.weather_cha.Rows
        '    Rcnt += Ta1.Insert(Dr.pcode, Dr.code, Dr.설명, Dr.m01, Dr.m02, Dr.m03, Dr.m04, Dr.m05, Dr.m06, Dr.m07, Dr.m08, Dr.m09, Dr.m10, Dr.m11, Dr.m12)
        'Next
        'For Each Dr As DS.weather_ilsaRow In DSET1.weather_ilsa.Rows
        '    Rcnt += Ta2.Insert(Dr.pcode, Dr.code, Dr.설명, Dr.최대부하, Dr.m01, Dr.m02, Dr.m03, Dr.m04, Dr.m05, Dr.m06, Dr.m07, Dr.m08, Dr.m09, Dr.m10, Dr.m11, Dr.m12)
        'Next
        'For Each Dr As DS.weather_supdoRow In DSET1.weather_supdo.Rows
        '    Rcnt += Ta3.Insert(Dr.pcode, Dr.code, Dr.설명, Dr.t01, Dr.t02, Dr.t03, Dr.t04, Dr.t05, Dr.t06, Dr.t07, Dr.t08, Dr.t09, Dr.t10,
        '                       Dr.t11, Dr.t12, Dr.t13, Dr.t14, Dr.t15, Dr.t16, Dr.t17, Dr.t18, Dr.t19, Dr.t20, Dr.t21, Dr.t22, Dr.t23, Dr.t24)
        'Next
        'For Each Dr As DS.weather_tempRow In DSET1.weather_temp.Rows
        '    Rcnt += Ta4.Insert(Dr.pcode, Dr.code, Dr.설명, Dr.t01, Dr.t02, Dr.t03, Dr.t04, Dr.t05, Dr.t06, Dr.t07, Dr.t08, Dr.t09, Dr.t10,
        '                       Dr.t11, Dr.t12, Dr.t13, Dr.t14, Dr.t15, Dr.t16, Dr.t17, Dr.t18, Dr.t19, Dr.t20, Dr.t21, Dr.t22, Dr.t23, Dr.t24)
        'Next
        'MsgBox("업데이트완료", MsgBoxStyle.Information, "확인")
    End Sub


#End Region

#Region "COntextMenu"


    Private Sub ContextMenuStrip1_Opening(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening
        'If Me.TreeView1.SelectedNode Is Nothing Then Return
        'Dim tagstring As String = Me.TreeView1.SelectedNode.Tag.ToString()

        'If Me.TreeView1.SelectedNode.Level = 0 Then '//상단메뉴이고
        '    If Me.TreeView1.SelectedNode.Text.Substring(0, 3) = "입력존" Then
        '        Me.그룹추가ToolStripMenuItem.Enabled = True
        '        Me.그룹변경ToolStripMenuItem.Enabled = False
        '        Me.그룹복사ToolStripMenuItem.Enabled = False
        '        Me.그룹삭제ToolStripMenuItem.Enabled = False
        '    Else
        '        e.Cancel = True
        '    End If
        'ElseIf Me.TreeView1.SelectedNode.Level = 1 AndAlso tagstring.Length > 3 Then
        '    If tagstring.Substring(0, 3) = "입력존" Then
        '        Me.그룹추가ToolStripMenuItem.Enabled = True
        '        Me.그룹변경ToolStripMenuItem.Enabled = True
        '        Me.그룹복사ToolStripMenuItem.Enabled = True
        '        Me.그룹삭제ToolStripMenuItem.Enabled = True
        '    Else
        '        e.Cancel = True
        '    End If
        'End If
    End Sub

    Private Sub 그룹추가ToolStripMenuItem_Click(sender As System.Object, e As EventArgs) Handles 그룹추가ToolStripMenuItem.Click
        'If Me.TreeView1.SelectedNode Is Nothing Then Return
        'Dim newname As String = InputBox("그룹이름", "신규그룹이름을 입력하세요", "그룹명")
        'If newname.Trim = "" Then Return
        'If Me.TreeView1.SelectedNode.Level = 1 Then
        '    If Me.TreeView1.SelectedNode.Parent.Nodes.Find(newname, True).Length = 0 Then
        '        Dim ntv As TreeNode = Me.TreeView1.SelectedNode.Parent.Nodes.Add(newname, newname + "(0)")
        '        ntv.Tag = "입력존|" + newname
        '        Me.TreeView1.SelectedNode = ntv
        '        'TreeView1_MouseDoubleClick(Nothing, Nothing)
        '    End If
        'Else
        '    If Me.TreeView1.SelectedNode.Nodes.Find(newname, True).Length = 0 Then
        '        Dim ntv As TreeNode = Me.TreeView1.SelectedNode.Nodes.Add(newname, newname + "(0)")
        '        ntv.Tag = "입력존|" + newname
        '        Me.TreeView1.SelectedNode = ntv
        '        'TreeView1_MouseDoubleClick(Nothing, Nothing)
        '    End If
        'End If
    End Sub

    Private Sub 그룹삭제ToolStripMenuItem_Click(sender As System.Object, e As EventArgs) Handles 그룹삭제ToolStripMenuItem.Click
        ''//선택된그룹을 삭제
        'If Me.TreeView1.SelectedNode Is Nothing Then Return
        'Dim tn As TreeNode = Me.TreeView1.SelectedNode
        'If Me.TreeView1.SelectedNode.Level <> 1 Then Return
        'Dim tag As String = Me.TreeView1.SelectedNode.Tag.ToString()
        'Dim t() As String = tag.Split("|")
        'If MsgBox("선택된그룹 [" + t(1) + "]을(를) 삭제하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") = MsgBoxResult.Ok Then
        '    For Each dr As DS.tbl_zoneRow In DSET1.tbl_zone.Select("code <> '0' and 그룹='" + t(1) + "'")
        '        DeleteMyunFromZoneCode(dr.code)
        '        dr.Delete()
        '    Next
        '    DSET1.tbl_zone.AcceptChanges()
        '    ' Refresh_MenuItems("")
        'End If
    End Sub

    '''해당존을 사용한 면을 삭제합니다.
    Private Sub DeleteMyunFromZoneCode(Zonecode As String)
        For Each dr As DS.tbl_myounRow In DSET1.tbl_myoun.Select("code <> '0' and 존분류='" + Zonecode + "'")
            dr.Delete()
        Next
        DSET1.tbl_myoun.AcceptChanges()
    End Sub

    Private Sub 그룹변경ToolStripMenuItem_Click(sender As System.Object, e As EventArgs) Handles 그룹변경ToolStripMenuItem.Click
        ''//선택된그룹을 삭제
        'If Me.TreeView1.SelectedNode Is Nothing Then Return
        'Dim tn As TreeNode = Me.TreeView1.SelectedNode
        'If Me.TreeView1.SelectedNode.Level <> 1 Then Return
        'Dim tag As String = Me.TreeView1.SelectedNode.Tag.ToString()
        'Dim t() As String = tag.Split("|")

        'Dim m As New System.Text.StringBuilder
        'Dim newname As String = InputBox("변경할 그룹이름을 입력하세요", "그룹변경", t(1))
        'If newname.Trim = "" Then Return
        'If newname.Trim = t(1) Then Return

        'If MsgBox("선택된그룹 [" + t(1) + "]을(를) [" + newname + "]로 변경하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") = MsgBoxResult.Ok Then
        '    For Each dr As DS.tbl_zoneRow In DSET1.tbl_zone.Select("code <> '0' and 그룹='" + t(1) + "'")
        '        dr.그룹 = newname
        '    Next
        '    DSET1.tbl_zone.AcceptChanges()
        '    ' Refresh_MenuItems("")
        'End If
    End Sub
    Private Sub 그룹복사ToolStripMenuItem_Click(sender As System.Object, e As EventArgs) Handles 그룹복사ToolStripMenuItem.Click
        ''//선택된그룹을 삭제
        'If Me.TreeView1.SelectedNode Is Nothing Then Return
        'Dim tn As TreeNode = Me.TreeView1.SelectedNode
        'If Me.TreeView1.SelectedNode.Level <> 1 Then Return
        'Dim tag As String = Me.TreeView1.SelectedNode.Tag.ToString()
        'Dim t() As String = tag.Split("|")

        'Dim m As New System.Text.StringBuilder
        'Dim newname As String = InputBox("새로운 그룹이름을 입력하세요", "그룹복사", t(1))
        'If newname.Trim = "" Then Return
        'If newname.Trim = t(1) Then Return

        'If MsgBox("선택된그룹 [" + t(1) + "]을(를) [" + newname + "]로 복사하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") = MsgBoxResult.Ok Then
        '    For Each dr As DS.tbl_zoneRow In DSET1.tbl_zone.Select("code <> '0' and 그룹='" + t(1) + "'")
        '        Dim newcode As String = GetNewZoneCode()
        '        Dim newdr As DataRow = DSET1.tbl_zone.NewRow
        '        For Each c As DataColumn In DSET1.tbl_zone.Columns
        '            newdr(c.ColumnName) = dr(c.ColumnName)
        '        Next
        '        newdr("code") = newcode
        '        newdr("그룹") = newname
        '        DuplicateZoneRow(dr.code, newcode)   '//이존의코드값을 지정해준다.
        '        DSET1.tbl_zone.Rows.Add(newdr)
        '    Next
        '    DSET1.tbl_zone.AcceptChanges()
        '    'Refresh_MenuItems("")
        'End If
    End Sub

    Private Sub DuplicateZoneRow(ZoneCode As String, newzoneCode As String)
        '//이입력존을 사용하는 입력면을 복제해서 연결해준다.
        Dim 사용입력면() As DS.tbl_myounRow = DSET1.tbl_myoun.Select("존분류='" + ZoneCode + "'")
        For Each 기존입력면 As DS.tbl_myounRow In 사용입력면
            Dim 신규입력면 As DS.tbl_myounRow = DSET1.tbl_myoun.Newtbl_myounRow
            For Each 기존컬럼 As DataColumn In DSET1.tbl_myoun.Columns
                If 기존컬럼.ColumnName.ToUpper = "CODE" Then
                    신규입력면.code = GetMyounMaxCode(DSET1.tbl_myoun)
                Else
                    신규입력면(기존컬럼.ColumnName) = 기존입력면(기존컬럼.ColumnName)
                End If
            Next
            신규입력면.존분류 = newzoneCode
            DSET1.tbl_myoun.Rows.Add(신규입력면)
            DSET1.tbl_myoun.AcceptChanges()
        Next
    End Sub

    '''면의새로운코드값을계산할때사용한다.
    Private Function GetMyounMaxCode(ByVal dt As DataTable) As String
        Try
            Dim Dr As DataRow = dt.Select("", "code desc")(0)
            Return Format(CInt(Dr("code")) + 1, "0000")
        Catch ex As Exception
            Return "0001"
        End Try
    End Function

    Private Function GetNewZoneCode() As String
        Try
            Dim Dr As DataRow = DSET1.tbl_zone.Select("", "code desc")(0)
            Dim Dr_myoun As DataRow = DSET1.tbl_myoun.Select("", "존분류 desc")(0)
            If Dr("code") >= Dr_myoun("존분류") Then
                Return Format(CInt(Dr("code")) + 1, "0000")
            Else
                Return Format(CInt(Dr_myoun("존분류")) + 1, "0000")
            End If
        Catch ex As Exception
            Return "0001"
        End Try
    End Function


#End Region



    Private Sub BtCalc_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub RibbonButton9_Click(sender As Object, e As EventArgs) Handles mbt_report_od.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If

        Frm_v20091231_Report.Show()
    End Sub

    Private Sub RibbonButton10_Click(sender As Object, e As EventArgs) Handles ribbonButton10.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If

        If Program = EProgram.친환경평가 Then
            Report_친환경.Show()
        Else
            Report_검토서2.Show()
        End If

    End Sub

    Private Sub RibbonButton5_Click(sender As Object, e As EventArgs) Handles ribbonButton5.Click
        Menu_New()
    End Sub

    Private Sub RibbonButton6_Click(sender As Object, e As EventArgs) Handles ribbonButton6.Click
        Menu_Open()
    End Sub

    Sub Menu_Save()
        '/여긴 버튼 클릭됫을떄 일어나는 이벤트 아시죵 ^^?
        If Not Prj.Opened Then
            MsgBox(CLang.열린파일없음, MsgBoxStyle.Information, "확인")
            Return
        End If

        '//열려잇는 폼이 있다면 저장하도록한다.
        For Each ChildForm As CForm In Me.MdiChildren
            If ChildForm.HasChanged Then ChildForm.AcceptChanged()
        Next

        '//파일을 저장한다.
        Func_Save_OD(Prj.FileName)
    End Sub

    Sub Menu_SaveAs()
        If Prj.FileName = "" Then
            MsgBox(CLang.열린파일없음, MsgBoxStyle.Information, "확인")
            Return
        End If

        '//열려잇는 폼이 있다면 저장하도록한다.
        For Each ChildForm As CForm In Me.MdiChildren
            If ChildForm.HasChanged Then ChildForm.AcceptChanged()
        Next

        Dim SD As New SaveFileDialog With {
            .FileName = Prj.FileName,
            .Filter = "템플릿파일(*." + FileExt + ")|*." + FileExt + "|모든파일(*.*)|*.*",
            .FilterIndex = 0
        }

        If SD.ShowDialog <> Windows.Forms.DialogResult.OK Then Return
        Prj.FileName = SD.FileName

        Me.Func_Save_OD(Prj.FileName)
    End Sub

    Private Sub BtSaveFile_Click(sender As Object, e As EventArgs) Handles mbt_save.Click
        Menu_Save()
    End Sub

    Private Sub BTSaveNew_Click(sender As Object, e As EventArgs) Handles mbt_save2.Click
        Menu_SaveAs()

    End Sub

    Private Sub RibbonButton13_Click(sender As Object, e As EventArgs) Handles RibbonButton13.Click
        Frm_About.ShowDialog()
    End Sub

    Private Sub RibbonButton9_Click_1(sender As Object, e As EventArgs) Handles RibbonButton9.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If

        If Frm_FileInfo.ShowDialog = Windows.Forms.DialogResult.OK Then
            Refresh_StatusInfo()
        End If
    End Sub

    Private Sub RibbonButton11_Click(sender As Object, e As EventArgs) Handles btShowWeather.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        'Me.Toggle_Menu_Color(E_MenuIdx.기상데이터)
        Frm_Weather.ControlBox = True
        Frm_Weather.ShowDialog()
    End Sub

    Private Sub RibbonButton12_Click(sender As Object, e As EventArgs) Handles ribbonButton12.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Frm_profile.ControlBox = True
        Frm_profile.Show()
    End Sub

    Private Sub RibbonButton14_Click(sender As Object, e As EventArgs)
        Dim but As C1.Win.C1Ribbon.RibbonButton = CType(sender, C1.Win.C1Ribbon.RibbonButton)
        Dim idx As Integer = CInt(but.Tag.ToString)
        Read_PreFile(idx)
    End Sub

    Private Sub RibbonButton14_Click_1(sender As Object, e As EventArgs) Handles RibbonButton14.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Frm_Common.ControlBox = True
        Frm_Common.Show()
        'Show_menu(New Frm_Common)
    End Sub

    Private Sub RibbonButton15_Click(sender As Object, e As EventArgs) Handles RibbonButton15.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Frm_RepResult_Admin.ControlBox = True
        Frm_RepResult_Admin.Show()
    End Sub

    Private Sub RibbonButton16_Click(sender As Object, e As EventArgs) Handles RibbonButton16.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Frm_Zone.ControlBox = True
        Frm_Zone.Show()
    End Sub

    ''' <summary>
    ''' 지정한 폼이 열려있는지를 확인함
    ''' </summary>
    ''' <param name="TagStr"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Function CheckOpenForm(TagStr As String) As CForm
        Dim childf As Form = Nothing
        For Each cf As Form In Me.MdiChildren
            If cf.Tag.ToString = TagStr Then
                childf = cf
                Exit For
            End If
        Next
        Return childf
    End Function

    Sub Show_Menu(fNo As Integer)
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If

        '//해당폼이 열여있는지 확인한다.
        Dim ftagStr As String = fNo.ToString()
        Dim ChildForm As CForm = CheckOpenForm(ftagStr)
        If Not ChildForm Is Nothing Then '//기존에 열려있는 폼이다.
            If ChildForm.WindowState = FormWindowState.Minimized Then ChildForm.WindowState = FormWindowState.Normal
            ChildForm.Show()
            ChildForm.Activate()
        Else
            If fNo = 1 Then
                ChildForm = New Frm_1_Basic()
            ElseIf fNo = 2 Then
                ChildForm = New Frm_2_Build()
            ElseIf fNo = 3 Then
                ChildForm = New Frm_3_Mach()
            ElseIf fNo = 4 Then
                ChildForm = New Frm_5_New()
            ElseIf fNo = 5 Then
                ChildForm = New Frm_6_Req()
            End If

            ChildForm.MdiParent = Me
            ChildForm.Show()
        End If
    End Sub
    Private Sub BtMenu_Click(sender As Object, e As EventArgs) Handles bt1.Click, bt2.Click, bt3.Click, bt4.Click, bt5.Click

        Dim but As C1.Win.C1Ribbon.RibbonButton = sender

        If but Is bt1 Then
            Show_Menu(1)
        ElseIf but Is bt2 Then
            Show_Menu(2)
        ElseIf but Is bt3 Then
            Show_Menu(3)
        ElseIf but Is bt4 Then
            Show_Menu(4)
        ElseIf but Is bt5 Then
            Show_Menu(5)
        End If

    End Sub

    Private Sub RibbonButton1_Click(sender As System.Object, e As System.EventArgs) Handles RibbonButton1.Click
        Me.LayoutMdi(MdiLayout.TileHorizontal)
    End Sub

    Private Sub RibbonButton2_Click(sender As System.Object, e As System.EventArgs) Handles RibbonButton2.Click
        Me.LayoutMdi(MdiLayout.Cascade)
    End Sub

    Private Sub RibbonButton3_Click(sender As System.Object, e As System.EventArgs) Handles RibbonButton3.Click
        Try
            For Each child As CForm In Me.MdiChildren
                If child.HasChanged Then child.AcceptChanged()
                child.Close()
            Next
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
        End Try

    End Sub

    Private Sub RibbonButton4_Click(sender As Object, e As EventArgs) Handles RibbonButton4.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Frm_Yk.ControlBox = True
        Frm_Yk.Show()
    End Sub

    Private Sub RibbonButton7_Click(sender As Object, e As EventArgs) Handles RibbonButton7.Click
        Me.LayoutMdi(MdiLayout.TileVertical)
    End Sub

    Private Sub RibbonButton17_Click(sender As Object, e As EventArgs)
        Me.LayoutMdi(MdiLayout.ArrangeIcons)
    End Sub

    Private Sub RibbonButton8_Click(sender As Object, e As EventArgs) Handles RibbonButton8.Click
        Show_Menu(1)
        Show_Menu(2)
        Show_Menu(3)
        Show_Menu(4)
    End Sub

    Private Sub RibbonButton18_Click(sender As Object, e As EventArgs) Handles RibbonButton18.Click
        Read_FilHistory()
    End Sub

    Private Sub RibbonButton20_Click(sender As Object, e As EventArgs) Handles RibbonButton20.Click
        Frm_ExtReport.Show()
    End Sub

    Private Sub RibbonButton21_Click(sender As System.Object, e As System.EventArgs) Handles RibbonButton21.Click
        Dim sd As New SaveFileDialog
        If sd.ShowDialog() <> Windows.Forms.DialogResult.OK Then Return
        DSETR1.ExtReport.WriteXml(sd.FileName, XmlWriteMode.WriteSchema)
    End Sub

    Private Sub RibbonButton22_Click(sender As System.Object, e As System.EventArgs)
        '//실행폴더내의 cache 폴더에 저장한다.
        Dim savepath As New System.IO.DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\Cache")
        If Not savepath.Exists Then savepath.Create()

        '//지역및 기상데이터를 모두저장한다.
        If DSET1.tbl_weather_od.Rows.Count < 2 Then
            MsgBox("저장가능한 기상데이터가 없습니다", MsgBoxStyle.Critical, "확인")
            Return
        End If

        Try
            DSET1.tbl_weather_od.WriteXml(savepath.FullName + "\tbl_weather_od.xml")
            DSET1.weather_group.WriteXml(savepath.FullName + "\weather_group.xml")
            DSET1.weather_cha_od.WriteXml(savepath.FullName + "\weather_cha_od.xml")
            DSET1.weather_ilsa_od.WriteXml(savepath.FullName + "\weather_ilsa_od.xml")
            DSET1.weather_supdo_od.WriteXml(savepath.FullName + "\weather_supdo_od.xml")
            DSET1.weather_temp_od.WriteXml(savepath.FullName + "\weather_temp_od.xml")
            MsgBox("저장완료", MsgBoxStyle.Information, "확인")
            Shell("explorer " + savepath.FullName, AppWinStyle.NormalFocus)
        Catch ex As Exception
            MsgBox("저장 중 오류가 발생했습니다" + vbCrLf + ex.Message, MsgBoxStyle.Critical, "확인")
        End Try

    End Sub

    Private Sub RibbonButton23_Click(sender As System.Object, e As System.EventArgs)
        '//실행폴더내의 cache 폴더에 저장한다.
        Dim savepath As New System.IO.DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\Cache")
        If Not savepath.Exists Then savepath.Create()

        '//지역및 기상데이터를 모두저장한다.
        If DSET1.tbl_common_od.Rows.Count < 2 Then
            MsgBox("저장가능한 공용데이터가 없습니다", MsgBoxStyle.Critical, "확인")
            Return
        End If

        Try
            DSET1.tbl_common_od.WriteXml(savepath.FullName + "\tbl_common_od.xml")
            MsgBox("저장완료", MsgBoxStyle.Information, "확인")
            Shell("explorer " + savepath.FullName, AppWinStyle.NormalFocus)
        Catch ex As Exception
            MsgBox("저장 중 오류가 발생했습니다" + vbCrLf + ex.Message, MsgBoxStyle.Critical, "확인")
        End Try
    End Sub

    Private Sub btVerCheck_Click(sender As Object, e As EventArgs) Handles btVerCheck.Click
        Work_msg("프로그램 버젼확인중")

        Dim MyVersion As String = Format(My.Application.Info.Version.Minor, "0000") & Format(My.Application.Info.Version.Build, "0000")
        Dim MyProgVer As String = ""
        If Pub.Program = EProgram.친환경평가 Then
            MyVersion = "20171215" '"20170708"
            MyProgVer = "20180118"
        Else
            MyVersion = "20180901"  '//ui version
            MyProgVer = "20180901"  '//interface version
        End If

        'MyProgVer = "20170710"

        '//네트워크 연결이되면 체크한다.
        If Pub.CheckInternet Then
            lbOnline.Text = String.Format("[{0}]", "Online")
            Dim L As New ArinLogin.ArinLOgin
            Dim VersionInfo As ArinLogin.ArinLOgin.sVersionInfo = Nothing

            '//로직용 버젼체크
            Try
                If Program = EProgram.총량평가 Then
                    VersionInfo = L.Get_LastVersion("N")   '//총량평가 
                Else
                    VersionInfo = L.Get_LastVersion("O")   '//친환경평가
                End If
            Catch ex As Exception
                End
            End Try
            If VersionInfo.Ver <> "0" AndAlso (CInt(VersionInfo.Ver) > CInt(MyVersion)) Then   '//0은 없거나 관리안함의 뜻이므로 넘어간다.
                Dim Msg As New System.Text.StringBuilder
                Msg.AppendLine("새로운 버젼이 확인되었습니다" & vbCrLf)
                Msg.AppendLine("현재버젼:" & MyVersion & " 신규버젼:" & VersionInfo.Ver)
                Msg.AppendLine("----------------------------------")
                Msg.AppendLine(VersionInfo.Desc)
                Msg.AppendLine("----------------------------------")
                If VersionInfo.Link.Trim = "" Then VersionInfo.Link = "http://홈페이지주소"
                If MsgBox(Msg.ToString, MsgBoxStyle.Information, "버젼확인") = MsgBoxResult.Ok Then
                End If
                End '2011.03.08 프로그램이 최신버전이 아니면 프로그램을 종료시킨다.
            Else
                '//프로그램버젼을 추가로 체크한다.
                Try
                    If Program = EProgram.총량평가 Then
                        VersionInfo = L.Get_LastVersion("Q")   '//총량평가  (프로그램)
                    Else
                        VersionInfo = L.Get_LastVersion("R")   '//친환경평가 (프로그램)
                    End If
                Catch ex As Exception
                    End
                End Try

                If VersionInfo.Ver <> "0" AndAlso (CInt(VersionInfo.Ver) > CInt(MyProgVer)) Then   '//0은 없거나 관리안함의 뜻이므로 넘어간다.
                    Dim Msg As New System.Text.StringBuilder
                    Msg.AppendLine("프로그램의 인터페이스가 변경되었습니다." & vbCrLf)
                    Msg.AppendLine("현재버젼:" & MyProgVer & " 신규버젼:" & VersionInfo.Ver)
                    Msg.AppendLine("----------------------------------")
                    Msg.AppendLine(VersionInfo.Desc)
                    Msg.AppendLine("----------------------------------")
                    If VersionInfo.Link.Trim = "" Then VersionInfo.Link = "http://홈페이지주소"
                    If MsgBox(Msg.ToString, MsgBoxStyle.Information, "버젼확인") = MsgBoxResult.Ok Then
                    End If
                    End '2011.03.08 프로그램이 최신버전이 아니면 프로그램을 종료시킨다.
                End If
                MsgBox("최신 버전입니다.", MsgBoxStyle.Information, "확인")

            End If


        Else
            lbOnline.Text = String.Format("[{0}]", "Offline")
            Dim msg As New System.Text.StringBuilder
            msg.AppendLine("오프라인 모드입니다")
            msg.AppendLine("신규버젼 체크를 할 수 없습니다")
            msg.AppendLine("신규버젼은 {0}에서 확인 하시기 바랍니다")
            MsgBox(msg.ToString(), MsgBoxStyle.Information, "확인")
        End If

        Work_msg("")
    End Sub

    Private Sub RibbonButton24_Click(sender As Object, e As EventArgs) Handles mbt_calc.Click

        For Each f As CForm In Me.MdiChildren
            '//새로여는 화면이 기존화면과 같다면 그냥 있늦다.
            If f.HasChanged Then f.AcceptChanged()
        Next

        'If Me.OpenedForm <> E_MenuIdx.NONE Then

        'End If

        Func_Calc_OD()
    End Sub

    Private Sub RibbonButton24_Click_1(sender As Object, e As EventArgs) Handles RibbonButton24.Click

        '//save file (weather, profile)
        Dim fn0 As String = AppDomain.CurrentDomain.BaseDirectory + "\common.dat"
        Dim fn1 As String = AppDomain.CurrentDomain.BaseDirectory + "\profile.dat"
        Dim fn2 As String = AppDomain.CurrentDomain.BaseDirectory + "\weather{0}.dat"

        If MsgBox("암호화를 하시겠습니까?", MsgBoxStyle.YesNo, "확인") = MsgBoxResult.Yes Then
            Dim ms0 As New System.IO.MemoryStream()
            Dim ms1 As New System.IO.MemoryStream()
            Dim ms2 As New System.IO.MemoryStream()

            Dim ms21 As New System.IO.MemoryStream()
            Dim ms22 As New System.IO.MemoryStream()
            Dim ms23 As New System.IO.MemoryStream()
            Dim ms24 As New System.IO.MemoryStream()
            Dim ms25 As New System.IO.MemoryStream()

            Dim ms26 As New System.IO.MemoryStream()
            Dim ms27 As New System.IO.MemoryStream()
            Dim ms28 As New System.IO.MemoryStream()

            DSET1.tbl_common_od.WriteXml(ms0)
            Dim buffer0() As Byte = EnctryArea(ms0.GetBuffer())
            System.IO.File.WriteAllBytes(String.Format(fn0, ""), buffer0)

            DSET1.tbl_profile_od.WriteXml(ms1)
            buffer0 = EnctryArea(ms1.GetBuffer())
            System.IO.File.WriteAllBytes(String.Format(fn1, ""), buffer0)

            DSET1.tbl_weather_od.WriteXml(ms2)
            buffer0 = EnctryArea(ms2.GetBuffer())
            System.IO.File.WriteAllBytes(String.Format(fn2, ""), buffer0)

            DSET1.weather_cha_od.WriteXml(ms21)
            buffer0 = EnctryArea(ms21.GetBuffer())
            System.IO.File.WriteAllBytes(String.Format(fn2, "_ch"), buffer0)

            DSET1.weather_group.WriteXml(ms22)
            buffer0 = EnctryArea(ms22.GetBuffer())
            System.IO.File.WriteAllBytes(String.Format(fn2, "_gr"), buffer0)

            DSET1.weather_ilsa_od.WriteXml(ms23)
            buffer0 = EnctryArea(ms23.GetBuffer())
            System.IO.File.WriteAllBytes(String.Format(fn2, "_is"), buffer0)

            DSET1.weather_supdo_od.WriteXml(ms24)
            buffer0 = EnctryArea(ms24.GetBuffer())
            System.IO.File.WriteAllBytes(String.Format(fn2, "_sd"), buffer0)

            DSET1.weather_temp_od.WriteXml(ms25)
            buffer0 = EnctryArea(ms25.GetBuffer())
            System.IO.File.WriteAllBytes(String.Format(fn2, "_tp"), buffer0)

            DSET1.weather_water.WriteXml(ms26)
            buffer0 = EnctryArea(ms26.GetBuffer())
            System.IO.File.WriteAllBytes(String.Format(fn2, "_water"), buffer0)

            DSET1.weather_river.WriteXml(ms27)
            buffer0 = EnctryArea(ms27.GetBuffer())
            System.IO.File.WriteAllBytes(String.Format(fn2, "_river"), buffer0)

            DSET1.weather_wind.WriteXml(ms28)
            buffer0 = EnctryArea(ms28.GetBuffer())
            System.IO.File.WriteAllBytes(String.Format(fn2, "_wind"), buffer0)
        Else
            DSET1.tbl_common_od.WriteXml(String.Format(fn0, "") + ".xml", True)
            DSET1.tbl_profile_od.WriteXml(String.Format(fn1, "") + ".xml", True)
            DSET1.tbl_weather_od.WriteXml(String.Format(fn2, "") + ".xml", True)
            DSET1.weather_cha_od.WriteXml(String.Format(fn2, "_ch") + ".xml", True)
            DSET1.weather_group.WriteXml(String.Format(fn2, "_gr") + ".xml", True)
            DSET1.weather_ilsa_od.WriteXml(String.Format(fn2, "_is") + ".xml", True)
            DSET1.weather_supdo_od.WriteXml(String.Format(fn2, "_sd") + ".xml", True)
            DSET1.weather_temp_od.WriteXml(String.Format(fn2, "_tp") + ".xml", True)

            DSET1.weather_water.WriteXml(String.Format(fn2, "_water") + ".xml", True)
            DSET1.weather_river.WriteXml(String.Format(fn2, "_river") + ".xml", True)
            DSET1.weather_wind.WriteXml(String.Format(fn2, "_wind") + ".xml", True)
        End If


    End Sub

    Private Sub RibbonButton25_Click(sender As Object, e As EventArgs) Handles RibbonButton25.Click
        DSET1.tbl_yk.Clear()
        DSET1.tbl_ykdetail.Clear()
        DSET1.tbl_new.Clear()
        DSET1.tbl_new_energy.Clear()
        DSET1.tbl_new_ground.Clear()
        DSET1.tbl_new_light.Clear()
        DSET1.AcceptChanges()
        DSETR1.ExtReport.Clear()
        DSETR1.AcceptChanges()
    End Sub

    Private Sub RibbonButton26_Click(sender As Object, e As EventArgs) Handles RibbonButton26.Click
        DSET1.tbl_profile_od.Clear()
        DSET1.tbl_weather_od.Clear()
        DSET1.weather_cha_od.Clear()
        DSET1.weather_ilsa_od.Clear()
        DSET1.weather_temp_od.Clear()
        DSET1.weather_supdo_od.Clear()
        DSET1.weather_group.Clear()

        DSET1.weather_water.Clear()
        DSET1.weather_river.Clear()
        DSET1.weather_wind.Clear()
        DSET1.AcceptChanges()
    End Sub


    Private Sub RibbonButton11_Click_1(sender As System.Object, e As System.EventArgs) Handles RibbonButton11.Click
        '//tpl test
        Dim od As New OpenFileDialog()
        od.Filter = "tpl|*.tpl"
        If (od.ShowDialog() = Windows.Forms.DialogResult.OK) Then
            Open_TPL(od.FileName)
        End If

    End Sub


    Private Function Open_TPL(ByVal FileName As String) As String

        '//현재열려있는프로젝트를 닫는다.
        DSET1.Clear()
        DSET2.Clear()
        DSETR1.Clear()
        DSETR2.Clear()
        DSET1.AcceptChanges()
        DSET2.AcceptChanges()
        DSETR1.AcceptChanges()
        DSETR2.AcceptChanges()


        Prj.IsError = False '//160509

        '//파일을 열어서 템플릿이름을 가져온다
        Dim FS As System.IO.Stream
        FS = New IO.FileStream(FileName, IO.FileMode.Open)

        Dim Br As New IO.BinaryReader(FS, System.Text.Encoding.Default)
        Prj.FileName = FileName
        Prj.Opened = False

        '//세이브파일구조(2)
        Prj.SFType = STB(Br.ReadBytes(2))


        Dim ext As String = "ECL2"
        Select Case Prj.SFType
            Case "00", "10"   '//기본버젼
                Prj.UIVersion = STB(Br.ReadBytes(10))
                Prj.LGVersino = STB(Br.ReadBytes(10))
                Select Case Prj.LGVersino
                    Case "2009123100", "2010030700", "2010031400"
                        Prj.LGVersino = StartVersion
                End Select
                Select Case Prj.UIVersion
                    Case "2009123100", "2010030700", "2010031400"
                        Prj.UIVersion = StartVersion
                        Prj.UIVersion = StartVersion
                End Select

                Prj.Name = STB(Br.ReadBytes(100))
                Prj.Desc = STB(Br.ReadBytes(256))
                Prj.MakeTime = STB(Br.ReadBytes(19))
                Prj.EditTime = STB(Br.ReadBytes(19))
                ' MsgBox(Br.BaseStream.Position)

                '//DS1 데이터초기화 및 오픈
                DSET1.Clear() : DSET1.AcceptChanges()
                Dim DS1Len As Int64 = Br.ReadInt64
                If DS1Len = 0 Then
                    DS1Len = FS.Length - Br.BaseStream.Position - 2
                End If
                'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1Len, MsgBoxStyle.Information, Hex(DS1Len))
                Dim DS1() As Byte
                Try
                    DS1 = Br.ReadBytes(CInt(DS1Len))
                Catch ex As Exception
                    Prj.IsError = True
                    MsgBox("파일이 손상되었습니다(Read Data Array)." & vbCrLf & FileName & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 byteRead Error")
                End Try

                'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1.Length, MsgBoxStyle.Information, DS1Len)
                If Not Prj.IsError Then
                    Dim Ms As New IO.MemoryStream(DS1)
                    Try
                        DSET1.ReadXml(Ms)
                        DSET1.AcceptChanges()
                        Ms.Close()
                    Catch ex As Exception
                        Prj.IsError = True
                        MsgBox("파일이 손상되었습니다(Read DataSet)" & vbCrLf & FileName & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 Open Error")
                    End Try

                    If Prj.IsError Then
                        If MsgBox("데이터를 복구모드로 확인하시겠습니까?", MsgBoxStyle.Question Or MsgBoxStyle.YesNo, "확인") = MsgBoxResult.Yes Then
                            '//메모리버퍼르 utf8를 이용하여 데이터처리를 해야한다
                            Dim accCount As UInteger = 0
                            Ms.Position = 0
                            Dim AllDataList As String = System.Text.Encoding.UTF8.GetString(DS1)
                            My.Computer.FileSystem.WriteAllText("c:\temp\1.txt", AllDataList, False)
                            Dim CurrentTable As String = ""
                            Dim dr As DataRow = Nothing

                            For Each line As String In AllDataList.Split(vbCrLf)



                                '//각줄을 가지고 처리를 한다
                                line = line.Trim
                                If line.ToLower.StartsWith("<ds") AndAlso line.EndsWith(">") Then
                                    '//데이터셋선언부이므로 넘어간다
                                ElseIf line.ToLower.StartsWith("<weather_") AndAlso line.EndsWith(">") Then
                                    CurrentTable = line.Substring(1, line.Length - 2)
                                    dr = DSET1.Tables(CurrentTable).NewRow
                                ElseIf line.ToLower.StartsWith("</weather_") AndAlso line.EndsWith(">") Then
                                    '//테이블의 종료
                                    '//
                                    accCount += 1
                                    DSET1.Tables(CurrentTable).Rows.Add(dr)
                                    CurrentTable = ""
                                ElseIf line.ToLower.StartsWith("<tbl_") AndAlso line.EndsWith(">") Then
                                    CurrentTable = line.Substring(1, line.Length - 2)
                                    dr = DSET1.Tables(CurrentTable).NewRow
                                ElseIf line.ToLower.StartsWith("</tbl_") AndAlso line.EndsWith(">") Then
                                    '//테이블의 종료
                                    DSET1.Tables(CurrentTable).Rows.Add(dr)
                                    accCount += 1
                                    CurrentTable = ""
                                Else
                                    '//일반데이터
                                    If String.IsNullOrWhiteSpace(CurrentTable) Then Continue For
                                    Dim 닫는태그위치 As Integer = line.IndexOf(">")
                                    If 닫는태그위치 > -1 Then
                                        Dim 필드명 As String = line.Substring(1, 닫는태그위치 - 1)
                                        Dim 값종료태그위치 As Integer = line.IndexOf("<", 닫는태그위치)
                                        If 값종료태그위치 > -1 Then
                                            Dim 내부값 As String = line.Substring(닫는태그위치 + 1, 값종료태그위치 - 닫는태그위치 - 1)
                                            dr(필드명) = 내부값
                                        End If
                                    End If
                                End If
                            Next

                            '//만약입력존이 없고 입력면 데이터가 있다면 존분류값을 이용해서 존을 우선 생성해준다
                            If DSET1.tbl_zone.Rows.Count < 2 AndAlso DSET1.tbl_myoun.Rows.Count > 1 Then
                                For Each drMn As DS.tbl_myounRow In DSET1.tbl_myoun.Rows
                                    Dim 존분류 As String = drMn.존분류.Trim
                                    If String.IsNullOrWhiteSpace(존분류) Then Continue For
                                    Dim 존데이터갯수 As Integer = DSET1.tbl_zone.Select("code='" + 존분류 + "'").Length
                                    If 존데이터갯수 = 0 Then
                                        Dim 뉴존 As DS.tbl_zoneRow = DSET1.tbl_zone.Newtbl_zoneRow
                                        뉴존.code = 존분류
                                        뉴존.설명 = "자동생성(" + 존분류 + ")"
                                        DSET1.tbl_zone.Addtbl_zoneRow(뉴존)
                                        accCount += 1
                                    End If
                                Next
                                DSET1.tbl_zone.AcceptChanges()
                            End If

                            MsgBox(accCount.ToString() + "건의 자료가 복구되었습니다", MsgBoxStyle.Critical, "확인")
                            DSET1.AcceptChanges()
                            DSETR1.Clear() : DSETR1.AcceptChanges()
                            Prj.IsError = False
                        End If
                    Else
                        '//에러가없는경우 다음진행

                        '//DS1가 있다면 게속 한다
                        DSETR1.Clear() : DSETR1.AcceptChanges()
                        DS1Len = Br.ReadInt64
                        DS1 = Br.ReadBytes(CInt(DS1Len))
                        Ms = New IO.MemoryStream(DS1)
                        Try
                            DSETR1.ReadXml(Ms)
                            DSETR1.AcceptChanges()
                            Ms.Close()
                        Catch ex As Exception
                            MsgBox("기존 버전의 계산결과를 가져올 수 없습니다." & vbCrLf & FileName & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds2 Open Error")
                        End Try

                        Prj.IsError = False

                    End If


                End If

            Case "01"   '//기본버젼(+암호
                Prj.UIVersion = STB(Br.ReadBytes(10))
                Prj.LGVersino = STB(Br.ReadBytes(10))
                Select Case Prj.LGVersino
                    Case "2009123100", "2010030700", "2010031400"
                        Prj.LGVersino = StartVersion
                End Select
                Select Case Prj.UIVersion
                    Case "2009123100", "2010030700", "2010031400"
                        Prj.UIVersion = StartVersion
                End Select
                Prj.Name = STB(Br.ReadBytes(100))
                Prj.Desc = STB(Br.ReadBytes(256))
                Prj.MakeTime = STB(Br.ReadBytes(19))
                Prj.EditTime = STB(Br.ReadBytes(19))
                Prj.Password = STB(Br.ReadBytes(8)) '//암호에 8바이트할당한다. 즉 8개의문자가가능 한글은 불가로한다
                ' MsgBox(Br.BaseStream.Position)

                '//DS1 데이터초기화 및 오픈
                DSET1.Clear() : DSET1.AcceptChanges()
                Dim DS1Len As Int64 = Br.ReadInt64
                'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1Len, MsgBoxStyle.Information, Hex(DS1Len))
                Dim DS1() As Byte = Br.ReadBytes(CInt(DS1Len))
                'MsgBox("pos=" & Br.BaseStream.Position & vbCrLf & DS1.Length, MsgBoxStyle.Information, DS1Len)
                Dim Ms As New IO.MemoryStream(DS1)
                Try
                    DSET1.ReadXml(Ms)
                    DSET1.AcceptChanges()
                    Ms.Close()
                Catch ex As Exception
                    MsgBox("파일이 손상되었습니다." & vbCrLf & FileName & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds1 Open Error")
                End Try

                '//DS1가 있다면 게속 한다
                DSETR1.Clear() : DSETR1.AcceptChanges()
                DS1Len = Br.ReadInt64
                DS1 = Br.ReadBytes(CInt(DS1Len))
                Ms = New IO.MemoryStream(DS1)
                Try
                    DSETR1.ReadXml(Ms)
                    DSETR1.AcceptChanges()
                    Ms.Close()
                Catch ex As Exception
                    MsgBox("기존 버전의 계산결과를 가져올 수 없습니다." & vbCrLf & FileName & vbCrLf & ex.Message.ToString, MsgBoxStyle.Information, "Ds2 Open Error")
                End Try
                Prj.IsError = False
            Case Else
                MsgBox("파일을 불러올 수 없습니다1" & vbCrLf & FileName, MsgBoxStyle.Critical, "불러오기실패")
                Prj.IsError = True
        End Select

        Br.Close()
        FS.Close()


        If Not Prj.IsError Then
            Prj.Opened = True
            'e.m_initdata.Enabled = True

            'Frm_Work.MdiParent = Me
            Frm_Work.Label1.Text = "데이터를 확인하고 있습니다"
            Frm_Work.Show()

            If DSET1.tbl_buha.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_buha.Rows.Add(New String() {"0", "(없음)"})
            If DSET1.tbl_bunbae.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_bunbae.Rows.Add(New String() {"0", "(없음)"})
            If DSET1.tbl_kongjo.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_kongjo.Rows.Add(New String() {"0", "(없음)"})
            'If DSET1.tbl_kongkub.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_kongkub.Rows.Add(New String() {"0", "(없음)"})
            If DSET1.tbl_myoun.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_myoun.Rows.Add(New String() {"0", "(없음)"})
            If DSET1.tbl_nanbangkiki.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_nanbangkiki.Rows.Add(New String() {"0", "(없음)"})
            If DSET1.tbl_nangbangkiki.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_nangbangkiki.Rows.Add(New String() {"0", "(없음)"})
            If DSET1.tbl_nbunbae.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_nbunbae.Rows.Add(New String() {"0", "(없음)"})
            If DSET1.tbl_new.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_new.Rows.Add(New String() {"0", "(없음)"})

            If DSET1.tbl_profile_od.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_profile_od.Rows.Add(New String() {"0", "(없음)"})
            If DSET1.tbl_weather_od.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_weather_od.Rows.Add(New String() {"0", "(없음)"})
            If DSET1.tbl_zone.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_zone.Rows.Add(New String() {"0", "(없음)"})
            If DSET1.tbl_yk.Select("code='0'").GetUpperBound(0) = -1 Then DSET1.tbl_yk.Rows.Add(New String() {"0", "(없음)"})
            If DSET1.tbl_Desc.Rows.Count < 1 Then
                MsgBox("건물개요데이터가 없으므로 초기자료를 생성합니다", MsgBoxStyle.Critical, "확인")
                Dim newdescdr As DS.tbl_DescRow = DSET1.tbl_Desc.NewRow
                newdescdr.name = "오류"
                newdescdr.buildarea = "0001"
                DSET1.tbl_Desc.Addtbl_DescRow(newdescdr)
                DSET1.tbl_Desc.AcceptChanges()
            End If


            '//날씨정보는 기상
            '//save file (weather, profile)
            DSET1.tbl_common_od.Clear()
            DSET1.tbl_profile_od.Clear()
            DSET1.tbl_weather_od.Clear()
            DSET1.weather_cha_od.Clear()
            DSET1.weather_group.Clear()
            DSET1.weather_ilsa_od.Clear()
            DSET1.weather_supdo_od.Clear()
            DSET1.weather_temp_od.Clear()
            Dim fn0 As String = AppDomain.CurrentDomain.BaseDirectory + "\common.dat"
            Dim fn1 As String = AppDomain.CurrentDomain.BaseDirectory + "\profile.dat"
            Dim fn2 As String = AppDomain.CurrentDomain.BaseDirectory + "\weather{0}.dat"

            If System.IO.File.Exists(fn0) Then
                Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn0, ""))
                If (buffer(0) = &H90) Then '//암호화된파일
                    Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                    Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                    Dim ms0 As New System.IO.MemoryStream(newbuffer)
                    DSET1.tbl_common_od.ReadXml(ms0)
                Else
                    '//아닌파일
                    DSET1.tbl_common_od.ReadXml(String.Format(fn0, ""))
                End If
            End If

            If System.IO.File.Exists(fn1) Then
                Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn1, ""))
                If (buffer(0) = &H90) Then '//암호화된파일
                    Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                    Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                    Dim ms0 As New System.IO.MemoryStream(newbuffer)
                    DSET1.tbl_profile_od.ReadXml(ms0)
                Else
                    '//아닌파일
                    DSET1.tbl_profile_od.ReadXml(String.Format(fn1, ""))
                End If
            End If
            If System.IO.File.Exists(String.Format(fn2, "")) Then
                Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, ""))
                If (buffer(0) = &H90) Then '//암호화된파일
                    Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                    Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                    Dim ms0 As New System.IO.MemoryStream(newbuffer)
                    DSET1.tbl_weather_od.ReadXml(ms0)
                Else
                    '//아닌파일
                    DSET1.tbl_weather_od.ReadXml(String.Format(fn2, ""))
                End If

            End If
            If System.IO.File.Exists(String.Format(fn2, "_ch")) Then
                Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, "_ch"))
                If (buffer(0) = &H90) Then '//암호화된파일
                    Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                    Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                    Dim ms0 As New System.IO.MemoryStream(newbuffer)
                    DSET1.weather_cha_od.ReadXml(ms0)
                Else
                    '//아닌파일
                    DSET1.weather_cha_od.ReadXml(String.Format(fn2, "_ch"))
                End If


            End If
            If System.IO.File.Exists(String.Format(fn2, "_gr")) Then
                Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, "_gr"))
                If (buffer(0) = &H90) Then '//암호화된파일
                    Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                    Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                    Dim ms0 As New System.IO.MemoryStream(newbuffer)
                    DSET1.weather_group.ReadXml(ms0)
                Else
                    '//아닌파일
                    DSET1.weather_group.ReadXml(String.Format(fn2, "_gr"))
                End If
            End If

            If System.IO.File.Exists(String.Format(fn2, "_is")) Then

                Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, "_is"))
                If (buffer(0) = &H90) Then '//암호화된파일
                    Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                    Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                    Dim ms0 As New System.IO.MemoryStream(newbuffer)
                    DSET1.weather_ilsa_od.ReadXml(ms0)
                Else
                    '//아닌파일
                    DSET1.weather_ilsa_od.ReadXml(String.Format(fn2, "_is"))
                End If

            End If


            If System.IO.File.Exists(String.Format(fn2, "_sd")) Then

                Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, "_sd"))
                If (buffer(0) = &H90) Then '//암호화된파일
                    Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                    Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                    Dim ms0 As New System.IO.MemoryStream(newbuffer)
                    DSET1.weather_supdo_od.ReadXml(ms0)
                Else
                    '//아닌파일
                    DSET1.weather_supdo_od.ReadXml(String.Format(fn2, "_sd"))
                End If

            End If
            If System.IO.File.Exists(String.Format(fn2, "_tp")) Then

                Dim buffer() As Byte = System.IO.File.ReadAllBytes(String.Format(fn2, "_tp"))
                If (buffer(0) = &H90) Then '//암호화된파일
                    Dim decKey() As Byte = New Byte() {&HAC, &H29, &H55, &H42}
                    Dim newbuffer() As Byte = DeCryptArea(buffer, decKey)
                    Dim ms0 As New System.IO.MemoryStream(newbuffer)
                    DSET1.weather_temp_od.ReadXml(ms0)
                Else
                    '//아닌파일
                    DSET1.weather_temp_od.ReadXml(String.Format(fn2, "_tp"))
                End If

            End If

            DSET1.tbl_common_od.AcceptChanges()
            DSET1.tbl_profile_od.AcceptChanges()
            DSET1.tbl_weather_od.AcceptChanges()
            DSET1.weather_cha_od.AcceptChanges()
            DSET1.weather_group.AcceptChanges()
            DSET1.weather_ilsa_od.AcceptChanges()
            DSET1.weather_supdo_od.AcceptChanges()
            DSET1.weather_temp_od.AcceptChanges()

            DSET1.AcceptChanges()


            '//입력존 데이터 취합
            Dim 존면적합 As Decimal = 0
            Dim 존수합 As Integer = 0
            Dim 존면적 As Decimal = 0
            For Each dr존 As DS.tbl_zoneRow In DSET1.tbl_zone.Select("code <> '0'")
                Dim 존수 As Integer = 0
                If IsNumeric(dr존.입력존의수) Then
                    존수 = CInt(dr존.입력존의수)
                Else
                    존수 = 1
                End If

                존수합 += 존수
                If IsNumeric(dr존.면적) Then
                    존면적 = dr존.면적 * 존수
                Else
                    존면적 = 0
                End If
                존면적합 = 존면적합 + 존면적
            Next


            '//건물용도기본값
            DSET1.tbl_type.Clear()
            Dim 용도 As String = DSET1.tbl_Desc.Rows(0)("isjugo").ToString
            If 용도 = "0001" OrElse 용도 = "0002" OrElse 용도 = "1" OrElse 용도 = "2" Then
                '//친환경(ecl3)

                '//전체존의수


                Dim newdr As DS.tbl_typeRow = DSET1.tbl_type.Newtbl_typeRow
                If 존수합 = 0 Then
                    newdr.세대면적 = 0
                Else
                    newdr.세대면적 = 존면적합 / 존수합
                End If


                newdr.세대수 = 존수합
                newdr.세대타입 = "1"
                newdr.code = "0001"
                DSET1.tbl_type.Addtbl_typeRow(newdr)
                DSET1.tbl_type.AcceptChanges()

                ext = "ECL3"
            Else
                '//ecl2

                '//층별개요추가

                Dim new개요 As DS.tbl_typeRow = DSET1.tbl_type.Newtbl_typeRow
                new개요.code = "0001"
                new개요.면적 = 존면적합
                new개요.층 = "업무시설"
                new개요.시설용도 = "0002"

                DSET1.tbl_type.Addtbl_typeRow(new개요)


                ext = "ECL2"
            End If

            If IsNumeric(용도) = False Then
                DSET1.tbl_Desc.Rows(0)("isjugo") = "1"
            End If

            '//그룹명이없는경우 처리함(130810:arin)
            For Each dr As DS.tbl_zoneRow In DSET1.tbl_zone.Select("isnull(그룹,'')=''")
                dr.그룹 = "기본"
            Next

            '//월별에너지사용량데이터영역생성(130819:arin)
            If DSET1.tbl_monuse.Rows.Count = 0 Then
                For y As Integer = 1 To 3
                    Dim idx As String = y.ToString("0000")
                    For i As Integer = 1 To 12
                        DSET1.tbl_monuse.Rows.Add(New String() {y.ToString() + "차년도", i.ToString("00"), "0", "0", "0", idx})   '//년,월,도시가스,전력,지역난방,코드
                    Next
                Next
            End If

            '//140808 데이터 기본값 처리
            '//입력존
            If Not DSET1 Is Nothing Then
                For i As Integer = 1 To DSET1.tbl_zone.Rows.Count

                    '//순실체적 재계산  150111
                    '순실체적NTb.Text = TOST(TOSG(면적NTb.Text) * TOSG(천장고NTb.Text))
                    Dim 면적 As String = ""
                    Dim 천장고 As String = ""
                    Dim 순실체적 As String = ""
                    Try
                        면적 = DSET1.tbl_zone.Rows(i - 1)("면적").ToString
                    Catch ex As Exception
                        면적 = ""
                    End Try
                    Try
                        천장고 = DSET1.tbl_zone.Rows(i - 1)("천장고p").ToString
                    Catch ex As Exception
                        천장고 = ""
                    End Try
                    Try
                        순실체적 = DSET1.tbl_zone.Rows(i - 1)("순실체적").ToString
                    Catch ex As Exception
                        순실체적 = ""
                    End Try
                    If IsNumeric(면적) AndAlso IsNumeric(천장고) Then
                        If Not IsNumeric(순실체적) Then
                            ' MsgBox("순실체적값이 없으므로 재계산 합니다", MsgBoxStyle.Information, "확인")
                            DSET1.tbl_zone.Rows(i - 1)("순실체적") = CSng(면적) * CSng(천장고)
                        End If
                    End If
                    If DSET1.tbl_zone.Rows(i - 1).RowState = DataRowState.Deleted OrElse _
                        DSET1.tbl_zone.Rows(i - 1).RowState = DataRowState.Detached Then
                        Continue For
                    End If
                    Dim StrCode As String = DSET1.tbl_zone.Rows(i - 1)("code").ToString
                    If StrCode.Length = 4 Then
                        DSET1.tbl_zone.Rows(i - 1)("code") = "0" + StrCode
                    End If
                Next
                DSET1.tbl_zone.AcceptChanges()
            End If

            If Not DSET2 Is Nothing Then
                For i As Integer = 1 To DSET2.tbl_zone.Rows.Count
                    If DSET2.tbl_zone.Rows(i - 1).RowState = DataRowState.Deleted OrElse _
                        DSET2.tbl_zone.Rows(i - 1).RowState = DataRowState.Detached Then
                        Continue For
                    End If
                    Dim StrCode As String = DSET2.tbl_zone.Rows(i - 1)("code").ToString
                    If StrCode.Length = 4 Then
                        DSET2.tbl_zone.Rows(i - 1)("code") = "0" + StrCode
                    End If
                Next
                DSET2.tbl_zone.AcceptChanges()
            End If

            '//입력면
            If Not DSET1 Is Nothing Then
                For i As Integer = 1 To DSET1.tbl_myoun.Rows.Count
                    If DSET1.tbl_myoun.Rows(i - 1).RowState = DataRowState.Deleted OrElse _
                        DSET1.tbl_myoun.Rows(i - 1).RowState = DataRowState.Detached Then
                        Continue For
                    End If
                    Dim StrCode As String = DSET1.tbl_myoun.Rows(i - 1)("code").ToString
                    If StrCode.Length = 4 Then
                        DSET1.tbl_myoun.Rows(i - 1)("code") = "0" + StrCode
                    End If

                    Dim StrCode2 As String = DSET1.tbl_myoun.Rows(i - 1)("존분류").ToString
                    If StrCode2.Length = 4 Then
                        StrCode2 = "0" + StrCode2
                        DSET1.tbl_myoun.Rows(i - 1)("존분류") = StrCode2
                    End If

                    '//입력존 찾기 171219
                    Dim 존목록() As DS.tbl_zoneRow = DSET1.tbl_zone.Select("code = '" + StrCode2 + "'")
                    If 존목록.Length = 1 Then
                        Dim 존수 As Integer = 0
                        If IsNumeric(존목록(0).입력존의수) Then
                            존수 = CInt(존목록(0).입력존의수)
                        Else
                            존수 = 1
                        End If
                        If 존수 > 1 Then
                            Dim 면적 As Single = TOSG(DSET1.tbl_myoun.Rows(i - 1)("건축부위면적"))
                            DSET1.tbl_myoun.Rows(i - 1)("건축부위면적") = 면적 * 존수
                        End If
                    End If
                Next



                DSET1.tbl_myoun.AcceptChanges()
            End If

            If Not DSET2 Is Nothing Then
                For i As Integer = 1 To DSET2.tbl_myoun.Rows.Count
                    If DSET2.tbl_myoun.Rows(i - 1).RowState = DataRowState.Deleted OrElse _
                        DSET2.tbl_myoun.Rows(i - 1).RowState = DataRowState.Detached Then
                        Continue For
                    End If
                    Dim StrCode As String = DSET2.tbl_myoun.Rows(i - 1)("code").ToString
                    If StrCode.Length = 4 Then
                        DSET2.tbl_myoun.Rows(i - 1)("code") = "0" + StrCode
                    End If

                    Dim StrCode2 As String = DSET2.tbl_myoun.Rows(i - 1)("존분류").ToString
                    If StrCode2.Length = 4 Then
                        DSET2.tbl_myoun.Rows(i - 1)("존분류") = "0" + StrCode2
                    End If

                Next
                DSET2.tbl_myoun.AcceptChanges()
            End If

            RibbonButton17_Click_1(Nothing, Nothing)

            Frm_Work.Close()


            '//접수일,인증데인터확인  / 13-12-05 / arin
            Dim Drdesc As DS.tbl_DescRow = DSET1.tbl_Desc.Rows(0)
            If Drdesc.injungdate.Trim = "" Then Drdesc.injungdate = Now.ToString("yyyy-MM-dd")
            If Drdesc.jubsudate.Trim = "" Then Drdesc.jubsudate = Now.ToString("yyyy-MM-dd")
            If Drdesc.용도수수료입금일 = "" Then Drdesc.용도수수료입금일 = Now.ToString("yyyy-MM-dd")
            If Drdesc.reqdate = "" Then Drdesc.reqdate = Now.ToString("yyyy-MM-dd")
            If Drdesc.existdate = "" Then Drdesc.existdate = Now.ToString("yyyy-MM-dd")
            If Drdesc.민간구분 = "" Then Drdesc.민간구분 = "1" '//1==공공, 0==일반
            Drdesc.buildarea = "010100"

            DSET1.tbl_Desc.AcceptChanges()

            ' // validation()    '//null보정

            '//팡리명이 너무길면안되니 경로를 뺴고 딱 파일명만 보여줍니다.
            Me.lbl_filename.Text = Prj.FileName.Substring(Prj.FileName.LastIndexOf("\") + 1)

        End If

        Return ext
    End Function

    Private Sub Set_Null(ByVal Columns() As String, ByRef dt As DataTable, ByVal val As String)
        For Each Dr As DataRow In dt.Select("code<>'0'", "code")
            For Each Col As String In Columns
                If Dr(Col).ToString.Trim = "" Then '//값이없으면 기본값(val)으로 설정
                    Dr(Col) = val
                End If
            Next
        Next
    End Sub

    Private Function validation() As Boolean
        '//존이 2개이상있어야한다 (없음데이터로인해서 반드시 1개는 있기때문이다.)
        '//여기보정데이터가잇네요.;
        Dim NoErr As Boolean = True

        '//콤보박스들의 값이 지정되어잇는지 확인한다. 무조건 있어야한다
        Dim Title As String
        Dim Columns() As String '//(없음)이 들어가는 콤보필드 
        Dim ColumnC() As String '//공용코드전용 필드들
        Dim CGubun() As String '//공용코드필드의 구분값이 저장됨
        Dim Columnst() As String    '//0이 들어가는 콤보필드

        '//ZONE
        Title = "Zone"
        Columns = New String() {"냉난방열공급시스템", "열저장능력", "열교가산치", _
                                "주말운전방식", "야간운전방식", "외기부하처리여부", _
                                "냉난방공조", "냉난방방식", _
                                 "조명부하산출방법", "조명방식", "인공광원"}
        ColumnC = New String() {"열저장능력", "열교가산치", _
                              "주말운전방식", "야간운전방식", "외기부하처리여부"} '
        '//다를지도 모르니 나중에 함 확인하시구요
        CGubun = New String() {"1023", "1022", _
                                "1002", "1002", "1054"}   '//공용코드있는데는 모조리 설정하시구요 물론 길이는 바로위하고 같아야합닌다.
        '//여기에 각 공용코드의 구분값 1009 뭐 이런것들을 같게 넣어주세요 column 가 8개가있었따면 cgubun 도 8개가 잇으면됩니다.

        Columnst = New String() {"프로필", "냉난방공조처리시스템", "열생산난방생산기기", _
                                "열생산급탕생산기기", "열생산냉방생산기기", _
                                 "열생산가습생산기기", "냉난방공조분배시스템", _
                                 "냉난방분배시스템", "공조냉방생산기기", "공조난방생산기기"}

        Set_Null(Columns, DSET1.tbl_zone, "(없음)")   '//데이터를 기본값 셋팅해주는구문이구요 없는데이터는 넓값처리
        Set_Null(ColumnC, DSET1.tbl_zone, "(없음)")   '//공용코드값이 아에없는 데이터를 기본값 셋팅해주는구문이구요 없는데이터는 넓값처리
        'Set_CheckCommon(ColumnC, DSET.tbl_zone, CGubun)    '//이거는 // 공용코드오류난 데이터 검색하는부분이에요
        Set_Null(Columnst, DSET1.tbl_zone, "0")

        Title = "신재생에너지"
        Columns = New String() {"기기종류", "가동연료", "태양열종류", "집열기유형", _
                                "집열판방위", "태양열시스템의성능", "축열탱크설치장소", _
                                "태양광모듈기울기", "태양광모듈방위", _
                                "태양광모듈종류", "태양광모듈적용타입", _
                                "열교환기설치여부", "팽창탱크설치여부"}
        Set_Null(Columns, DSET1.tbl_new, "(없음)")
        'Set_Null(Columnst, DSET.tbl_bunbae, "0")

        Title = "난방분배시스템"
        Columns = New String() {"생산기기구분", "표준치적용", "배관망유형", _
                                "배관구간방식", "배관설치장소", _
                                "배관설치장소", "지관장소"}
        Set_Null(Columns, DSET1.tbl_nbunbae, "(없음)")
        'Set_Null(Columnst, DSET.tbl_bunbae, "0")

        Title = "난방기기"
        Columns = New String() {"열생산기기방식", "사용연료", "운전방식", "보일러방식", _
                                "지역난방방식", "단열등급", "축열탱크방식", _
                                "배관망유형", "펌프교정계수", "펌프제어유형", _
                                "분배시스템방식", "순환유무", "펌프제어", _
                                "히트펌프시스템종류", "신재생연결여부"}
        Columnst = New String() {"연결된시스템"}
        Set_Null(Columns, DSET1.tbl_nanbangkiki, "(없음)")
        Set_Null(Columnst, DSET1.tbl_nanbangkiki, "0")

        Title = "냉방기기"
        Columns = New String() {"냉동기방식", "냉동기종류", "냉동기압축방식", _
                                "압축기제어방식", "냉동기설비시스템", _
                                "냉동기설비시스템", "제어방식", _
                                "열생산연결방식", "사용연료", "증발식건식냉각기", _
                                "증발식냉각기", "보조방음기유무", "신재생연결여부"}
        Columnst = New String() {"온수열생산기기", "연결된시스템"}
        Set_Null(Columns, DSET1.tbl_nangbangkiki, "(없음)")
        Set_Null(Columnst, DSET1.tbl_nangbangkiki, "0")


        Title = "입력면"
        Columns = New String() {"건축부위방식", "블라인드유무", _
                                "블라인드위치", "방위", "블라인드빛종류", _
                                "블라인드색상", "블라인드각도"}
        Columnst = New String() {"존분류", "대차대조존"}
        Set_Null(Columns, DSET1.tbl_myoun, "(없음)")
        Set_Null(Columnst, DSET1.tbl_myoun, "0")


        'Title = "난방공급시스템"
        'Columns = New String() {"열공급시스템", "노출형제어", "바닥난방열제어", _
        '                        "바닥난방열건축부위", "바닥난방전기제어", "바닥난방전기건축부위", "전기난방제어"}
        'Columnst = New String() {"열공급생산기기"}
        'Set_Null(Columns, DSET1.tbl_kongkub, "(없음)")
        'Set_Null(Columnst, DSET1.tbl_kongkub, "0")


        Title = "공조처리"
        Columns = New String() {"공조방식", "리턴공기혼합여부", "가습기유형", "외기냉방제어유무", "열교환기유형"}
        Set_Null(Columns, DSET1.tbl_kongjo, "(없음)")
        'Set_Null(Columnst, DSET.tbl_bunbae, "0")

        Title = "냉방분배시스템"
        Columns = New String() {"냉매방식", "펌프운전제어유무"}
        Columnst = New String() {"냉동기"}
        Set_Null(Columns, DSET1.tbl_bunbae, "(없음)")
        Set_Null(Columnst, DSET1.tbl_bunbae, "0")


        '//모든공조데이터 순환
        For Each DR As DS.tbl_kongjoRow In DSET1.tbl_kongjo.Select("code<>'0'")
            DR.팬효율산출방식 = DR.팬효율산출방식.Trim
            'MsgBox(DR.설명 & "==현재저장된값 : " & DR.팬효율산출방식 & " 길이 = " & DR.팬효율산출방식.Length)
            If DR.팬효율산출방식.Trim = "" Then DR.팬효율산출방식 = "입력치"
        Next
        'DSET.tbl_kongjo.AcceptChanges()
        DSET1.AcceptChanges()


        '//그값이 존에잇어요?cnrkehlsrp?추가된게?공조기기요
        For Each Dr As DS.tbl_zoneRow In DSET1.tbl_zone.Select("code <> '0'") '//모든존을 검사 없음(0)은 빼고
            'If Dr.공조난방생산기기 = "0" And Dr.공조냉방생산기기 = "0" Then '//둘다 0일경우
            '//오류를 내고싶으면 여기서 return false 해버리면됩니다.'다른족건이 잇다면.. 아까처럼..
            'Return False 냉난방공조 라는 공조에 냉난방이 있으면  : :
            'End If
            If Dr.냉난방공조 = "냉난방" Then '//
                If Dr.공조난방생산기기 = "0" OrElse Dr.공조냉방생산기기 = "0" Then
                    MsgBox("입력존에서 공조방식에 대응하는 공조냉난방생산기기가 지정되지 않은 것이 있습니다.")
                    Return False
                End If
            End If
            If Dr.냉난방공조 = "난방" OrElse (Dr.냉난방공조 = "냉방" And Dr.외기부하처리여부 = "예") Then '//
                If Dr.공조난방생산기기 = "0" Then
                    MsgBox("입력존에서 공조방식에 대응하는 공조난방생산기기가 지정되지 않은 것이 있습니다.")
                    Return False
                End If
            End If
            If Dr.냉난방공조 = "냉방" OrElse (Dr.냉난방공조 = "난방" And Dr.외기부하처리여부 = "예") Then '//
                If Dr.공조냉방생산기기 = "0" Then
                    MsgBox("입력존에서 공조방식에 대응하는 공조냉방생산기기가 지정되지 않은 것이 있습니다.")
                    Return False
                End If
            End If
            If Dr.냉난방공조 = "환기" And Dr.외기부하처리여부 = "예" Then '//
                If Dr.공조난방생산기기 = "0" OrElse Dr.공조냉방생산기기 = "0" Then
                    MsgBox("입력존에서 외기부하처리에 따른 공조냉난방생산기기가 지정되지 않은 것이 있습니다.")
                    Return False
                End If
            End If



        Next

        '//여기에서 FAlse 를 반환해버리면.. 게산은 돌지않아요 게산전에 수행되는곳이구요
        '//아까 파일오픈시에도 여기를 호출합니다.  바로 윗부분이 nul l값에대한 기본값 처리구요.
        Return NoErr
    End Function

    Private Sub RibbonButton17_Click_1(sender As System.Object, e As System.EventArgs) Handles RibbonButton17.Click







        '//171001 - 데이터보정
        For i As Integer = 1 To DSET1.tbl_kongjo.Rows.Count
            Dim 대수 As String = DSET1.tbl_kongjo.Rows(i - 1)("대수").ToString()
            If 대수 = "" OrElse 대수 = "0" Then
                DSET1.tbl_kongjo.Rows(i - 1)("대수") = 1
            End If
        Next
        For Each dr As DS.tbl_nanbangkikiRow In DSET1.tbl_nanbangkiki.Rows
            Dim 대수 As String = dr.보일러대수
            If 대수 = "" OrElse 대수 = "0" Then
                dr.보일러대수 = 1
            End If

            '//존에 난방에 연결되면 난방, 급탕,  난방+급탕결정
            Dim 난방연결 As Boolean = False
            Dim 급탕연결 As Boolean = False
            For Each dr2 As DS.tbl_zoneRow In DSET1.tbl_zone.Rows
                If dr2.열생산난방생산기기 <> "0" AndAlso dr2.열생산난방생산기기 = dr.code Then
                    난방연결 = True
                    'Continue For
                End If
                If dr2.열생산급탕생산기기 <> "0" AndAlso dr2.열생산급탕생산기기 = dr.code Then
                    급탕연결 = True
                    ' Continue For
                End If
            Next

            If 난방연결 AndAlso 급탕연결 Then
                dr.난방급탕구분 = "난방급탕용"
            ElseIf 난방연결 Then
                dr.난방급탕구분 = "난방용"
            ElseIf 급탕연결 Then
                dr.난방급탕구분 = "급탕용"
            End If

            If dr.펌프동력 <> "" Then
                dr.펌프동력 = TOSG(dr.펌프동력) / 1000
            End If

            If dr.열생산기기방식 = "히트펌프" Then
                dr.보일러정격출력 = dr.히트난방용량
                dr.사용연료 = dr.히트연료
                dr.정격보일러COP = dr.히트난방정격7
            ElseIf dr.열생산기기방식.StartsWith("지역난방") Then
                dr.보일러정격출력 = dr.열교환기정격출력
                dr.사용연료 = "지역난방"
            ElseIf dr.열생산기기방식 = "전기보일러" Then
                dr.사용연료 = "전기"
            End If


        Next




        For Each dr As DS.tbl_nangbangkikiRow In DSET1.tbl_nangbangkiki.Select("code <> '0'")
            Dim 대수 As String = dr.대수
            If 대수 = "" OrElse 대수 = "0" Then
                dr.대수 = 1
            End If


            dr.대수 = TOSG(dr.대수)


            If dr.냉동기방식 = "압축식" Then
                dr.사용연료 = "전기"
            ElseIf dr.냉동기방식 = "흡수식" Then
                If dr.열생산연결방식 = "직화식" Then
                    '//수정필요없음
                ElseIf dr.열생산연결방식 = "외부연결" Then
                    '//연결돈자료찾아서 연료 가져온다.
                    For Each dr3 As DS.tbl_nanbangkikiRow In DSET1.tbl_nanbangkiki.Rows
                        If dr3.code = dr.온수열생산기기 Then
                            dr.사용연료 = dr3.사용연료
                        End If
                    Next
                End If
            ElseIf dr.냉동기방식 = "압축식(LNG)" Then
                dr.사용연료 = "천연가스"
            ElseIf dr.냉동기방식 = "지역냉방" Then
                dr.사용연료 = "지역냉방"
            End If

            dr.냉각수펌프동력 = 0
            dr.냉수펌프동력 = 0

            '//냉수펌프동력(냉방분배에서 찾는다)
            For Each dr4 As DS.tbl_bunbaeRow In DSET1.tbl_bunbae.Select("code <> '0'")
                If dr.code = dr4.냉동기 Then

                    If dr4.설명.LastIndexOf("냉각수") > 0 Then
                        dr.냉각수펌프동력 = TOSG(dr4.펌프동력) / 1000
                    Else
                        dr.냉수펌프동력 = TOSG(dr4.펌프동력) / 1000
                    End If
                End If
            Next

            If dr.냉동기종류 = "실내공조시스템" Then
                dr.냉동기종류 = "히트펌프"
            End If

            If dr.냉각수펌프동력 = "" Then
                dr.냉각수펌프동력 = "0"
            End If
            If dr.냉수펌프동력 = "" Then
                dr.냉수펌프동력 = "0"
            End If

            '//냉각탑종류
            If dr.증발식건식냉각기 = "증발식" Then
                If dr.증발식냉각기 = "개방형" Then
                    dr.증발식건식냉각기 = "증발식(개방형)"
                ElseIf dr.증발식냉각기 = "폐쇄형" Then
                    dr.증발식건식냉각기 = "증발식(폐쇄형)"
                End If
            End If
        Next


        For Each dr As DS.tbl_kongjoRow In DSET1.tbl_kongjo.Select("code <> '0'")
            If dr.열회수율 <> "" AndAlso dr.열회수율 <> "0" Then
                dr.열회수율 = TOSG(dr.열회수율) * 100
            End If
            dr.열회수율_냉방 = TOSG(dr.열회수율_냉방) * 100

            If dr.설정치난방 = "20" AndAlso dr.설정치냉방 = "26" Then
                dr.공조방식 = "환기용"
            End If
        Next



        '//조명기기추가
        DSET1.tbl_light.Rows.Clear()
        For Each dr As DS.tbl_zoneRow In DSET1.tbl_zone.Select("code <> '0'")
            Dim newdr As DS.tbl_lightRow = DSET1.tbl_light.Newtbl_lightRow
            newdr.code = (DSET1.tbl_light.Rows.Count + 1).ToString("00000")
            newdr.설명 = dr.설명
            newdr.대수 = TOSG(dr.입력존의수)
            newdr.조명전력 = TOSG(dr.면적) * TOSG(dr.조명에너지부하율입력치)
            newdr.조명종류 = "형광등"
            DSET1.tbl_light.Addtbl_lightRow(newdr)
        Next
        DSET1.tbl_light.AcceptChanges()

        '//실내단말기추가
        'DSET1.tbl_danmal.Rows.Clear()
        'For Each dr As DS.tbl_kongkubRow In DSET1.tbl_kongkub.Select("code <> '0'")
        '    Dim newdr As DS.tbl_danmalRow = DSET1.tbl_danmal.Newtbl_danmalRow
        '    newdr.설명 = dr.설명
        '    newdr.대수 = TOSG(dr.팬송풍기수)
        '    newdr.전력합 = "0"
        '    newdr.용량 = "0"
        '    newdr.팬동력 = TOSG(dr.팬송풍기정격전력)
        '    DSET1.tbl_danmal.Addtbl_danmalRow(newdr)
        'Next
        'DSET1.tbl_danmal.AcceptChanges()

        '//신재생추가
        DSET1.tbl_new_energy.Clear()
        DSET1.tbl_new_light.Clear()
        DSET1.tbl_new_ground.Clear()
        DSET1.tbl_new_열병합.Clear()

        '//공용코프
        'DSET1.tbl_common_od.Clear()
        'DSET1.tbl_common_od.Merge(DSET1.tbl_common)

        Dim drDesc As DS.tbl_DescRow = DSET1.tbl_Desc.Rows(0)
        drDesc.buildm21 = "0"
        drDesc.층고 = ""
        drDesc.buildarea = "010000"



        Dim 면적합 As Double = 0
        Dim 천장고합 As Double = 0
        For Each dr As DS.tbl_zoneRow In DSET1.tbl_zone.Select("code <> '0' and code <>'(없음)'")
            면적합 += TOSG(dr.면적)
            천장고합 += TOSG(dr.천장고p) * TOSG(dr.면적)
        Next
        drDesc.천장고 = (천장고합 / 면적합).ToString("N2")


        '//입력면
        For Each dr As DS.tbl_myounRow In DSET1.tbl_myoun.Select("code <> '0'")
            If dr.열관류율2 <> "" Then
                Dim dryk() As DS.tbl_ykRow = DSET1.tbl_yk.Select("code = '" + dr.열관류율2 + "'")
                If dryk.Length = 1 Then
                    dr.열관류율 = TOSG(dryk(0).열관류율)
                End If
            End If

        Next



        For Each dr As DS.tbl_newRow In DSET1.tbl_new.Select("code <> '0'")

            If dr.기기종류 = "태양광" Then
                Dim newdr1 As DS.tbl_new_lightRow = DSET1.tbl_new_light.Newtbl_new_lightRow
                newdr1.code = dr.code
                newdr1.설명 = dr.설명
                newdr1.태양광모듈기울기 = dr.태양광모듈기울기
                newdr1.태양광모듈면적 = dr.태양광모듈면적
                newdr1.태양광모듈방위 = dr.태양광모듈방위
                newdr1.태양광모듈적용타입 = dr.태양광모듈적용타입
                newdr1.태양광모듈종류 = dr.태양광모듈종류.Replace(" ", "")
                newdr1.태양광모듈효율 = TOSG(dr.태양광모듈효율) * 100
                newdr1.태양광용량 = dr.태양광용량

                DSET1.tbl_new_light.Addtbl_new_lightRow(newdr1)

            ElseIf dr.기기종류 = "태양열" Then
                Dim newdr1 As DS.tbl_new_energyRow = DSET1.tbl_new_energy.Newtbl_new_energyRow
                newdr1.code = dr.code
                newdr1.설명 = dr.설명
                newdr1.태양열종류 = dr.태양열종류
                newdr1.태양열시스템의성능 = dr.태양열시스템의성능
                newdr1.집열기유형 = dr.집열기유형
                newdr1.집열판면적 = dr.집열판면적
                newdr1.집열판방위 = dr.집열판방위
                newdr1.집열효율 = dr.집열효율
                newdr1.솔라펌프의정격출력 = dr.솔라펌프의정격출력
                newdr1.축열탱크체적급탕 = dr.축열탱크체적급탕
                newdr1.축열탱크체적난방 = dr.축열탱크체적난방
                newdr1.축열탱크설치장소 = dr.축열탱크설치장소

                DSET1.tbl_new_energy.Addtbl_new_energyRow(newdr1)
            ElseIf dr.기기종류 = "열병합" Then
                Dim newdr1 As DS.tbl_new_열병합Row = DSET1.tbl_new_열병합.Newtbl_new_열병합Row
                newdr1.code = dr.code
                newdr1.설명 = dr.설명
                newdr1.열병합냉난방구분 = dr.열병합냉난방구분
                newdr1.열생산능력 = dr.열생산능력
                newdr1.열생산효율 = dr.열생산효율
                newdr1.발전효율 = dr.발전효율
                newdr1.열병합신재생여부 = dr.열병합신재생여부

                '//이 개체가 난방, 냉방기기에 적용되엇는지 체크한다.
                Dim 난방사용 As Boolean = False
                Dim 냉방사용 As Boolean = False

                For Each dr난방 As DS.tbl_nanbangkikiRow In DSET1.tbl_nanbangkiki.Select("code<>'0'")
                    If dr난방.연결된시스템 = dr.code Then
                        난방사용 = True
                        Exit For
                    End If
                Next

                For Each dr냉방 As DS.tbl_nangbangkikiRow In DSET1.tbl_nangbangkiki.Select("code<>'0'")
                    If dr냉방.연결된시스템 = dr.code Then
                        냉방사용 = True
                        Exit For
                    End If
                Next

                If 난방사용 AndAlso 냉방사용 Then
                    newdr1.열병합냉난방구분 = "냉난방용"
                ElseIf 난방사용 Then
                    newdr1.열병합냉난방구분 = "난방용"
                ElseIf 냉방사용 Then
                    newdr1.열병합냉난방구분 = "냉방용"
                End If


                DSET1.tbl_new_열병합.Addtbl_new_열병합Row(newdr1)
            ElseIf dr.기기종류 = "지열" Then
                Dim newdr1 As DS.tbl_new_groundRow = DSET1.tbl_new_ground.Newtbl_new_groundRow
                newdr1.code = dr.code
                newdr1.설명 = dr.설명
                newdr1.지열냉난방구분 = dr.지열냉난방구분
                newdr1.지열히트펌프용량 = dr.지열히트펌프용량
                newdr1.가동연료 = dr.가동연료
                newdr1.열성능비난방 = dr.열성능비난방
                newdr1.열성능비냉방 = dr.열성능비냉방
                newdr1.펌프용량1차 = dr.펌프용량1차

                '//이 개체가 난방, 냉방기기에 적용되엇는지 체크한다.
                Dim 난방사용 As Boolean = False
                Dim 냉방사용 As Boolean = False

                For Each dr난방 As DS.tbl_nanbangkikiRow In DSET1.tbl_nanbangkiki.Select("code<>'0'")
                    If dr난방.연결된시스템 = dr.code Then
                        난방사용 = True
                        Exit For
                    End If
                Next

                For Each dr냉방 As DS.tbl_nangbangkikiRow In DSET1.tbl_nangbangkiki.Select("code<>'0'")
                    If dr냉방.연결된시스템 = dr.code Then
                        냉방사용 = True
                        Exit For
                    End If
                Next

                If 난방사용 AndAlso 냉방사용 Then
                    newdr1.지열냉난방구분 = "냉난방용"
                ElseIf 난방사용 Then
                    newdr1.지열냉난방구분 = "난방용"
                ElseIf 냉방사용 Then
                    newdr1.지열냉난방구분 = "냉방용"
                End If
                DSET1.tbl_new_ground.Addtbl_new_groundRow(newdr1)

            End If


        Next

        '//신재생다시구성
        DSET1.tbl_new.Clear()

        '//기본 없음을 하나 추가해준다.
        DSET1.tbl_new.Rows.Add(New String() {"0", "(없음)"})
        DSET1.tbl_new.AcceptChanges()

        '//데이터를 모은다
        For Each dr As DS.tbl_new_energyRow In DSET1.tbl_new_energy.Rows
            Dim newdr As DS.tbl_newRow = DSET1.tbl_new.NewRow
            For Each c As DataColumn In DSET1.tbl_new_energy.Columns
                newdr(c.ColumnName) = dr(c.ColumnName)
            Next
            newdr.기기종류 = "태양열"
            newdr.지열냉난방구분 = newdr.태양열종류
            DSET1.tbl_new.Rows.Add(newdr)
        Next

        For Each dr As DS.tbl_new_groundRow In DSET1.tbl_new_ground.Rows
            Dim newdr As DS.tbl_newRow = DSET1.tbl_new.NewRow
            For Each c As DataColumn In DSET1.tbl_new_ground.Columns
                newdr(c.ColumnName) = dr(c.ColumnName)
            Next
            newdr.기기종류 = "지열"
            DSET1.tbl_new.Rows.Add(newdr)
        Next

        For Each dr As DS.tbl_new_lightRow In DSET1.tbl_new_light.Rows
            Dim newdr As DS.tbl_newRow = DSET1.tbl_new.NewRow
            For Each c As DataColumn In DSET1.tbl_new_light.Columns
                newdr(c.ColumnName) = dr(c.ColumnName)
            Next
            newdr.기기종류 = "태양광"
            DSET1.tbl_new.Rows.Add(newdr)
        Next


        For Each dr As DS.tbl_new_열병합Row In DSET1.tbl_new_열병합.Rows
            Dim newdr As DS.tbl_newRow = DSET1.tbl_new.NewRow
            For Each c As DataColumn In DSET1.tbl_new_열병합.Columns
                newdr(c.ColumnName) = dr(c.ColumnName)
            Next
            newdr.기기종류 = "열병합"
            DSET1.tbl_new.Rows.Add(newdr)
        Next


        DSET1.tbl_new.AcceptChanges()

    End Sub

    Dim prepath As String = ""
    Private Sub RibbonButton22_Click_1(sender As System.Object, e As System.EventArgs) Handles RibbonButton22.Click
        Dim fd As New FolderBrowserDialog
        fd.SelectedPath = prepath
        If fd.ShowDialog <> Windows.Forms.DialogResult.OK Then Return

        prepath = fd.SelectedPath

        Dim filecnt As Integer = 0
        For Each file As String In System.IO.Directory.GetFiles(fd.SelectedPath, "*.tpl", IO.SearchOption.AllDirectories)
            Dim ext As String = Open_TPL(file)


            Dim fi As New System.IO.FileInfo(file)
            Dim newfil As String = fi.Directory.FullName + "\" + fi.Name.Replace(fi.Extension, "." + ext)
            Me.Func_Save_OD(newfil, False)
            filecnt += 1
        Next

        MsgBox(filecnt.ToString() + " File")

    End Sub

    Private Sub RibbonButton23_Click_1(sender As System.Object, e As System.EventArgs) Handles RibbonButton23.Click
        If Not Prj.Opened Then
            Work_msg_timer(CLang.열린파일없음)
            Return
        End If
        Frm_V20091231_buha.ControlBox = True
        Frm_V20091231_buha.Show()
    End Sub

    Private Sub ExportCSV()
        Return

        '//모든테이블에대하여 내용을 출력
        If Prj.Opened = False Then
            MsgBox("No File")
            Return
        End If
        If MsgBox("Export CSV?", MsgBoxStyle.YesNo, "Save") <> MsgBoxResult.Yes Then Return


        Dim fi As New System.IO.FileInfo(Prj.FileName)
        Dim path As String = fi.Directory.FullName + "\" + fi.Name.Replace(fi.Extension, "")
        If System.IO.Directory.Exists(path) = False Then System.IO.Directory.CreateDirectory(path)
        For i As Integer = 1 To DSET1.Tables.Count

            Dim dt As System.Data.DataTable = DSET1.Tables(i - 1)
            Dim file As String = path + "\" + dt.TableName + ".csv"
            Dim sb As New System.Text.StringBuilder
            For Each col As System.Data.DataColumn In dt.Columns
                sb.Append("," + col.ColumnName)
            Next
            sb.AppendLine()


            For j As Integer = 1 To dt.Rows.Count
                Dim sb2 As New System.Text.StringBuilder
                For k As Integer = 1 To dt.Columns.Count
                    Dim val As String = dt.Rows(j - 1)(k - 1).ToString()
                    If dt.Columns(k - 1).ColumnName.ToLower() = "code" AndAlso val = "0" Then
                        sb2.Clear()
                        Exit For
                    Else
                        sb2.Append("," + val.Replace(",", "_"))
                    End If
                Next
                If sb2.Length > 0 Then sb.AppendLine(sb2.ToString())
            Next
            System.IO.File.WriteAllText(file, sb.ToString(), System.Text.Encoding.UTF8)
        Next
        MsgBox("ok")
        Shell("explorer " + path, AppWinStyle.NormalFocus)
    End Sub

    Private Sub RibbonButton27_Click(sender As System.Object, e As System.EventArgs) Handles RibbonButton27.Click
        If MsgBox("공용코드값(1089)을 서버로부터 가져오시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") = MsgBoxResult.Ok Then

          
            Dim dtcommon As New DS.tbl_common_odDataTable()
            Try

                Dim TaC As New DSTableAdapters.tbl_common_odTableAdapter
                TaC.Fill(dtcommon)
                dtcommon.AcceptChanges()
            Catch ex As Exception
                MsgBox("공용코드 업데이트실패" & vbCrLf & ex.Message.ToString, MsgBoxStyle.Critical, "확인")
            End Try

            For Each drow As DS.tbl_common_odRow In dtcommon
                If drow.gubun <> "1089" Then Continue For

                Dim v As Integer = CInt(drow.code)

                If v < 100 OrElse v > 136 Then Continue For

                Dim finds() As DS.tbl_common_odRow = DSET1.tbl_common_od.Select("gubun='1089' and code = '" + drow.code + "'")
                If finds Is Nothing OrElse finds.Length < 1 Then
                    Dim newdr As DS.tbl_common_odRow = DSET1.tbl_common_od.Newtbl_common_odRow()
                    newdr.gubun = drow.gubun
                    newdr.code = drow.code
                    newdr.name = drow.name
                    newdr.codename = drow.codename
                    newdr.valn1 = drow.valn1
                    newdr.EndEdit()
                    DSET1.tbl_common_od.Addtbl_common_odRow(newdr)
                End If
            Next
            DSET1.tbl_common_od.AcceptChanges()



            Work_msg("")


        End If

    End Sub

    Private Sub RibbonButton28_Click(sender As System.Object, e As System.EventArgs) Handles RibbonButton28.Click
        If MsgBox("새파일을 생성 하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") <> MsgBoxResult.Ok Then Return '//ok 안하면 빠져나가기
        Dim newfilename As New System.IO.FileInfo(".\basefile\new." + FileExt)
        If newfilename.Exists Then
            System.IO.File.Copy(newfilename.FullName, newfilename.FullName + "_bak_" + DateTime.Now.ToString("yyMMddHhmmssffff"))
        End If
        Me.Func_Save_OD(newfilename.FullName)
    End Sub
End Class