Imports DevExpress.Utils
Imports DevExpress.XtraBars.Navigation
Imports DevExpress.XtraEditors
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Views.Tile

Public Class frmConstructor_Main

    Public CONSTRUCTORID As Integer
    Public DT_CONSTRUCT_VIEW As DataTable
    Public EBENE2_PARENT_ID As Integer
    Public EBENE3_PARENT_ID As Integer
    Public ACT_EBENE As Integer
    Public ACT_EBENE_STRING
    Public SelectedRecordID As Integer
    Public PARENT_RECORDID As Integer

    Public EBENE1_ENTITY
    Public EBENE2_ENTITY
    Public EBENE3_ENTITY
    Public EBENE1_COLUMNNAME
    Public EBENE2_COLUMNNAME
    Public EBENE3_COLUMNNAME
    Public EBENE1_RECID
    Public EBENE2_RECID
    Public EBENE3_RECID
    Public EBENE1_GRID_RESULT
    Public EBENE2_GRID_RESULT
    Public EBENE3_GRID_RESULT
    Public act_FormViewID
    Public DT_SELECTION
    Public EBENE_SQLRESULT
    Public EDIT_STATE As EditState = EditState.None
    Public GRID_TYPE As GridType = GridType.Carousel

    Public Enum EditState
        None
        Insert
        Update
    End Enum

    Public Enum GridType
        Grid
        Carousel
    End Enum

    Private Sub XtraForm2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: Diese Codezeile lädt Daten in die Tabelle "DD_ECMAdmin.VWTEMPQUICKVIEW". Sie können sie bei Bedarf verschieben oder entfernen.
        VWTEMPQUICKVIEWTableAdapter.Connection.ConnectionString = MyConnectionString
        Me.VWTEMPQUICKVIEWTableAdapter.Fill(Me.DD_ECMAdmin.VWTEMPQUICKVIEW)

        CONSTRUCTORID = CURRENT_CONSTRUCTOR_ID
        DT_CONSTRUCT_VIEW = ClassDatabase.Return_Datatable("SELECT * FROM TBPMO_FORM_CONSTRUCTOR WHERE GUID = " & CONSTRUCTORID)


        Init_Grid_Control()

        'Load_Tree_View()
        Load_Tree_View(CONSTRUCTORID)
    End Sub

#Region "NavPane"


    Private Function FindNode(tncoll As TreeNodeCollection, strText As [String]) As TreeNode
        Dim tnFound As TreeNode
        For Each tnCurr As TreeNode In tncoll
            If tnCurr.Text.StartsWith(strText) Then
                Return tnCurr
            End If
            tnFound = FindNode(tnCurr.Nodes, strText)
            If tnFound IsNot Nothing Then
                Return tnFound
            End If
        Next
        Return Nothing
    End Function


    Private Sub navPane_MouseUp(sender As Object, e As MouseEventArgs) Handles navPane.MouseUp
        Dim pane As TileNavPane = TryCast(sender, TileNavPane)
        Dim hitInfo As TileNavPaneHitInfo = pane.ViewInfo.CalcHitInfo(e.Location)
        If hitInfo.InButton Then
            Dim element = hitInfo.ButtonInfo.Element
            navPane.HideDropDownWindow()

            If TypeOf element Is NavButton Then
                Dim btn As NavButton = TryCast(element, NavButton)

                If btn.IsMain Then ResetNav()
            Else
                Dim Entity As String = element.Tag
                Dim Node = FindNode(TreeViewLevelSelect.Nodes, Entity)

                If Node IsNot Nothing Then
                    TreeViewLevelSelect.SelectedNode = Node
                    Load_Tree_View_Data()
                End If
            End If

        End If
    End Sub

    Private Sub ResetNav()
        ' Grid zurücksetzen
        Clear_Grid_View()

        ' Navigation zurücksetzen
        navPane.Categories.Clear()
        ' TreeView zurücksetzen
        'Load_Tree_View(CONSTRUCTORID)
        TreeViewLevelSelect.SelectedNode = Nothing
    End Sub

    Private Function LoadLevel1Nav()
        Dim cat As New TileNavCategory()
        cat.Caption = EBENE1_GRID_RESULT
        cat.Name = EBENE1_GRID_RESULT
        cat.TileText = EBENE1_GRID_RESULT
        cat.Tag = EBENE1_ENTITY

        navPane.SelectedElement = cat

        Return cat
    End Function

    Private Function LoadLevel2Nav()
        Dim item As New TileNavItem()
        item.Caption = EBENE2_GRID_RESULT
        item.Name = EBENE2_GRID_RESULT
        item.TileText = EBENE2_GRID_RESULT
        item.Tag = EBENE2_ENTITY

        navPane.SelectedElement = item

        Return item
    End Function

    Private Function LoadLevel3Nav()
        Dim subitem As New TileNavSubItem()
        subitem.Caption = EBENE3_GRID_RESULT
        subitem.Name = EBENE3_GRID_RESULT
        subitem.TileText = EBENE3_GRID_RESULT
        subitem.Tag = EBENE3_ENTITY

        navPane.SelectedElement = subitem

        Return subitem
    End Function

#End Region

