Public Class Frm_Desc
#Region "data Base 변경여부및 적용방법"

    '''변경된내용을적용한다.
    Public Overrides Function AcceptChanged() As Boolean

        Dim drv As DataRowView = bs.Current
        If drv Is Nothing Then Return True



        bs.EndEdit()
        Dim BaseDS As DataSet = CType(bs.DataSource, DataSet)
        Dim BaseDT As DataTable = BaseDS.Tables(bs.DataMember)
        BaseDT.AcceptChanges()
        Return True
    End Function

    '''변경된내용이있다면 취소한다.
    Public Overrides Function RejectChanged() As Boolean
        Dim BaseDS As DataSet = CType(bs.DataSource, DataSet)
        Dim BaseDT As DataTable = BaseDS.Tables(bs.DataMember)
        BaseDT.RejectChanges()
        Return True
    End Function

    '''데이터에변형이있었는가?
    Public Overrides Function HasChanged() As Boolean
        bs.EndEdit()
        Dim BaseDS As DataSet = CType(bs.DataSource, DataSet)
        Dim BaseDT As DataTable = BaseDS.Tables(bs.DataMember)
        Dim ChangeDT As DataTable = BaseDT.GetChanges
        If Not ChangeDT Is Nothing Then Return True
        Return False
    End Function

    '''기본데이터테이블을 반환합니다.
    Public Function DT() As DataTable
        Dim BaseDS As DataSet = CType(bs.DataSource, DataSet)
        Return BaseDS.Tables(bs.DataMember)
    End Function


