Public Class Frm_Bunbae
    Dim Init As Boolean = False
    Dim SrcDrv As DataRowView



    Public Sub New(_opentime)

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

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

    End Sub

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

    '''변경된내용을적용한다.
    Public Overrides Function AcceptChanged() As Boolean
        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

    Private Sub ShowHistory()
        Dim drv As DataRowView = Me.bs.Current
        Dim f As New Frm_History("tbl_bunbae", drv("code").ToString)
        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_bunbae"
            newdr.ovalue = oval
            newdr.nvalue = nval
            newdr.column = e.Column.ColumnName
            newdr.code = e.Row("code").ToString
            DSHistory.history.AddhistoryRow(newdr)
            DSHistory.history.AcceptChanges()
        End If
    End Sub
    Private Sub MdiMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Me.Show()
        My.Application.DoEvents()
        'Work_msg_timer("잠시만 기다려주세요")


        '//공유데이터셋에 연결한다.
        Me.bs.DataSource = DSET1

        '//냉방분배
        AddHandler DSET1.tbl_bunbae.TableNewRow, AddressOf AddNewDataRow_bunbae
        AddHandler DSET1.tbl_bunbae.ColumnChanging, AddressOf AddNewDataRow_Zone_Changed2

        '//모든컨트롤의 cTrl_enter 를 추가합니다
        BindProperty(CType(Me.SplitContainer1.Panel2.Controls, Control.ControlCollection))

        '//콤보컨트롤 바인딩
        Binding_Zone()

        Me.bs.Filter = "code <> '0'"
        Me.Init = True

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

        bs_CurrentChanged(sender, e)

        AddDebug("▲ Form Load")
    End Sub
#Region "Control_Enter"
    Private Sub BindProperty(ByVal Ctl As Control.ControlCollection)
        For Each C As Control In Ctl
            If C.Controls.Count > 1 Then
                BindProperty(C.Controls)
            Else
                If C.GetType.ToString.ToUpper.IndexOf("MYTB") <> -1 Then
                    AddHandler CType(C, MyTb).KeyDown, AddressOf TextBOx_KeyDown
                ElseIf C.GetType.ToString.ToUpper.IndexOf("MYCMB") <> -1 Then
                    AddHandler CType(C, MyCmb).KeyDown, AddressOf Cmd_KeyDown
                End If
            End If
        Next
    End Sub

    Private Sub TextBOx_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        If e.KeyCode = Keys.Enter AndAlso e.Control Then
            Try
                Dim Field As String = (CType(sender, MyTb).DataBindings.Item("text").BindingMemberInfo.BindingField)
                For Each Dr As DataRow In DT.Select(Me.bs.Filter, "")
                    Dr(Field) = CType(sender, MyTb).Text
                Next
                Work_msg_timer("모든값이 변경되었습니다", 25)
            Catch ex As Exception

            End Try

        End If
    End Sub
    Private Sub Cmd_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        If e.KeyCode = Keys.Enter AndAlso e.Control Then
            Try
                Dim Field As String = (CType(sender, MyCmb).DataBindings.Item("selectedvalue").BindingMemberInfo.BindingField)
                For Each Dr As DataRow In DT.Select(Me.bs.Filter, "")
                    Dr(Field) = CType(sender, MyCmb).SelectedValue
                Next
                Work_msg_timer("모든값이 변경되었습니다", 25)
            Catch ex As Exception

            End Try
        End If
    End Sub
#End Region
    Private Sub 냉동기ComboBox_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles 냉동기ComboBox.KeyDown
        Dim drv As DataRowView = Me.bs.Current
        If drv Is Nothing Then Return

        If e.KeyCode = Keys.V And e.Control Then
            e.Handled = True
            e.SuppressKeyPress = False
            '//클립보드붙여넣기
            Dim CB() As String = My.Computer.Clipboard.GetText.Split(CChar(vbCrLf))
            If CB.GetUpperBound(0) <> 25 Then
                MsgBox("붙여넣기가 호환되는 데이터가 아닙니다.", MsgBoxStyle.Information, "확인")
                Return
            End If

            For ii As Integer = 0 To CType(CB(0).Split(CChar(vbTab)), String()).GetUpperBound(0)
                If Me.bs.Count = 0 OrElse ii > 0 Then
                    If Me.bs.Position >= 0 AndAlso Me.bs.Position < Me.bs.Count - 1 Then
                        Me.bs.Position += 1
                    Else
                        Me.bt_add.PerformClick() '//한줄추가
                    End If
                End If

                Dim Cnt As Short = 0
                For i As Integer = 0 To CB.GetUpperBound(0)
                    Select Case i
                        Case 0
                            CType(bs.Current, DataRowView)("설명") = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 0 + 2 '//사용프로필 앞에 두개를 숫자4자로변환
                            If CB(i).Split(CChar(vbTab))(ii).Trim = "" Then
                                Me.냉동기ComboBox.SelectedIndex = 0
                            Else
                                Me.냉동기ComboBox.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                            End If
                            ' Me.냉동기ComboBox.Text = CStr(IIf(CB(i).Split(CChar(vbTab))(ii).Trim = "", "0", CB(i).Split(CChar(vbTab))(ii).Trim))
                        Case 3 + 2 '//공란
                            If CB(i).Split(CChar(vbTab))(ii).Trim = "" Then
                                Me.냉매방식ComboBox.SelectedIndex = 0
                            Else
                                Me.냉매방식ComboBox.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                            End If
                            ' Me.냉매방식ComboBox.Text = CStr(IIf(CB(i).Split(CChar(vbTab))(ii).Trim = "", "0", CB(i).Split(CChar(vbTab))(ii).Trim))
                        Case 4 + 2
                            If CB(i).Split(CChar(vbTab))(ii).Trim = "" Then
                                Me.펌프운전제어유무ComboBox.SelectedIndex = 0
                            Else
                                Me.펌프운전제어유무ComboBox.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                            End If
                            'Me.펌프운전제어유무ComboBox.Text = CStr(IIf(CB(i).Split(CChar(vbTab))(ii).Trim = "", "0", CB(i).Split(CChar(vbTab))(ii).Trim))
                        Case 5 + 2
                            Me.급수온도NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 6 + 2
                            Me.환수온도NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 7 + 2
                            Me.설정점에서의온도차NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 8 + 2
                            Me.냉매의비열NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 9 + 2
                            Me.냉매의밀도NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 10 + 2
                            Me.냉매의점도NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 11 + 2
                            Me.배관의압력손실NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 12 + 2
                            Me.개별저항비율NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 13 + 2
                            Me.펌프동력NTb1.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 15 + 2
                            Me.공급범위의길이NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 16 + 2
                            Me.공급범위의넓이NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 17 + 2
                            Me.열층의수NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 18 + 2
                            Me.층고NTb1.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 20 + 2
                            Me.생산기기압력손실NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 21 + 2
                            Me.사용기기압력손실NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                        Case 22 + 2
                            Me.제어밸브압력손실NTb.Text = CB(i).Split(CChar(vbTab))(ii).Trim
                    End Select
                Next
            Next

            Me.bs.EndEdit()
        End If
    End Sub

#Region "기본"
    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 Function GetMaxCode(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 Sub AddNewDataRow_bunbae(ByVal sender As Object, ByVal e As System.Data.DataTableNewRowEventArgs)
        e.Row.Item("code") = GetMaxCode(DSET1.tbl_bunbae)
        e.Row.Item("설명") = "신규데이터"
        e.Row.Item("sortkey") = GetNewSortKey()
    End Sub

    Private Function GetNewSortKey() As String
        AddDebug("GetNewSortKey")

        Dim drows() As DS.tbl_bunbaeRow = DSET1.tbl_bunbae.Select("code <> '0'", "sortkey desc")
        If drows.Length < 1 Then Return 1
        Dim Dr As DS.tbl_bunbaeRow = drows(0)
        Dim maxsortkey As Integer = Dr.sortkey
        Return maxsortkey + 1

    End Function

#Region "제어버튼"
    Private Sub ToolStripButton48_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_add.Click
        If Not EndEdit(Me.bs) Then Return
        Me.bs.AddNew()
        INitRow(Me.Controls)
        MdiMain.RefreshMenuList(TreeTag)
    End Sub


    Private Sub ToolStripButton49_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_Del.Click
        Dbbase.DelCrow(Me.bs, True)
        MdiMain.RefreshMenuList(TreeTag)
    End Sub

    Private Sub ToolStripButton51_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_cancel.Click
        If Not EndEdit(Me.bs) Then Return
        Data_Cancel(DSET1.tbl_profile, Nothing)
        MdiMain.RefreshMenuList(TreeTag)
    End Sub
#End Region

    Private Sub Binding_Zone()

        '//냉방분배시스템
        Dim bs_냉동기ComboBox As New BindingSource(DSET1, "tbl_nangbangkiki")
        Me.냉동기ComboBox.DataSource = bs_냉동기ComboBox
        bs_냉동기ComboBox.Sort = "code"
        냉동기ComboBox.DisplayMember = "설명"
        냉동기ComboBox.ValueMember = "code"
        Me.냉동기ComboBox.DataBindings.Add("selectedvalue", Me.bs, "냉동기")
        'AddHandler 냉동기ComboBox.KeyDown, AddressOf Cmb_DeleteVal


        Dim bs_냉매방식ComboBox As New BindingSource(DSET1, "tbl_common")
        bs_냉매방식ComboBox.Filter = "gubun='1055'"
        bs_냉매방식ComboBox.Sort = "code"
        Me.냉매방식ComboBox.DataSource = bs_냉매방식ComboBox
        냉매방식ComboBox.DisplayMember = "name"
        냉매방식ComboBox.ValueMember = "name"
        Me.냉매방식ComboBox.DataBindings.Add("selectedvalue", Me.bs, "냉매방식")
        'AddHandler 냉매방식ComboBox.KeyDown, AddressOf Cmb_DeleteVal

        Dim bs_펌프운전제어유무ComboBox As New BindingSource(DSET1, "tbl_common")
        bs_펌프운전제어유무ComboBox.Filter = "gubun='1056'"
        bs_펌프운전제어유무ComboBox.Sort = "code"
        Me.펌프운전제어유무ComboBox.DataSource = bs_펌프운전제어유무ComboBox
        펌프운전제어유무ComboBox.DisplayMember = "name"
        펌프운전제어유무ComboBox.ValueMember = "name"
        Me.펌프운전제어유무ComboBox.DataBindings.Add("selectedvalue", Me.bs, "펌프운전제어유무")
        'AddHandler 펌프운전제어유무ComboBox.KeyDown, AddressOf Cmb_DeleteVal

    End Sub
    Private Sub Frm_V20091231_Zone_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseWheel
        If e.Delta < 0 Then
            If Me.bs.Position < Me.bs.Count Then Me.bs.Position += 1
        Else
            If Me.bs.Position > 0 Then Me.bs.Position -= 1
        End If
        Me.Validate()
        My.Application.DoEvents()
    End Sub
#End Region

    Private Sub bt_Del_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles bt_Del.MouseDown
        
        If e.Button = Windows.Forms.MouseButtons.Right Then
            If MsgBox("전체삭제를 하시겠습니까?", MsgBoxStyle.Information Or MsgBoxStyle.OkCancel, "확인") = MsgBoxResult.Ok Then
                Dim dR() As DataRow = DSET1.tbl_bunbae.Select(Me.bs.Filter, "")
                For i As Integer = dR.GetUpperBound(0) To 0 Step -1
                    dR(i).Delete()
                Next

                DSET1.tbl_bunbae.AcceptChanges()
            End If
        End If
    End Sub

    Private Sub 냉매방식ComboBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 냉매방식ComboBox.SelectedIndexChanged
        Dim drv As DataRowView = Me.bs.Current
        If drv Is Nothing Then Return

        If Me.냉매방식ComboBox.SelectedIndex < 0 Then Return
        If Me.냉매방식ComboBox.Text.IndexOf("DataRow") <> -1 Then Return
        If String.IsNullOrWhiteSpace(Me.냉매방식ComboBox.Text) Then Return

        Try
            Select Case Me.냉매방식ComboBox.Text
                Case "물"
                    Me.냉매의비열NTb.Text = "4.18"
                    Me.냉매의밀도NTb.Text = "1000"
                    Me.냉매의점도NTb.Text = "1"
                Case "40%글리콜"
                    Me.냉매의비열NTb.Text = "3.5"
                    Me.냉매의밀도NTb.Text = "1070"
                    Me.냉매의점도NTb.Text = "4.4"
                Case "40%글루콜" '디비에 글루콜로 명기되어 임시로 쓰임 디비 수정시 삭제 필요
                    Me.냉매의비열NTb.Text = "3.5"
                    Me.냉매의밀도NTb.Text = "1070"
                    Me.냉매의점도NTb.Text = "4.4"
                Case "(없음)"
                    Me.냉매의비열NTb.Text = ""
                    Me.냉매의밀도NTb.Text = ""
                    Me.냉매의점도NTb.Text = ""
                Case Else
                    MsgBox("알수없는 냉매방식(" + 냉매방식ComboBox.Text + ") 입니다", MsgBoxStyle.Critical, "확인")
                    Me.냉매의비열NTb.Text = ""
                    Me.냉매의밀도NTb.Text = ""
                    Me.냉매의점도NTb.Text = ""
            End Select
            bs.EndEdit()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "확인")
        End Try
    End Sub

    Private Sub 급수온도NTb_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles 급수온도NTb.TextChanged
        Dim drv As DataRowView = Me.bs.Current
        If drv Is Nothing Then Return

        Try
            Me.설정점에서의온도차NTb.Text = TOST(TOSG(Me.환수온도NTb.Text) - TOSG(Me.급수온도NTb.Text))
        Catch ex As Exception

        End Try

    End Sub

    Private Sub 환수온도NTb_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles 환수온도NTb.TextChanged
        Dim drv As DataRowView = Me.bs.Current
        If drv Is Nothing Then Return

        Try
            Me.설정점에서의온도차NTb.Text = TOST(TOSG(Me.환수온도NTb.Text) - TOSG(Me.급수온도NTb.Text))
        Catch ex As Exception

        End Try

    End Sub


    Private Sub dv_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles dv.MouseUp
        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.08 추가
            If e.Button = Windows.Forms.MouseButtons.Right Then
                Dim Frm_FilterA As New Frm_Filter
                Frm_FilterA.ColumTitle = getColCaption(Me.DT)
                Frm_FilterA.ColumList = getColName(Me.DT)
                Frm_FilterA.Colorlist = "냉동기"
                Frm_FilterA.Numfield = ""    '//20100618  Color 리스트처럼 , 구분해서 필드들을 모두 넣으세요.
                Frm_FilterA.Default_Filter = "code <> '0'"

                If Frm_FilterA.ShowDialog <> Windows.Forms.DialogResult.OK Then Return '//창떳을떄 확인아ㅣ고 취소눌르면 다음을 수행하지않는다는거에요.
                Dim Filter As String = Frm_FilterA.tb_filter.Text   '//값은 아까 그 텍박에 잇구요.
                Try
                    Me.bs.Filter = Filter

                    '//바꾸기값이 있으면 변경 20100618
                    If Frm_FilterA.cmb_fieldc.SelectedIndex >= 0 AndAlso Frm_FilterA.cmb_fieldc.Text.ToLower <> "code" AndAlso _
                    Frm_FilterA.tb_valuec.Text <> "" Then
                        Dim Drow() As DataRow = Me.DT.Select(Filter)
                        For Each Dr As DataRow In Drow
                            Dr(Frm_FilterA.cmb_fieldc.Text) = Frm_FilterA.tb_valuec.Text
                        Next
                        MsgBox("바꾸기 완료", MsgBoxStyle.Information, "확인")
                    End If

                Catch ex As Exception
                    Me.bs.Filter = ""
                End Try
            End If
        End If
    End Sub

    Private Sub dv_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dv.KeyDown
        '//여기보시면   alt+d 누르면  한줄을 경고없이(falsE)삭제하도록 햇어요.. 사실원래 밋alt +d 인데.. ㅎㅎ 잘못해서 ctrl 됫다는
        If Prj.UserAuthType = "ADMIN" OrElse Prj.UserAuthType = "BOTH" OrElse Prj.UserAuthType = "BOTH2" OrElse Prj.UserAuthType = "BOTH1" Then  '//2011.03.08 추가
            Select Case e.KeyCode
                Case Keys.D
                    If e.Alt Then
                        Dbbase.DelCrow(Me.bs, False)
                    End If
                Case Keys.C
                    If e.Control Then
                        Me.SrcDrv = Me.bs.Current
                        If Me.SrcDrv Is Nothing Then
                            MsgBox("저장할 ROW가 없습니다", MsgBoxStyle.Information, "확인")
                            Return
                        End If
                        ' My.Computer.Clipboard.SetData("ZDATA", Drv)
                    End If
                Case Keys.V
                    If e.Control Then
                        If Me.SrcDrv Is Nothing Then Return
                        Me.bt_add.PerformClick()  '//신규추가
                        Dim NewDrv As DataRowView = Me.bs.Current

                        For Each C As DataColumn In Me.DT.Columns
                            If C.ColumnName.ToUpper = "CODE" Then
                            ElseIf C.ColumnName.ToUpper = "설명" Then
                                NewDrv(C.ColumnName) = SrcDrv(C.ColumnName) & "#1"
                            Else
                                NewDrv(C.ColumnName) = SrcDrv(C.ColumnName)
                            End If
                        Next
                        Me.bs.EndEdit()
                        bs.MoveLast()
                    End If
            End Select
        End If
    End Sub

    Private Sub bs_CurrentChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bs.CurrentChanged
        If Not Init Then Return
        Dim drv As DataRowView = Me.bs.Current
        If drv Is Nothing Then Return
        Me.lb_code.Text = "[" + drv("code").ToString + "]"
        Me.bs.EndEdit()
    End Sub

    Private Sub SplitContainer1_Panel2_Paint(sender As System.Object, e As System.Windows.Forms.PaintEventArgs) Handles SplitContainer1.Panel2.Paint

    End Sub

    Private Sub dv_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dv.CellContentClick

    End Sub

    Private Sub Frm_Bunbae_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        Select Case e.KeyCode
            Case Keys.F12
                ShowHistory()
        End Select
    End Sub
End Class