#Region "TreeView"

    Sub Load_Tree_View(ConstructorId As Integer)

        Dim LEVEL1_NODE As TreeNode
        Dim LEVEL2_NODE As TreeNode
        Dim LEVEL3_NODE As TreeNode
        Dim SQL As String
        Dim DT, DT2, DT3 As DataTable

        ' Daten für Level1 Nodes Laden
        SQL = "SELECT * from VWPMO_CONSTRUCTOR_FORMS WHERE PARENT_ID = 0 AND CONSTRUCT_ID = " & ConstructorId & " ORDER BY SEQUENCE"
        DT = ClassDatabase.Return_Datatable(SQL)

        If DT Is Nothing Then
            Exit Sub
        End If

        If DT.Rows.Count = 1 Then
            Dim LEVEL1_TITLE = DT.Rows(0).Item("FORM_TITLE").ToString
            Dim LEVEL1_ID = DT.Rows(0).Item("FORM_ID").ToString

            ' Rootnode erstellen und taggen
            LEVEL1_NODE = New TreeNode(LEVEL1_TITLE)
            LEVEL1_NODE.Tag = LEVEL1_ID

            ' TreeView leeren und Rootnode einfügen
            TreeViewLevelSelect.Nodes.Clear()
            TreeViewLevelSelect.Nodes.Add(LEVEL1_NODE)

            ' Daten für Level2 Nodes Laden
            SQL = String.Format("SELECT * from VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0} AND PARENT_ID = {1} ORDER BY SEQUENCE", ConstructorId, LEVEL1_ID)
            DT2 = ClassDatabase.Return_Datatable(SQL)

            If DT2 Is Nothing Or DT2.Rows.Count = 0 Then
                Exit Sub
            End If

            For Each row As DataRow In DT2.Rows
                Dim LEVEL2_TITLE As String = row.Item("FORM_TITLE").ToString
                Dim LEVEL2_ID As Integer = row.Item("FORM_ID")
                Dim LEVEL2_PARENT_ID As Integer = row.Item("PARENT_ID")

                ' Node erstellen..
                LEVEL2_NODE = New TreeNode(LEVEL2_TITLE)
                LEVEL2_NODE.Tag = LEVEL2_ID
                ' ..und einfügen
                LEVEL1_NODE.Nodes.Add(LEVEL2_NODE)

                ' Daten für Level3 Nodes laden
                SQL = String.Format("SELECT * from VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0} AND PARENT_ID = {1} ORDER BY SEQUENCE", ConstructorId, LEVEL2_ID)
                DT3 = ClassDatabase.Return_Datatable(SQL)

                If DT3 Is Nothing Or DT3.Rows.Count = 0 Then
                    Exit Sub
                End If

                For Each subrow As DataRow In DT3.Rows
                    Dim LEVEL3_TITLE As String = subrow.Item("FORM_TITLE")
                    Dim LEVEL3_ID As Integer = subrow.Item("FORM_ID")

                    ' Node erstellen..
                    LEVEL3_NODE = New TreeNode(LEVEL3_TITLE)
                    LEVEL3_NODE.Tag = LEVEL3_ID
                    ' ..und einfügen
                    LEVEL2_NODE.Nodes.Add(LEVEL3_NODE)
                Next

            Next

            TreeViewLevelSelect.ExpandAll()
            TreeViewLevelSelect.Nodes(0).EnsureVisible()
        End If

    End Sub


    Sub Load_Tree_View_Data()
        Dim SelectedNode As TreeNode = TryCast(TreeViewLevelSelect.SelectedNode, TreeNode)
        Dim FormId As Integer = SelectedNode.Tag

        If SelectedNode IsNot Nothing Then
            Dim parentNode As TreeNode = TryCast(SelectedNode.Parent, TreeNode)

            ACT_EBENE = 2

            If parentNode IsNot Nothing Then
                Dim grandParentNode As TreeNode = TryCast(parentNode.Parent, TreeNode)

                If grandParentNode IsNot Nothing Then
                    ACT_EBENE = 3
                End If
            Else
                ACT_EBENE = 1
            End If

            Load_Entity_Data(FormId, ACT_EBENE)
        End If
    End Sub
#End Region

#Region "GridControl"


    Public Sub Init_Grid_Control()
        GridControlSelection.MainView = grvwCarousel
        'GridControlSelection.MainView = grvwTiles
    End Sub

    Public Sub Hide_Grid_Columns()
        If GRID_TYPE = GridType.Grid Then
            grvwGrid.Columns.Item("Record-ID").Visible = False
            grvwGrid.Columns.Item("Form-ID").Visible = False
        Else
            Dim cols As New List(Of String) From {"Record-ID", "Form-ID", "AddedWho", "AddedWhen", "ChangedWho", "ChangedWhen"}

            For Each colname As String In cols
                Dim col = grvwCarousel.Columns.Item(colname)
                If col IsNot Nothing Then
                    col.Visible = False
                End If
            Next

        End If
    End Sub

    Public Function Get_Grid_Sql(ConstructorId As Integer, FormId As Integer)
        If GRID_TYPE = GridType.Grid Then
            Return String.Format("SELECT SQL_SELECT_EBENE1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0} AND FORM_ID = {1}", ConstructorId, FormId)
        Else
            Return String.Format("SELECT SQL_QUICK_VIEW FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = {0} AND FORM_ID = {1}", ConstructorId, FormId)
        End If
    End Function

    Public Sub Clear_Grid_View()
        GridControlSelection.DataSource = Nothing

        If GRID_TYPE = GridType.Grid Then
            grvwGrid.Columns.Clear()
        Else
            grvwCarousel.Columns.Clear()
        End If
    End Sub

    Public Function Get_Grid_Row_Count() As Integer
        If GRID_TYPE = GridType.Grid Then
            Return grvwGrid.RowCount
        Else
            Return grvwCarousel.RowCount
        End If
    End Function

    Public Function Get_Grid_Column_Count() As Integer
        If GRID_TYPE = GridType.Grid Then
            Return grvwGrid.Columns.Count
        Else
            Return grvwCarousel.Columns.Count
        End If
    End Function

    Public Function Get_Focused_Row_Cell_Value(columnName As String)
        If GRID_TYPE = GridType.Grid Then
            Return grvwGrid.GetFocusedRowCellValue(grvwGrid.Columns(columnName))
        Else
            Return grvwCarousel.GetFocusedRowCellValue(grvwCarousel.Columns(columnName))
        End If
    End Function


    Private Sub GridView_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles grvwGrid.FocusedRowChanged, grvwCarousel.FocusedRowChanged
        'If vFormClosing = True Or SaveRoutine_Active = True Then
        '    Exit Sub
        'End If

        'Check_Record_Changed()



        Load_Record_Data()
        'Hide_Grid_Columns()

        'If dataloaded = True Then
        '    If LogErrorsOnly = False Then ClassLogger.Add(">> grvwSelection_FocusedRowChanged - EditState: " & EDIT_STATE, False)
        '    Dim selRecID = GetSelected_RecordID()
        '    If Not selRecID Is Nothing And selRecID <> SelectedRecordID Or EDIT_STATE = "insert" Then
        '        Focused_Row_Column_Changed()
        '    Else
        '        'Console.WriteLine("SelRecordID identisch")
        '    End If
        'End If
    End Sub