#End Region

    Dim DT지역중분류 As DataTable
    Dim init As Boolean = False
    Dim 변경암함_세부지역 As Boolean = False

    Public Sub New(_opentime)

        ' 이 호출은 디자이너에 필요합니다.
        InitializeComponent()
        OpenTime = _opentime

        ' InitializeComponent() 호출 뒤에 초기화 코드를 추가하십시오.

    End Sub
    Private Sub MdiMain_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        CEnergy.ARINCLASS.SaveLoad_FrmSetting(Me, Me.bs.Position, True)
    End Sub
    Private Sub ShowHistory()
        Dim drv As DataRowView = Me.bs.Current
        Dim f As New Frm_History("tbl_Desc", "")
        If f.ShowDialog = DialogResult.OK Then
            drv(f.colname) = f.val
            Me.Validate()
            Me.bs.EndEdit()
            My.Application.DoEvents()
            MsgBox("값이 변경되었습니다", MsgBoxStyle.Information, "확인")
        End If
    End Sub
    Private Sub AddNewDataRow_Zone_Changed2(ByVal sender As Object, ByVal e As System.Data.DataColumnChangeEventArgs)
        Dim oval As String = e.Row(e.Column.ColumnName).ToString
        Dim nval As String = e.ProposedValue.ToString
        If oval <> nval Then
            Dim newdr As DS2.historyRow = DSHistory.history.NewhistoryRow
            newdr.time = Now.ToString("yyyy-MM-dd HH:mm:ss")
            newdr.tablename = "tbl_Desc"
            newdr.ovalue = oval
            newdr.nvalue = nval
            newdr.column = e.Column.ColumnName
            newdr.code = ""
            DSHistory.history.AddhistoryRow(newdr)
            DSHistory.history.AcceptChanges()
        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.F12
                ShowHistory()
        End Select
    End Sub

    'Sub AttachAreaBind()
    '    '//지역중분류값을 업데이트한다
    '    bsArea1.DataSource = DSET1
    '    bsArea1.DataMember = "weather_group"
    '    bsArea2.DataSource = DSET1
    '    bsArea2.DataMember = "weather_group"

    '    cmbArea1.DataSource = bsArea1
    '    cmbArea2.DataSource = bsArea2

    '    cmbArea1.DisplayMember = "name"
    '    cmbArea1.ValueMember = "code"
    '    'bsArea1.Filter = "code like '%0000'"

    '    cmbArea2.DisplayMember = "name"
    '    cmbArea2.ValueMember = "code"
    '    'bsArea2.Filter = "code ='test'"
    'End Sub

    Private Sub MdiMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        init = False

        Me.Show()
        My.Application.DoEvents()


        '//지역중분류값을 업데이트한다
        bsArea1.DataSource = DSET1
        bsArea1.DataMember = "weather_group"
        bsArea2.DataSource = DSET1
        bsArea2.DataMember = "weather_group"

        'Read_WeatherFile()

        Me.LinkLabel1.Visible = False
        Me.LinkLabel2.Visible = False
        Me.LinkLabel3.Visible = False

        'MdiMain.Toggle_Menu_Color(MdiMain.E_MenuIdx.건물개요)
        'CEnergy.ARINCLASS.SaveLoad_FrmSetting(Me)
        '//프로필 관련

        '//공유데이터셋에 연결한다.
        Me.bs.DataSource = DSET1
        If Me.bs.Count = 0 Then bs.AddNew()
        bs.EndEdit()

        '//Zone
        Binding_Zone()
        init = True

        Try
            Me.bs.Position = CEnergy.ARINCLASS.Read_LastPos_Frm(Me)
        Catch ex As Exception
            Me.bs.MoveFirst()
        End Try

        Dim drDesc As DS.tbl_DescRow = DSET1.tbl_Desc.Rows(0)
        btArea.Text = GetAreaName(drDesc.buildarea)

        If Not (Prj.UserId.ToLower() = "guest" OrElse Prj.UserId.ToLower().StartsWith("user") OrElse Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1") Then  '//2011.03.08 추가
            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("C")   '//버젼을 가져오는데  eco 버젼만 가져오게 바꺼야겟죵 ^^ 구분자를 넣도록 합시닷!
                If VersionInfo.Ver <> "0" AndAlso (CInt(VersionInfo.Ver) > CInt(MyVersion)) Then   '//0은 없거나 관리안함의 뜻이므로 넘어간다.
                    ' Dim Lc As String = Me.cmbArea2.SelectedValue
                    Read_CommonCode()
                    'Me.cmbArea2.SelectedValue = Lc
                    Me.bs.EndEdit()
                End If
            Catch ex As Exception
                MsgBox("공용코드 에러" & ex.Message.ToString)
            End Try

            '/표준프로파일버젼확인 '//2010.12.06 추가
            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("P")   '//버젼을 가져오는데  eco 버젼만 가져오게 바꺼야겟죵 ^^ 구분자를 넣도록 합시닷!
                If VersionInfo.Ver <> "0" AndAlso (CInt(VersionInfo.Ver) > CInt(MyVersion)) Then   '//0은 없거나 관리안함의 뜻이므로 넘어간다.
                    'Dim Lp As String = Me.cmbArea2.SelectedValue
                    Read_ProfileData()
                    'Me.cmbArea2.SelectedValue = Lp
                    Me.bs.EndEdit()
                End If
            Catch ex As Exception
                MsgBox("표준프로파일 에러" & ex.Message.ToString)
            End Try

            '/기상데이터버젼확인 
            '/기상데이터는 로컬파일을 사용하도록 한다 200816
            '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 Lw As String = Me.cmbArea2.SelectedValue
            '        Read_WeatherData()
            '        'Me.cmbArea2.SelectedValue = Lw
            '        Me.bs.EndEdit()
            '    End If
            'Catch ex As Exception

            'End Try



        Else
            If Not Prj.UserId.ToLower() = "guest" Then
                '//서버업데이트기능 숨김
                Me.LinkLabel1.Visible = True
                'Me.LinkLabel2.Visible = True
                Me.LinkLabel3.Visible = True
            End If
        End If

        '지역코드설정()


        AddHandler DSET1.tbl_Desc.ColumnChanging, AddressOf AddNewDataRow_Zone_Changed2

        AddDebug("▲ Form Load")
    End Sub


    Private Sub Binding_Zone()
        Dim bs_cmb_공조방식 As New BindingSource(DSET1, "tbl_weather")
        bs_cmb_공조방식.Filter = ""
        'Me.cmbArea2.DataSource = bs_cmb_공조방식
        'cmbArea2.DisplayMember = "건물위치"
        'cmbArea2.ValueMember = "code"
        'Me.cmbArea2.DataBindings.Add("selectedvalue", Me.bs, "buildarea")

        Dim bs_cmb_인증기관 As New BindingSource(DSET1, "tbl_common")
        bs_cmb_인증기관.Filter = "gubun='1100'"
        bs_cmb_인증기관.Sort = "code"
        cmb_인증기관.DataSource = bs_cmb_인증기관
        cmb_인증기관.DisplayMember = "name"
        cmb_인증기관.ValueMember = "name"
        Me.cmb_인증기관.DataBindings.Add("selectedvalue", Me.bs, "인증기관")


        Dim bs_cmb_건물용도 As New BindingSource(DSET1, "tbl_common")
        bs_cmb_건물용도.Filter = "gubun='1201'"
        bs_cmb_건물용도.Sort = "code"
        cmb_주거용건축물.DataSource = bs_cmb_건물용도
        cmb_주거용건축물.DisplayMember = "name"
        cmb_주거용건축물.ValueMember = "valn1"
        Me.cmb_주거용건축물.DataBindings.Add("selectedvalue", Me.bs, "isjugo")

        'Dim DT주거용 As New DataTable
        'DT주거용.Columns.Add("name")
        'DT주거용.Columns.Add("value")
        'DT주거용.Rows.Add(New String() {"주거용건축물(단독주택)", "1"})
        'DT주거용.Rows.Add(New String() {"주거용건축물(공동주택)", "2"})
        'DT주거용.Rows.Add(New String() {"비주거용(제1종근린생활시설)", "11"})
        'DT주거용.Rows.Add(New String() {"비주거용(제2종근린생활시설)", "12"})
        'DT주거용.Rows.Add(New String() {"비주거용(문화및집회시설)", "13"})
        'DT주거용.Rows.Add(New String() {"비주거용(종교시설)", "14"})
        'DT주거용.Rows.Add(New String() {"비주거용(판매시설)", "15"})
        'DT주거용.Rows.Add(New String() {"비주거용(의료시설)", "16"})
        'DT주거용.Rows.Add(New String() {"비주거용(교육연구시설)", "17"})
        'DT주거용.Rows.Add(New String() {"비주거용(노유자시설)", "18"})
        'DT주거용.Rows.Add(New String() {"비주거용(수련시설)", "19"})
        'DT주거용.Rows.Add(New String() {"비주거용(운동시설)", "20"})
        'DT주거용.Rows.Add(New String() {"비주거용(업무시설)", "21"})
        'DT주거용.Rows.Add(New String() {"비주거용(숙박시설)", "22"})
        'DT주거용.Rows.Add(New String() {"비주거용(위락시설)", "23"})
        'DT주거용.Rows.Add(New String() {"비주거용(고장물품제조가공이용시설)", "24"})
        'DT주거용.Rows.Add(New String() {"비주거용(창고시설)", "25"})
        'DT주거용.Rows.Add(New String() {"비주거용(위험물처리장)", "26"})
        'DT주거용.Rows.Add(New String() {"비주거용(자동차관리시설)", "27"})
        'DT주거용.Rows.Add(New String() {"비주거용(동물및식물관련시설)", "28"})
        'DT주거용.Rows.Add(New String() {"비주거용(분뇨및쓰레기처리시설)", "29"})
        'DT주거용.Rows.Add(New String() {"비주거용(교정및군사시설)", "30"})
        'DT주거용.Rows.Add(New String() {"비주거용(방송통신시설)", "31"})
        'DT주거용.Rows.Add(New String() {"비주거용(발전시설발전소)", "32"})
        'DT주거용.Rows.Add(New String() {"비주거용(묘지관리시설)", "33"})
        'DT주거용.Rows.Add(New String() {"비주거용(관광휴계시설)", "34"})
        'DT주거용.Rows.Add(New String() {"비주거용(장례식장)", "35"})

        'Me.cmb_주거용건축물.DataSource = DT주거용
        'Me.cmb_주거용건축물.DisplayMember = "name"
        'Me.cmb_주거용건축물.ValueMember = "value"
        'Me.cmb_주거용건축물.DataBindings.Add("selectedvalue", Me.bs, "isjugo")

        'AddHandler cmb_location.KeyDown, AddressOf Cmb_DeleteVal
    End Sub


    Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        ' Dim L As String = Me.cmbArea2.SelectedValue
        If MsgBox("공용코드값을 서버로부터 가져오시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") = MsgBoxResult.Ok Then Read_CommonCode()
        ' Me.cmbArea2.SelectedValue = L
        Me.bs.EndEdit()
    End Sub

    Private Sub LinkLabel2_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel2.LinkClicked
        'Dim L As String = Me.cmbArea2.SelectedValue
        If MsgBox("기상데이터값을 서버로부터 가져오시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") = MsgBoxResult.Ok Then Read_WeatherData()
        ' AttachAreaBind()
        ' Me.cmbArea2.SelectedValue = L
        Me.bs.EndEdit()
    End Sub
    Private Sub LinkLabel3_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel3.LinkClicked '//2010.12.06 추가
        ' Dim L As String = Me.cmbArea2.SelectedValue
        If MsgBox("표준프로파일값을 서버로부터 가져오시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") = MsgBoxResult.Ok Then Read_ProfileData()
        '  Me.cmbArea2.SelectedValue = L
        Me.bs.EndEdit()
    End Sub

    Private Sub bs_CurrentChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bs.CurrentChanged
        Me.bs.EndEdit()
        Dim drv As DataRowView = Me.bs.Current
        If drv Is Nothing Then Return
        If drv("공공").ToString = "" Then drv("공공") = "1"
        If drv("공공").ToString = "1" Then
            Me.CheckBox1.Checked = True
        Else
            Me.CheckBox1.Checked = False
        End If
    End Sub

    Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker1.ValueChanged, DateTimePicker2.ValueChanged
        '//준공이후 경과년수계산
        Dim datetime1 As String = Format(Me.DateTimePicker1.Value, "yyyy")
        Dim datetime2 As String = Format(Me.DateTimePicker2.Value, "yyyy")
        Dim datetime3 As String = Format(Me.DateTimePicker1.Value, "MM")
        Dim datetime4 As String = Format(Me.DateTimePicker2.Value, "MM")
        Dim priod As Single
        Try
            If TOSG(datetime3) - TOSG(datetime4) >= 0 Then
                priod = Math.Round(TOSG(datetime1) - TOSG(datetime2) + (TOSG(datetime3) - TOSG(datetime4)) / 12, 1)
            Else
                priod = Math.Round(TOSG(datetime1) - TOSG(datetime2) - (TOSG(datetime4) - TOSG(datetime3)) / 12, 1)
            End If

        Catch ex As Exception
            priod = 0
        End Try
        If priod < 0 Then priod = 0
        MyTb6.Text = CStr(priod)
        Me.bs.EndEdit()
    End Sub



    Private Sub CheckBox1_Click(sender As Object, e As System.EventArgs) Handles CheckBox1.Click
        Dim drv As DataRowView = Me.bs.Current
        If drv Is Nothing Then Return
        drv("공공") = IIf(Me.CheckBox1.Checked, "1", "0")
    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox1.CheckedChanged

    End Sub

    'Private Sub 지역코드설정()
    '    Dim drv As DataRowView = Me.bs.Current
    '    If drv Is Nothing Then Return

    '    '//지역코드에는 Weather_Group의 코드값이 들어있다.
    '    Dim 지역코드 As String = drv("buildarea").ToString
    '    If 지역코드 <> "" AndAlso 지역코드 <> "0" AndAlso 지역코드 <> "00" AndAlso 지역코드.Length = 6 Then

    '        변경암함_세부지역 = True

    '        '//Dep 1
    '        Dim codeHeader As String = 지역코드.Substring(0, 2)
    '        bsArea2.Filter = String.Format("code like '{0}%' and code not like '%0000' and code like '%00'", codeHeader)
    '        Me.cmbArea1.SelectedValue = codeHeader + "0000"   '//선택해줌   

    '        codeHeader = 지역코드.Substring(0, 4)
    '        'bsArea3.Filter = String.Format("code like '{0}%' and code not like '%00'", codeHeader)
    '        Me.cmbArea2.SelectedValue = codeHeader + "00"

    '        'Me.cmbArea3.SelectedValue = 지역코드

    '        '//찾은 중분류코드에맞는 중분류를 자동 선택해준다.
    '        변경암함_세부지역 = False
    '    Else
    '        bsArea1.Filter = "code like '%0000'"
    '        bsArea2.Filter = "code='test'"
    '        'bsArea3.Filter = "code='test'"
    '    End If
    'End Sub

    'Private Sub cmbArea1_SelectedIndexChanged(sender As Object, e As EventArgs)
    '    If init = False Then Return '//초기화전이면 수행안함
    '    Dim drv As DataRowView = Me.bs.Current
    '    If drv Is Nothing Then Return


    '    '//지역그룹선택을 바꾼다면 해당 지역에 맞도록 우측을 갱신해줘야한다
    '    If 변경암함_세부지역 Then Return '//순환참조방지
    '    If Me.cmbArea1.SelectedIndex < 0 OrElse cmbArea1.Text = "없음" OrElse cmbArea1.SelectedValue.ToString() = "00" Then
    '        Me.cmbArea2.SelectedIndex = -1
    '    Else
    '        Dim codeHeader As String = cmbArea1.SelectedValue.ToString().Substring(0, 2)
    '        bsArea2.Filter = String.Format("code like '{0}%' and code not like '%0000' and code like '%00'", codeHeader)

    '        cmbArea2.DataSource = bsArea2
    '        cmbArea2.DisplayMember = "name"
    '        cmbArea2.ValueMember = "code"

    '        If (cmbArea2.Items.Count > 0) Then
    '            cmbArea2.SelectedIndex = 0
    '        Else
    '            cmbArea2.SelectedIndex = -1
    '        End If

    '        If cmbArea1.SelectedIndex >= 0 Then
    '            drv("buildarea") = cmbArea1.SelectedValue.ToString()
    '            drv.EndEdit()
    '        End If

    '    End If
    'End Sub

    'Private Sub CmbArea2_SelectedIndexChanged_1(sender As System.Object, e As System.EventArgs)
    '    If init = False Then Return '//초기화전이면 수행안함
    '    Dim drv As DataRowView = Me.bs.Current
    '    If drv Is Nothing Then Return

    '    '//지역그룹선택을 바꾼다면 해당 지역에 맞도록 우측을 갱신해줘야한다
    '    If 변경암함_세부지역 Then Return '//순환참조방지
    '    If Me.cmbArea2.SelectedIndex < 0 OrElse cmbArea2.Text = "없음" OrElse cmbArea2.SelectedValue.ToString() = "00" Then
    '        'Me.cmbArea3.SelectedIndex = -1
    '    Else
    '        Dim codeHeader As String = cmbArea2.SelectedValue.ToString().Substring(0, 4)
    '        'bsArea3.Filter = String.Format("code like '{0}%' and code not like '%00'", codeHeader)
    '        'cmbArea3.SelectedIndex = -1

    '        If cmbArea2.SelectedIndex >= 0 Then
    '            drv("buildarea") = cmbArea2.SelectedValue.ToString()
    '            drv.EndEdit()
    '        End If

    '    End If
    'End Sub

    Private Sub Label41_Click(sender As Object, e As EventArgs) Handles Label41.Click

    End Sub

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

    End Sub

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

    End Sub

    Function GetAreaName(code As String)
        If String.IsNullOrEmpty(code) OrElse code.Length <> 6 Then Return code
        Dim Grp1 As String = code.Substring(0, 2)

        '//그룹 이름 찾기
        Dim GrpName As String = String.Empty
        Dim CodeName As String = String.Empty

        Dim GrpCode As String = Grp1 + "0000"
        Dim GrpList() As DS.weather_groupRow = DSET1.weather_group.Select("code='" + GrpCode + "'")
        If GrpList Is Nothing OrElse GrpList.Length = 1 Then
            GrpName = GrpList(0).name
        End If

        GrpList = DSET1.weather_group.Select("code='" + code + "'")
        If GrpList Is Nothing OrElse GrpList.Length = 1 Then
            CodeName = GrpList(0).name
        End If

        If CodeName = String.Empty Then
            Return code
        Else
            Return GrpName + " > " + CodeName
        End If

    End Function

    Private Sub btArea_Click(sender As Object, e As EventArgs) Handles btArea.Click
        Dim PreCode As String = String.Empty
        Dim dr As DS.tbl_DescRow = Nothing
        If DSET1.tbl_Desc.Rows.Count = 1 Then
            dr = DSET1.tbl_Desc.Rows(0)
            PreCode = dr.buildarea
        End If
        Dim f As New fSelectWeatherGroup(PreCode)
        If f.ShowDialog() = DialogResult.OK Then
            If Not dr Is Nothing Then
                btArea.Text = GetAreaName(f.SelectedCode)
                dr.buildarea = f.SelectedCode
                dr.EndEdit()
            End If
        End If
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Read_CommonCode()
        Read_ProfileData()
    End Sub
End Class