#End Region

#Region "Status Bar"

    Public Sub Update_Status_Label(visible As Boolean, Optional text As String = "", Optional state As EditState = EditState.None)
        tssStatus.Text = text
        tssStatus.Visible = visible

        Select Case state
            Case EditState.Insert
                tssStatus.BackColor = Color.Yellow
            Case EditState.Update
                tssStatus.BackColor = Color.LightBlue
            Case Else
                tssStatus.BackColor = Color.LightGray
        End Select
    End Sub

    Public Sub Update_Record_Label(RecordId As Integer)
        Dim SQL As String = "SELECT 'Added by ' + ADDED_WHO + ' when ' + CONVERT(VARCHAR(16),ADDED_WHEN,20) + ', Changed by ' + COALESCE(CHANGED_WHO,'') + ' when ' + COALESCE(CONVERT(VARCHAR(16),CHANGED_WHEN,20),'') FROM TBPMO_RECORD WHERE GUID = " & RecordId
        Dim result = ClassDatabase.Execute_Scalar(SQL)

        If IsDBNull(result) Or IsNothing(result) Then
            tssRecord.Visible = False
        Else
            If CURRENT_FORM_TYPE = 5 Then
                tssRecord.Text = String.Format("Group-Record ({0}) - {1}", RecordId, result.ToString)
            Else
                tssRecord.Text = String.Format("Record ({0}) - {1}", RecordId, result.ToString)
            End If
            tssRecord.Visible = True
        End If
    End Sub

#End Region


    Sub Load_Entity_Data(FormId As Integer, CurrentLevel As Integer)
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim IS_SINGLE_RECORD As Boolean
            Dim LOAD_DIRECT As Boolean
            'VerknüpfungenToolStripMenuItem.Enabled = False
            CURRENT_FORM_TYPE = ClassDatabase.Execute_Scalar("SELECT FORM_TYPE_ID FROM TBPMO_FORM WHERE GUID = " & FormId)
            IS_SINGLE_RECORD = ClassDatabase.Execute_Scalar("SELECT SINGLE_RECORD FROM TBPMO_FORM WHERE GUID = " & FormId)
            LOAD_DIRECT = ClassDatabase.Execute_Scalar("SELECT LOAD_DIRECT FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FormId)
            SelectedRecordID = 0
            Dim DT As DataTable
            Dim sql As String = "SELECT PARENT_ID FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FormId
            Dim PARENT_ID = ClassDatabase.Execute_Scalar(sql)
            If PARENT_ID Is Nothing Then
                MsgBox("Error in GetParentID for selectedNode - Check Logfile", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            'dataloaded = False
            'Abhängig von der Entität die Selektierungs-Daten laden
            Dim _sql As String
            Select Case CurrentLevel
                Case 1
                    PARENT_RECORDID = 0
                    CURRENT_PARENTID = 0
                    EBENE1_ENTITY = TreeViewLevelSelect.SelectedNode.Text
                    ACT_EBENE_STRING = EBENE1_ENTITY
                    If LogErrorsOnly = False Then ClassLogger.Add(">> Ebene 1 in TreeView selektiert", False)
                    EBENE2_ENTITY = ""
                    EBENE3_ENTITY = ""
                    'tslblEntity2.Visible = False
                    'tslblEntity3.Visible = False
                    _sql = ClassDatabase.Execute_Scalar(Get_Grid_Sql(CONSTRUCTORID, FormId))
                    EBENE1_COLUMNNAME = ClassDatabase.Execute_Scalar("SELECT COLUMN_NAME1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FormId)
                    EBENE2_COLUMNNAME = ""
                    EBENE3_COLUMNNAME = ""
                    EBENE2_GRID_RESULT = Nothing
                    EBENE3_GRID_RESULT = Nothing
                    '_sql = ClassDatabase.Execute_Scalar("SELECT SQL_QUICK_VIEW FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FormId)

                Case 2
                    'Dim Level1Select = ClassDatabase.Execute_Scalar(Get_Grid_Sql(CONSTRUCTORID, FormId)) 'ClassDatabase.Execute_Scalar("SELECT LEVEL1_SELECT FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FormId)
                    'If CBool(Level1Select) = False And CURRENT_FORM_TYPE <> 5 And EBENE1_RECID = 0 Then
                    '    MsgBox("Entität '" & TreeViewLevelSelect.SelectedNode.Text & "' kann nicht ohne Auswahl eines Ebene 1 Datensatzes gewählt werden!", MsgBoxStyle.Exclamation)
                    '    TreeViewLevelSelect.SelectedNode = TreeViewLevelSelect.SelectedNode.Parent
                    '    Exit Sub
                    'End If
                    EBENE2_ENTITY = TreeViewLevelSelect.SelectedNode.Text
                    ACT_EBENE_STRING = EBENE2_ENTITY
                    If LogErrorsOnly = False Then ClassLogger.Add(">> Ebene 2 in TreeView selektiert", False)
                    EBENE3_ENTITY = ""
                    'Parent-ID setzen
                    If EBENE1_RECID > 0 Then
                        PARENT_RECORDID = EBENE1_RECID
                        CURRENT_PARENTID = EBENE1_RECID
                        _sql = ClassDatabase.Execute_Scalar(Get_Grid_Sql(CONSTRUCTORID, FormId))
                        If GRID_TYPE = GridType.Grid Then

                        Else

                            _sql = _sql.ToString.Replace("TBPMO_FORM T1", "TBPMO_FORM T1 ,TBPMO_RECORD_CONNECT T2")
                            _sql = _sql & " AND T.GUID = T2.RECORD2_ID  AND T2.RECORD1_ID = @T2.RECORD1_ID"
                            _sql = _sql.ToString.Replace("@T2.RECORD1_ID", PARENT_RECORDID)
                        End If
                      
                    End If
                    'tslblEntity3.Visible = False
                    Select Case CURRENT_FORM_TYPE
                        Case 5
                            If GET_GROUP_RECORD(FormId) = True Then
                                EBENE2_RECID = CURRENT_RECORD_ID
                            End If
                    End Select

                    EBENE2_COLUMNNAME = ClassDatabase.Execute_Scalar("SELECT COLUMN_NAME1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FormId)

                    EBENE3_COLUMNNAME = ""
                    'Wenn bereits ein Record für Ebene 1 gewählt wurde dann einschränken
                    If EBENE1_RECID > 0 Then
                        _sql = ClassDatabase.Execute_Scalar(Get_Grid_Sql(CONSTRUCTORID, FormId))
                        If GRID_TYPE = GridType.Grid Then

                        Else
                            '_sql = ClassDatabase.Execute_Scalar("SELECT SQL_QUICK_VIEW FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FormId)

                            _sql = _sql.Replace("@RecordID", EBENE1_RECID)
                            _sql = _sql.ToString.Replace("TBPMO_FORM T1", "TBPMO_FORM T1 ,TBPMO_RECORD_CONNECT T2")
                            _sql = _sql & " AND T.GUID = T2.RECORD2_ID  AND T2.RECORD1_ID = @T2.RECORD1_ID"
                            _sql = _sql.ToString.Replace("@T2.RECORD1_ID", PARENT_RECORDID)
                        End If

                    Else
                        _sql = ClassDatabase.Execute_Scalar("SELECT SQL_QUICK_VIEW FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FormId)
                    End If
                    EBENE2_GRID_RESULT = Nothing
                    EBENE3_GRID_RESULT = Nothing

                Case 3
                    Select Case CURRENT_FORM_TYPE
                        Case 5
                            If GET_GROUP_RECORD(FormId) = True Then
                                EBENE3_RECID = CURRENT_RECORD_ID
                            End If
                    End Select

                    If EBENE2_RECID = 0 Then
                        MsgBox("Entität '" & TreeViewLevelSelect.SelectedNode.Text & "' kann nicht ohne Auswahl eines Ebene 1 Datensatzes gewählt werden!", MsgBoxStyle.Exclamation)
                        TreeViewLevelSelect.SelectedNode = TreeViewLevelSelect.SelectedNode.Parent
                        Exit Sub
                    End If

                    EBENE3_ENTITY = TreeViewLevelSelect.SelectedNode.Text
                    ACT_EBENE_STRING = EBENE3_ENTITY
                    If LogErrorsOnly = False Then ClassLogger.Add(">> Ebene 3 in TreeView selektiert", False)
                    'Parent-ID setzen
                    If EBENE2_RECID > 0 Then
                        PARENT_RECORDID = EBENE2_RECID
                        CURRENT_PARENTID = EBENE2_RECID
                    End If

                    EBENE3_COLUMNNAME = ClassDatabase.Execute_Scalar("SELECT COLUMN_NAME1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FormId)
                    'Wenn bereits ein Record für Ebene 1 gewählt wurde dann eisnchränken
                    If EBENE2_RECID > 0 Then
                        Try
                            _sql = ClassDatabase.Execute_Scalar(Get_Grid_Sql(CONSTRUCTORID, FormId))
                            If GRID_TYPE = GridType.Grid Then

                            Else

                                _sql = _sql.Replace("@RecordID", EBENE2_RECID)
                                _sql = _sql.ToString.Replace("TBPMO_FORM T1", "TBPMO_FORM T1 ,TBPMO_RECORD_CONNECT T2")
                                _sql = _sql & " AND T.GUID = T2.RECORD2_ID  AND T2.RECORD1_ID = @T2.RECORD1_ID"
                                _sql = _sql.ToString.Replace("@T2.RECORD1_ID", PARENT_RECORDID)

                            End If

                           

                        Catch ex As Exception

                        End Try

                    Else
                        MsgBox("Entität kann nicht ohne Auswahl eines Ebene 2 Datensatzes gewählt werden!", MsgBoxStyle.Exclamation)
                        'Grid leeren
                        Clear_Grid_View()
                        Me.Cursor = Cursors.Default
                        Exit Sub
                    End If
                    EBENE3_GRID_RESULT = Nothing
            End Select

            CURRENT_FORM_ID = FormId
            CURRENT_ENTITYSTRING = ACT_EBENE_STRING
            CURRENT_PARENTID = PARENT_RECORDID
            act_FormViewID = ClassDatabase.Execute_Scalar("SELECT GUID FROM TBPMO_FORM_VIEW where FORM_ID = " & FormId)
            'If EDIT_STATE = "none" Then
            '    'Die Controls der Entität laden
            '    Load_Controls(act_FormViewID)
            '    set_pnlsize()
            'End If
            CURRENT_FORMVIEW_ID = act_FormViewID

            'Überprüfen ob windream Dos angezeigt werden sollen?
            'Check_windream_Show(act_FormViewID)



            'If windream_Docshow = True Then
            '    Clear_Windream_ResultList()
            '    If WD_ShowEnitityDocs = True Then
            '        RUN_WD_SEARCH("", "ENTITY")
            '    End If
            'End If

            ' Me.pnlDetails.Enabled = False
            'Me.tsbtnshowWorkflowtasks.Enabled = False
            'tsbtnRecordAdd.Enabled = True


            Select Case CURRENT_FORM_TYPE
                Case 5
                    'Nur eine Gruppen-Entität: d.h. es wird nur die Dateientab angezeigt
                    Console.WriteLine("OnlyGroupType")

                    'TabPageDetails.PageVisible = False
                    'Anzeige_Selected_Entity()
                    'tsbtnRecordAdd.Visible = False
                    'tsbtnRecorddelete.Visible = False
                    'tsbtnRecordSave.Visible = False
                Case Else
                    'tsbtnRecordAdd.Visible = True
                    'tsbtnRecorddelete.Visible = True
                    'tsbtnRecordSave.Visible = True
                    'TabPageDetails.PageVisible = True
                    Dim Beschreibung = ClassDatabase.Execute_Scalar("SELECT FORM_TITLE FROM TBPMO_FORM_VIEW WHERE GUID = " & act_FormViewID)
                    'TabPageDetails.Text = "Detaileingabe zu " & Beschreibung
                    'Den Spaltennamen für die Selektion laden
                    sql = "SELECT COLUMN_NAME1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FormId
                    'Jetzt die Datensätze zur Entität laden
                    CURRENT_ENTITYSQL = _sql
                    Dim DTEntity As DataTable = ClassDatabase.Return_Datatable(CURRENT_ENTITYSQL, "LoadEntityData - Get DTEntity")
                    Dim primaryKey(1) As DataColumn
                    primaryKey(0) = DTEntity.Columns("Record-ID")
                    DTEntity.PrimaryKey = primaryKey
                    LoadGrid_Selection(_sql, DTEntity)

                    'If LOAD_DIRECT = True Then
                    '    Dim sql1 = CURRENT_ENTITYSQL
                    '    sql1.Replace("T.*", "TOP 1 [Record-ID]")
                    '    Dim id = ClassDatabase.Execute_Scalar(sql1, True)
                    '    If Not id Is Nothing Then
                    '        If LogErrorsOnly = False Then ClassLogger.Add(">> Load Record directly - RecordID: " & CURRENT_RECORD_ID, False)
                    '        Load_Record_Data()
                    '    End If
                    'Else


                    'End If
                    'Überprüfen ob es für diese Entität Wiedervorlagen gibt?
                    'Check_FOLLOWUP_IsConfigured(CURRENT_FORM_ID)
            End Select

            'Load_Templates()

            Me.Cursor = Cursors.Default
            'dataloaded = True
        Catch ex As Exception
            MsgBox("Error in Load_Entity_Data:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
        CreateTile()
    End Sub
    Sub CreateTile()
        Dim HasImages As Boolean = False
        Dim ImageIndex As Integer = -1
        Dim i As Integer = 0
        Dim j As Integer = 0
        Dim DT As DataTable = DirectCast(DT_SELECTION, DataTable)

        Dim PrimaryFont As New Font("Segoe UI", 14, FontStyle.Bold)
        Dim SecondaryFont As New Font("Segoe UI", 12)

        ' Datatable laden
        GridControl1.DataSource = DT

        For Each Column As DataColumn In DT.Columns
            Dim index As Integer = DT.Columns.IndexOf(Column)
            Dim RECORDID_Column As TileViewItemElement
            Dim ImageColumn As TileViewItemElement
            Dim HeadlineColumn As TileViewItemElement
            Dim TextColumn As TileViewItemElement
            Dim TextHeaderColumn As TileViewItemElement

            Select Case index
                Case 0
                    ' RecordId
                    RECORDID_Column = New TileViewItemElement()
                    With RECORDID_Column
                        .Column = TileView1.Columns(0)
                     
                    End With
                Case 1
                    ' Index 1 ist das Bild
                    If Column.DataType.ToString.Contains("Byte") Then
                        ImageColumn = New TileViewItemElement()
                        With ImageColumn
                            .Column = TileView1.Columns(1)
                            .ImageSize = New Size(186, 90)
                            .ImageScaleMode = TileItemImageScaleMode.Squeeze
                            .ImageAlignment = TileItemContentAlignment.BottomLeft
                        End With
                        TileView1.TileTemplate.Add(ImageColumn)
                    End If
                Case 2
                    ' Index 2 ist die Headline
                    HeadlineColumn = New TileViewItemElement()
                    With HeadlineColumn
                        .Column = TileView1.Columns(2)
                        .TextAlignment = TileItemContentAlignment.TopRight
                        .Appearance.Normal.Font = PrimaryFont
                        .Appearance.Normal.ForeColor = Color.DodgerBlue
                        .Column.OptionsFilter.AllowFilter = True
                    End With
                    TileView1.TileTemplate.Add(HeadlineColumn)
                Case 3 To 4
                    ' Indexe 3 und 4 sind normale Textzeilen
                    TextColumn = New TileViewItemElement()
                    TextHeaderColumn = New TileViewItemElement()
                    Dim OffsetIndex = index - 3
                    Dim LastElement = DirectCast(TileView1.TileTemplate.Last, TileViewItemElement)
                    Dim TileSize = TileView1.OptionsTiles.ItemSize

                    With TextHeaderColumn

                        .Text = Column.ColumnName
                        .TextAlignment = TileItemContentAlignment.Manual
                        .TextLocation = New Point(200, 80 + (OffsetIndex * 40))
                        .Appearance.Normal.Font = SecondaryFont
                        .Appearance.Normal.ForeColor = Color.Red
                    End With

                    With TextColumn
                        .Column = TileView1.Columns(index)
                        .TextAlignment = TileItemContentAlignment.Manual
                        .TextLocation = New Point(200, 100 + (OffsetIndex * 40))
                        .Appearance.Normal.Font = SecondaryFont
                    End With

                    TileView1.TileTemplate.Add(TextHeaderColumn)
                    TileView1.TileTemplate.Add(TextColumn)
            End Select


        Next

        'Dim PictureIndex As Integer = -1
        'Dim DT = DirectCast(DT_SELECTION, DataTable)
        'Dim i As Integer = 0
        'For Each Column As DataColumn In DT.Columns
        '    If Column.DataType.ToString.Contains("Byte") Then
        '        PictureIndex = i
        '    End If
        '    i += 1
        'Next

        'If PictureIndex <> -1 Then
        '    HasImages = True
        'End If

        'GridControl1.DataSource = DT
        'Das BackgroundImage setzen
        'If PictureIndex <> -1 Then
        '    TileView1.ColumnSet.BackgroundImageColumn = TileView1.Columns(PictureIndex) '"Image")
        '    TileView1.OptionsTiles.ItemBackgroundImageAlignment = DevExpress.XtraEditors.TileItemContentAlignment.MiddleLeft
        '    TileView1.OptionsTiles.ItemBackgroundImageScaleMode = DevExpress.XtraEditors.TileItemImageScaleMode.ZoomInside
        'End If





        'Dim ImageColumn As New TileViewItemElement()
        'With ImageColumn
        '    .Column = TileView1.Columns(2)
        '    .ImageSize = New Size(124, 60)
        '    .ImageAlignment = TileItemContentAlignment.MiddleLeft
        '    .ImageScaleMode = TileItemImageScaleMode.ZoomOutside
        '    .ImageBorder = TileItemElementImageBorderMode.None
        '    .MaxWidth = 124
        'End With





        'Dim PrimaryColumn As New TileViewItemElement()
        'With PrimaryColumn
        '    .Column = TileView1.Columns(1)
        '    .TextAlignment = TileItemContentAlignment.TopRight
        '    .Appearance.Normal.ForeColor = SystemColors.MenuHighlight
        '    .Appearance.Normal.Font = PrimaryFont
        'End With

        'Dim SecondaryColumn As New TileViewItemElement()
        'With SecondaryColumn
        '    .Column = TileView1.Columns(3)
        '    '.TextAlignment = TileItemContentAlignment.MiddleRight
        '    .Appearance.Normal.ForeColor = Color.Black
        '    .Appearance.Normal.Font = SecondaryFont
        '    .TextAlignment = TileItemContentAlignment.MiddleRight
        'End With




        'TileView1.TileTemplate.Add(PrimaryColumn)
        'TileView1.TileTemplate.Add(ImageColumn)
        'TileView1.TileTemplate.Add(SecondaryColumn)

        'TileView1.TileTemplate.Add(New TileViewItemElement With {.Column = TileView1.Columns(3), .TextAlignment = TileItemContentAlignment.MiddleCenter})
        'TileView1.TileTemplate.Add(New TileViewItemElement With {.Column = TileView1.Columns(1), .TextAlignment = TileItemContentAlignment.Manual, .TextLocation = New Point(180, 39)})
        'Try
        '    TryCast(TileView1.TileTemplate(0), TileViewItemElement).Column = TileView1.Columns(3) '"Name")
        'Catch ex As Exception

        'End Try
        'TileView1.TileTemplate.Add(New TileViewItemElement With {.Column = TileView1.Columns("Date"), .TextAlignment = TileItemContentAlignment.Manual, .TextLocation = New Point(150, 100)})
    End Sub
    Private Function GET_GROUP_RECORD(FORM_ID As Integer)
        Dim sqlRecord As String = "select guid from TBPMO_RECORD where Form_ID = " & FORM_ID
        Dim recid = ClassDatabase.Execute_Scalar(sqlRecord, True)
        If IsNothing(recid) Then
            If ClassControlCommandsUI.CreateRecord(FORM_ID) = True Then
                recid = ClassControlCommandsUI.GetLastRecord
                If IsNothing(recid) Then
                    CURRENT_RECORD_ID = recid
                    ClassControlCommandsUI.ConnectRecord(CURRENT_PARENTID, CURRENT_RECORD_ID, "Group-Entity Link")
                Else
                    Return False
                End If
            Else

                Return False
            End If
        Else
            Try
                CURRENT_RECORD_ID = CInt(recid)

            Catch ex As Exception
                MsgBox("Error while getting CURRENT_RECORDID: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                Return False
            End Try
        End If
        'Refresh_CreatedChangedRecordByID(CURRENT_RECORD_ID)
        Return True
    End Function

    Private Function LoadGrid_Selection(Grid_SQL As String, Datatable_Grid As DataTable)
        Try
            DT_SELECTION = Datatable_Grid
            EBENE_SQLRESULT = Grid_SQL
            Dim i = EBENE_SQLRESULT.ToLower.IndexOf("from")
            EBENE_SQLRESULT = EBENE_SQLRESULT.ToLower.Substring(i)
            ' Alle Checkboxen für aktuelle Ansicht heraussuchen
            Dim sqlcheck As String = "SELECT CONTROL_COLUMN FROM VWPMO_VALUES WHERE CONTROL_TYPE_ID in (10,11) AND FORM_ID = " & CURRENT_FORM_ID
            Dim dtcheck As DataTable = ClassDatabase.Return_Datatable(sqlcheck)
            Dim listcheck As New List(Of String)

            'Liste von allen Spaltentiteln mit Checkbox erstellen
            If dtcheck.Rows.Count > 0 Then
                For Each row As DataRow In dtcheck.Rows
                    listcheck.Add(row.Item(0))
                Next
            End If

            'Duplikate entfernen
            listcheck = listcheck.Distinct().ToList()

            'Grid leeren
            Clear_Grid_View()

            'Databinding Neu
            BindingSource_Entity.DataSource = Datatable_Grid
            GridControlSelection.DataSource = BindingSource_Entity


            grvwTiles.ColumnSet.BackgroundImageColumn = grvwTiles.Columns("Column2")
            Dim tileViewItemElement As New TileViewItemElement()
            tileViewItemElement.Column = grvwTiles.Columns("Column1")
            tileViewItemElement.ImageBorderColor = System.Drawing.Color.Empty
            tileViewItemElement.Text = "element1"
            grvwTiles.TileTemplate.Add(tileViewItemElement)


            ' Den Editor Initialisieren und Optionen setzen
            Dim CheckBoxEditorForDisplay = New RepositoryItemCheckEdit()
            CheckBoxEditorForDisplay.ValueChecked = 1
            CheckBoxEditorForDisplay.ValueUnchecked = 0

            ' Alle Checkbox Spalten durchgehen und CheckBoxEditor zuweisen
            'For Each col As String In listcheck
            '    grvwSelection.GridControl.RepositoryItems.Add(CheckBoxEditorForDisplay)

            '    If Not IsNothing(grvwSelection.Columns(col)) Then
            '        grvwSelection.Columns(col).ColumnEdit = CheckBoxEditorForDisplay
            '    End If
            'Next
            'grvwGrid.Columns("Record-ID").OptionsColumn.AllowShowHide = False
            'Load_GridSelection_Layout()
            'HideColumns()
            Dim selnode As TreeNode = TreeViewLevelSelect.SelectedNode
            Dim origtext As String = selnode.Text
            If origtext.Contains(" (") Then
                Dim existingstring = origtext.Substring(0, origtext.IndexOf("(") - 1)

                selnode.Text = String.Format("{0} ({1})", existingstring, Get_Grid_Row_Count())
            Else
                selnode.Text = String.Format("{0} ({1})", selnode.Text, Get_Grid_Row_Count())
            End If
        Catch ex As Exception
            MsgBox("Error in LoadGrid_Selection:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try

        Return True
    End Function

    Sub Show_Selected_Record_Data(GridColumn_String As String, Optional DirectRecID As Integer = 0)
        Try
            'Me.pnlDetails.Visible = True
            'ZeigeRecordLogsToolStripMenuItem.Enabled = False
            If DirectRecID = 0 Then
                If LogErrorsOnly = False Then ClassLogger.Add(">> Record wird über Datagrid focusedRow geladen", False)
                'Überhaupt Columns in Grid?
                If Get_Grid_Column_Count() = 0 Then
                    'Me.pnlDetails.Enabled = False
                    'Me.tsbtnshowWorkflowtasks.Enabled = False

                    'tsstatus_Detail_show(True, "Keine Columns in Grid")
                    Exit Sub
                End If
                'Überhaupt Rows in Grid?
                If Get_Grid_Row_Count() > 0 Then
                    Dim Grid_RecordID = Get_Focused_Row_Cell_Value(GridColumn_String)
                    If Grid_RecordID Is Nothing = False Then
                        SelectedRecordID = Grid_RecordID
                        CURRENT_RECORD_ID = Grid_RecordID
                    Else
                        'tsstatus_Detail_show(True, "Grid_RecordID konnte nicht gewählt werden!")
                        ClassLogger.Add(">> Grid_RecordID konnte nicht gewählt werden - SelectedRecord_ShowData", True)
                        Exit Sub
                    End If
                End If

            Else 'Record wird direkt geladen
                If LogErrorsOnly = False Then ClassLogger.Add(">> Record wird DIREKT geladen", False)
                SelectedRecordID = DirectRecID
                CURRENT_RECORD_ID = DirectRecID
            End If

            Dim Record_Changes As String = "SELECT count(GUID) FROM VWPMO_RECORD_CHANGES WHERE RECORD_ID = " & CURRENT_RECORD_ID
            Dim RC = ClassDatabase.Execute_Scalar(Record_Changes)
            If Not RC Is Nothing Then
                If RC > 0 Then
                    'ZeigeRecordLogsToolStripMenuItem.Enabled = True
                End If
            End If
            'Die aktuelle Ebene überprüfen und den Datensatz übergeben, ebenso den PARENT-Record setzen
            Select Case ACT_EBENE
                Case 1
                    PARENT_RECORDID = 0
                    EBENE1_RECID = SelectedRecordID
                    CURRENT_PARENTID = EBENE1_RECID
                    If Not EBENE1_COLUMNNAME Is Nothing Then
                        EBENE1_GRID_RESULT = Get_GridResult(EBENE1_COLUMNNAME)


                        Dim cat As TileNavCategory = LoadLevel1Nav()
                        navPane.Categories.Clear()
                        navPane.Categories.Add(cat)

                    End If
                Case 2
                    EBENE2_RECID = SelectedRecordID
                    If Not EBENE2_COLUMNNAME Is Nothing Then
                        EBENE2_GRID_RESULT = Get_GridResult(EBENE2_COLUMNNAME)
                        'Dim sql As String = "select @p " & EBENE_SQLRESULT & " where [Record-ID] = " & SelectedRecordID
                        'sql = sql.Replace("@p", EBENE2_COLUMNNAME)
                        'Dim result = ClassDatabase.Execute_Scalar(sql)
                        'EBENE2_GRID_RESULT = result 'grvwSelection.GetFocusedRowCellValue(grvwSelection.Columns(EBENE2_COLUMNNAME))

                        Dim cat As TileNavCategory = LoadLevel1Nav()
                        navPane.Categories.Clear()
                        navPane.Categories.Add(cat)

                        Dim item As TileNavItem = LoadLevel2Nav()
                        cat.Items.Add(item)


                    End If
                    If EBENE1_RECID > 0 Then
                        PARENT_RECORDID = EBENE1_RECID
                        CURRENT_PARENTID = EBENE1_RECID
                    Else
                        CURRENT_PARENTID = EBENE2_RECID
                    End If
                Case 3
                    EBENE3_RECID = SelectedRecordID
                    If Not EBENE3_COLUMNNAME Is Nothing Then
                        EBENE3_GRID_RESULT = Get_GridResult(EBENE3_COLUMNNAME)
                        'EBENE3_GRID_RESULT = grvwSelection.GetFocusedRowCellValue(grvwSelection.Columns(EBENE3_COLUMNNAME))

                        Dim cat As TileNavCategory = LoadLevel1Nav()
                        navPane.Categories.Clear()
                        navPane.Categories.Add(cat)

                        Dim item As TileNavItem = LoadLevel2Nav()
                        cat.Items.Add(item)

                        Dim subitem As TileNavSubItem = LoadLevel3Nav()
                        item.SubItems.Add(subitem)

                    End If
                    If EBENE2_RECID > 0 Then
                        PARENT_RECORDID = EBENE2_RECID
                        CURRENT_PARENTID = EBENE2_RECID
                    End If
            End Select



            'Me.pnlDetails.Enabled = True
            'Me.tsbtnshowWorkflowtasks.Enabled = True
            'Me.tsbtnshowTaskoverview.Enabled = True
            'tsstatus_Detail_show(False, "")
        Catch ex As Exception
            MsgBox("Error in SelectedRecord_ShowData:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Function Get_GridResult(Columnname As String)
        Dim result As String = Get_Focused_Row_Cell_Value(Columnname)
        If result = String.Empty Then
            Return "No Column configured"
        Else
            Return result
        End If
    End Function

    Function GetSelected_RecordID()
        Try
            If Get_Grid_Column_Count() = 0 Then
                'Me.pnlDetails.Enabled = False
                'Me.tsbtnshowWorkflowtasks.Enabled = False
                'tsstatus_Detail_show(True, "Keine Columns in Grid")
                Return Nothing
            End If
            'Überhaupt Rows in Grid?
            If Get_Grid_Row_Count() > 0 Then
                Dim Grid_RecordID = Get_Focused_Row_Cell_Value("Record-ID")
                If Grid_RecordID Is Nothing = False Then
                    Return Grid_RecordID
                Else
                    'tsstatus_Detail_show(True, "Grid_RecordID konnte nicht gewählt werden!")
                    'ClassLogger.Add(">> Grid_RecordID konnte nicht gewählt werden - SelectedRecord_ShowData", True)
                    Return Nothing
                End If
            Else
                Return Nothing
            End If
        Catch ex As Exception

        End Try
    End Function



    Sub Load_Record_Data()
        Select Case EDIT_STATE
            Case EditState.None
                'Ganz normalerDatensatzwechsel Wechsel
                Show_Selected_Record_Data("Record-ID")
                'Refresh_Treeview_SelectedData()
                'tslblStatusMain_show(False, "")
            Case EditState.Insert
                'Refresh_Treeview_SelectedData()
            Case EditState.Update
                ' Refresh_Treeview_SelectedData()
        End Select
        'Select Case TCDetails.SelectedTabPageIndex
        '    Case 0
        '        'Die Values in die Controls laden
        '        If EDIT_STATE = "none" Then
        '            'TabPageDetails.Text = "Detaileingabe zu '" & ACT_EBENE_STRING & "' - Record(" & SelectedRecordID & ")"
        '            'Die Daten auf dem Panel laden
        '            ClassControlValues.LoadControlValues(SelectedRecordID, CURRENT_FORM_ID, CtrlBuilder.AllControls)
        '            'Load_Control_Values(CtrlBuilder.AllControls)
        '            'Refresh_Treeview_SelectedData()
        '            RECORD_CHANGED = False
        '        End If
        '    Case 1
        '        RUN_WD_SEARCH(WD_Suche, "RECORD")
        '    Case 2
        '        If FOLLOW_UPisActive = True Then Refresh_FollowUps()
        'End Select
        'DT_FU_Record = Nothing
        'VerknüpfungenToolStripMenuItem.Enabled = True

        'If FOLLOW_UPisActive = True Then Refresh_FollowUp_TabHeader()
        'Refresh_CreatedChangedRecordByID(SelectedRecordID)
        'Anzeige_Selected_Entity()
        'Show_act_WFTask()
        'Get_RecordCounts_Nodes()

        'Refresh_TaskOverview()
    End Sub

    Private Sub TreeViewEbeneSelect_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeViewLevelSelect.AfterSelect
        Load_Tree_View_Data()
    End Sub

    Private Sub btn_Refresh_ElementClick(sender As Object, e As NavElementEventArgs) Handles btn_Refresh.ElementClick
        Load_Tree_View_Data()
    End Sub

    Private Sub btn_home_ElementClick(sender As Object, e As NavElementEventArgs) Handles btn_home.ElementClick
        Load_Tree_View(CURRENT_CONSTRUCTOR_ID)
    End Sub


    Private Sub AnsichtUmschaltenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AnsichtUmschaltenToolStripMenuItem.Click
        GridControlSelection.MainView = grvwTiles
    End Sub

    Private Sub TileView1_ItemClick(sender As Object, e As TileViewItemClickEventArgs) Handles TileView1.ItemClick
        Console.WriteLine("TileView1.ItemClick")
        Dim val As Integer = TileView1.GetRowCellValue(TileView1.FocusedRowHandle, "Record-ID")

    End Sub

    Private Sub TileView1_SelectionChanged(sender As Object, e As DevExpress.Data.SelectionChangedEventArgs) Handles TileView1.SelectionChanged
        Console.WriteLine("TileView1.SelectionChanged")
    End Sub
End Class
