Imports System.ComponentModel
Imports DevExpress.Xpf.Core
Imports DevExpress.Xpf.Printing
Imports DevExpress.Utils
Imports tsWPF.Controles
Imports DevExpress.Xpf.Bars
Imports DevExpress.Xpf.Grid
Imports System.IO
Imports System.Threading.Tasks
Imports Microsoft.Win32
Imports tsl5.Extensiones

Public Class ContenedorLineas
    Public apLinea As ApLineas
    Dim _DescripcionDiseño As String
    Dim _TodosUsuariosDiseño As Boolean
    Public Property t As Task


    Public Event CargaAplicacion(sender As System.Object, e As System.Windows.RoutedEventArgs)
    Public Event AntesDeGuardar(sender As System.Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)
    Public Event DespuesDeGuardar(sender As System.Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)


    Public Sub New()

        ' Llamada necesaria para el diseñador.
        InitializeComponent()

        ' Agregue cualquier inicialización después de la llamada a InitializeComponent().

    End Sub

    Public Sub New(apLinea As ApLineas, uc As UserControl)
        If Not (System.ComponentModel.DesignerProperties.GetIsInDesignMode(Me)) Then
            ' Llamada necesaria para el diseñador.
            InitializeComponent()
            Me.contenido.Children.Add(uc)
            Me.apLinea = apLinea
            apLinea.ContenedorL = Me
            apLinea.LanzaEventoCargado()
            If apLinea.PermisosConcedidos.Exportar Then
                Dim cm As New ContextMenu

                Dim mie As New MenuItem()
                mie.Tag = "MI_EXPORTAR_EXCEL"
                mie.Header = "Exportar a Excel"
                AddHandler mie.Click, AddressOf _ExportarExcel
                cm.Items.Add(mie)


                Dim mi As New MenuItem()
                mi.Tag = "MI_EXPORTAR"
                mi.Header = "Exportar Otros Formatos"
                AddHandler mi.Click, AddressOf _Exportar
                cm.Items.Add(mi)
                Me.apLinea.Rejilla.ContextMenu = cm
            End If

        End If
    End Sub

    Private Sub _ExportarExcel(sender As Object, e As RoutedEventArgs)
        Dim mi As MenuItem = sender
        Dim cm As ContextMenu = mi.Parent
        Dim tsgc As tsGridControl = cm.PlacementTarget
        Dim vista As TableView = tsgc.View

        Dim sfd As New SaveFileDialog
        sfd.FileName = IO.Path.GetDirectoryName("Exportacion") & (tsgc.NombreTablaBase.NothingAVacio & " Exportacion.xlsx").Trim
        sfd.Filter = "Fichero Excel (*.xls, *.xlsx, *.csv)|*.xls;*.xlsx;*.csv"
        sfd.DefaultExt = ".xlsx"
        If sfd.ShowDialog Then
            Select Case IO.Path.GetExtension(sfd.FileName).ToLower
                Case ".xls"
                    vista.ExportToXls(sfd.FileName)
                Case ".xlsx"
                    vista.ExportToXlsx(sfd.FileName)
                Case ".csv"
                    vista.ExportToCsv(sfd.FileName)
            End Select
            Process.Start(sfd.FileName)
        End If
    End Sub
    Private Sub _Exportar(sender As Object, e As RoutedEventArgs)
        Dim mi As MenuItem = sender
        Dim cm As ContextMenu = mi.Parent
        Dim tsgc As tsGridControl = cm.PlacementTarget
        Dim vista As TableView = tsgc.View
        Try


            'Dim link As New PrintableControlLink(CType(vista, TableView))
            'link.CreateDocument()
            'Dim vi As New tsWPF.ucVisualizadorInformes()
            'vi.Visualizador.DocumentSource = link
            'Dim docpanel = New DevExpress.Xpf.Docking.DocumentPanel
            'Dim tabHeaderPrintInfoControl As New TabHeaderPrintInfoControl() With {.TabName = "Exportación " & tsgc.PropiedadesTSGC.Descripcion}
            'docpanel.Caption = tabHeaderPrintInfoControl
            'docpanel.Content = vi
            'docpanel.ClosingBehavior = DevExpress.Xpf.Docking.ClosingBehavior.ImmediatelyRemove
            'Me.apLinea.GrupoDocumentos.Add(docpanel)
            'Comun.dm.DockController.Activate(docpanel)







            Dim preview As New DocumentPreview()
            Dim model As LinkPreviewModel = CreateLinkPreviewModel(TryCast(vista, IPrintableControl))
            model.Link.PaperKind = System.Drawing.Printing.PaperKind.A4Rotated
            preview.Model = model
            Dim tabHeaderPrintInfoControl As New TabHeaderPrintInfoControl() With {.TabName = "Exportación " & tsgc.PropiedadesTSGC.Descripcion, .LinkPreviewModel = model}
            Dim docpanel = New DevExpress.Xpf.Docking.DocumentPanel
            docpanel.Caption = tabHeaderPrintInfoControl
            docpanel.Content = preview
            docpanel.ClosingBehavior = DevExpress.Xpf.Docking.ClosingBehavior.ImmediatelyRemove
            Me.apLinea.GrupoDocumentos.Add(docpanel)
            Comun.dm.DockController.Activate(docpanel)
            model.Link.CreateDocument(True)
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Sub
    'Public Shared Function CreateLinkPreviewModel(ByVal printableControl As IPrintableControl) As LinkPreviewModel
    '    Dim link As New PrintableControlLink(TryCast(printableControl, IPrintableControl))
    '    Return New LinkPreviewModel(link)
    'End Function





    'Private Sub BotonEditar(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs) Handles btEditar.ItemClick
    '    If Not apLinea.Rejilla.CurrentItem Is Nothing Then
    '        apLinea.IApLin.Editar()
    '    End If

    'End Sub
    Private Sub BotonNuevo(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs) Handles btNuevo.ItemClick
        apLinea.IApLin.Nuevo()
    End Sub

    Private Sub BotonEliminar(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs) Handles btEliminar.ItemClick
        'apLinea.IApLin.Eliminar()
        apLinea.Eliminar()
    End Sub
    'Private Sub BotonGuardar(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs) Handles btGuardar.ItemClick
    '    apLinea.Guardar()
    'End Sub


    'Private Sub ContenedorLineas_GotFocus(sender As Object, e As RoutedEventArgs) Handles Me.GotFocus
    '    Debug.WriteLine("contenedorlin.gotfocus")
    'End Sub

    Private Sub btSeleccionar_CheckedChanged(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)
        apLinea.SeleccionarHabilitadoCambiado(btSeleccionar.IsChecked)


    End Sub

    Public Sub btInvertir_ItemClick(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)

        'Dim enti As System.Data.Objects.DataClasses.EntityObject = Nothing

        'For i = 0 To Me.apLinea.Rejilla.VisibleRowCount - 1
        '    enti = Me.apLinea.Rejilla.GetRow(i)
        '    Dim key As Integer
        '    If Not enti Is Nothing Then
        '        Dim rowHandle As Integer = Me.apLinea.Rejilla.GetRowHandleByVisibleIndex(i)
        '        key = enti.GetType.GetProperty(Me.apLinea.CampoIndice).GetValue(enti, Nothing)
        '        Dim newIsSelected As Boolean = Not Me.apLinea.ElementosSeleccionados.GetIsSelected(key)
        '        Me.apLinea.Rejilla.SetCellValue(rowHandle, "tswpf_seleccionar", newIsSelected)
        '    End If
        'Next
        'Me.apLinea.Rejilla.RefreshData()

        Try
            Dim iq As IQueryable(Of System.Data.Objects.DataClasses.EntityObject)
            Dim li As List(Of System.Data.Objects.DataClasses.EntityObject) = Nothing
            Dim key As Integer

            Try
                'iq = Me.apLinea.Rejilla.DataContext
                iq = Me.apLinea.Rejilla.ItemsSource
                li = iq.ToList
            Catch ex As InvalidCastException
                'Catch ex As Exception
                Try
                    li = Me.apLinea.Rejilla.ItemsSource
                Catch ex2 As Exception
                    Dim ob = Me.apLinea.Rejilla.ItemsSource
                    For i = 0 To ob.Count - 1
                        key = ob(i).GetType.GetProperty(Me.apLinea.CampoIndice).GetValue(ob(i), Nothing)
                        Dim newIsSelected As Boolean = Not Me.apLinea.ElementosSeleccionados.GetIsSelected(key)
                        Dim rowHandle As Integer = Me.apLinea.Rejilla.GetRowHandleByListIndex(i)
                        If Me.apLinea.Rejilla.IsGroupRowExpanded(rowHandle) Or Me.apLinea.Rejilla.GetRowLevelByRowHandle(rowHandle) = 0 Then
                            Me.apLinea.Rejilla.SetCellValue(rowHandle, "tswpf_seleccionar", newIsSelected)
                        End If
                    Next
                End Try
            End Try
            If li IsNot Nothing Then
                For i = 0 To li.Count - 1
                    key = li(i).GetType.GetProperty(Me.apLinea.CampoIndice).GetValue(li(i), Nothing)
                    Dim newIsSelected As Boolean = Not Me.apLinea.ElementosSeleccionados.GetIsSelected(key)
                    Dim rowHandle As Integer = Me.apLinea.Rejilla.GetRowHandleByListIndex(i)
                    If Me.apLinea.Rejilla.IsGroupRowExpanded(rowHandle) Or Me.apLinea.Rejilla.GetRowLevelByRowHandle(rowHandle) = 0 Then
                        Me.apLinea.Rejilla.SetCellValue(rowHandle, "tswpf_seleccionar", newIsSelected)
                    End If
                Next
            End If
            Me.apLinea.Rejilla.RefreshData()
        Catch ex As Exception
            Debug.Write(ex.Message)
        End Try
        Me.apLinea.LanzaEventoInvertirSeleccion()


        'Dim key As Integer
        'Dim enti As System.Data.Objects.DataClasses.EntityObject = Nothing
        'For i As Integer = 0 To Me.apLinea.Rejilla.DataContext.Count - 1
        '    enti = Me.apLinea.Rejilla.DataContext.GetType(i)
        '    key = enti.GetType.GetProperty(Me.apLinea.CampoIndice).GetValue(enti, Nothing)
        '    Dim newIsSelected As Boolean = Not Me.apLinea.ElementosSeleccionados.GetIsSelected(key)
        '    Dim rowHandle As Integer = Grid.GetRowHandleByListIndex(i)
        '    Grid.SetCellValue(rowHandle, "Selected", newIsSelected)
        'Next i


    End Sub

    Private Sub btImprimirListado_ItemClick(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)
        Dim preview As New DocumentPreview()
        Dim model As LinkPreviewModel = CreateLinkPreviewModel(TryCast(Me.apLinea.Rejilla.View, IPrintableControl))
        preview.Model = model

        Dim tabHeaderPrintInfoControl As New TabHeaderPrintInfoControl() With {.TabName = "Listado de " & Me.apLinea.Titulo, .LinkPreviewModel = model}
        Dim docpanel = New DevExpress.Xpf.Docking.DocumentPanel
        docpanel.Caption = tabHeaderPrintInfoControl
        docpanel.Content = preview
        docpanel.ClosingBehavior = DevExpress.Xpf.Docking.ClosingBehavior.ImmediatelyRemove
        Me.apLinea.GrupoDocumentos.Add(docpanel)
        Comun.dm.DockController.Activate(docpanel)
        model.Link.CreateDocument(True)
    End Sub
    Public Shared Function CreateLinkPreviewModel(ByVal printableControl As IPrintableControl) As LinkPreviewModel
        Dim link As New PrintableControlLink(TryCast(printableControl, IPrintableControl))
        Return New LinkPreviewModel(link)
    End Function

    Private Sub btImprimirPlantilla_ItemClick(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)
        Dim idPlantilla As Integer = bePlantilla.EditValue
        Me.apLinea.LanzaImprimirPlantilla(sender, e, idPlantilla)
    End Sub

    Private Sub btAcciones_ItemClick(sender As Object, e As ItemClickEventArgs)
        Dim idAccion As Integer = beAcciones.EditValue
        Me.apLinea.LanzaEjecutarAccion(sender, e, idAccion)
    End Sub

    Private Sub btActualizar_ItemClick(sender As Object, e As ItemClickEventArgs)
        Me.apLinea.RefrescaUC()
    End Sub

    Private Sub ContenedorLineas_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
        If DXSplashScreen.IsActive Then DXSplashScreen.Close()
    End Sub

    Private Sub ContenedorLineas_Unloaded(sender As Object, e As RoutedEventArgs) Handles Me.Unloaded
        Try
            If apLinea.Contexto IsNot Nothing Then
                If apLinea.Contexto.Connection.State <> System.Data.ConnectionState.Closed Then apLinea.Contexto.Connection.Close()
            End If
        Catch ex As Exception

        End Try
    End Sub
    Private Sub btAyuda_ItemClick(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)
        Me.apLinea.DelegadoAyuda.Invoke(Me.apLinea.uc.GetType.ToString)
    End Sub

    Private Sub btDiseño_ItemClick(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)
        Try
            Dim drs = ObtieneDiseñoActual()
            Me.apLinea.DelegadoDiseño.Invoke(Me.apLinea.Contexto, OperacionDiseñoEnum.GUARDAR, Me.apLinea.uc.GetType.ToString, _DescripcionDiseño, _TodosUsuariosDiseño, drs)
        Catch ex As Exception
            If Me.apLinea.DelegadoErrorNoControlado IsNot Nothing Then Me.apLinea.DelegadoErrorNoControlado.Invoke(Me.apLinea, ex)
            DXMessageBox.Show(ex.Message, "Error btDiseño_Itemclick")
        End Try
    End Sub

    Friend Function ObtieneDiseñoActual() As Byte()
        Dim ld As New DiseñoRejillas
        Dim i As Integer
        Dim lg As List(Of tsGridControl) = Nothing
        tsWPF.ObtieneHijosDeTipo(Of tsGridControl)(ApLineas, lg)
        For Each l In lg
            i += 1
            If l.Name = "" Then l.Name = "tsRejilla-" & i.ToString
            Dim dr As New DiseñoRejilla
            dr.Nombre = l.Name
            dr.Version = "1"
            Dim ms As New MemoryStream
            'Dim ms As New FileStream("c:\tmp\diseño1.xml", FileMode.CreateNew)
            l.SaveLayoutToStream(ms)
            '  l.SaveLayoutToXml("c:\tmp\diseño2.xml")
            'ms.Close()
            dr.Diseño = ms.ToArray
            ld.Rejillas.Add(dr)
        Next
        Dim drs = System.Text.Encoding.Unicode.GetBytes(tsl5.Utilidades.serializar(ld))
        Return drs
    End Function

    Private Sub btRestaurarDiseño_ItemClick(sender As Object, e As DevExpress.Xpf.Bars.ItemClickEventArgs)


        If apLinea.DiseñoOriginal IsNot Nothing Then
            Try
                Dim ld As New DiseñoRejillas
                ld = tsl5.Utilidades.deserializar(System.Text.Encoding.Unicode.GetString(apLinea.DiseñoOriginal), ld.GetType)
                Dim i As Integer
                Dim lg As List(Of tsGridControl) = Nothing
                tsWPF.ObtieneHijosDeTipo(Of tsGridControl)(ApLineas, lg)
                For Each l In lg
                    i += 1
                    If l.Name = "" Then l.Name = "tsRejilla-" & i.ToString
                    Try
                        If ld.Rejillas.Any(Function(x) x.Nombre = l.Name) Then
                            Dim dr As DiseñoRejilla = ld.Rejillas.Where(Function(x) x.Nombre = l.Name).First
                            l.RestoreLayoutFromStream(New System.IO.MemoryStream(dr.Diseño))
                        End If
                    Catch ex As Exception
                        Debug.Write("Error DelegadoDiseño Rejilla")
                    End Try
                Next
                Dim drs = System.Text.Encoding.Unicode.GetBytes(tsl5.Utilidades.serializar(ld))
                Me.apLinea.DelegadoDiseño.Invoke(Me.apLinea.Contexto, OperacionDiseñoEnum.RESTAURAR_ORIGINAL, Me.apLinea.uc.GetType.ToString, _DescripcionDiseño, _TodosUsuariosDiseño, drs)
            Catch ex As Exception
                If Me.apLinea.DelegadoErrorNoControlado IsNot Nothing Then Me.apLinea.DelegadoErrorNoControlado.Invoke(Me.apLinea, ex)
            End Try
        End If
    End Sub

    Private Sub btGuardarDiseñoComo_ItemClick(sender As Object, e As ItemClickEventArgs)
        Try
            Dim drs = ObtieneDiseñoActual()
            Me.apLinea.DelegadoDiseño.Invoke(Me.apLinea.Contexto, OperacionDiseñoEnum.GUARDAR_COMO, Me.apLinea.uc.GetType.ToString, _DescripcionDiseño, _TodosUsuariosDiseño, drs)
        Catch ex As Exception
            If Me.apLinea.DelegadoErrorNoControlado IsNot Nothing Then Me.apLinea.DelegadoErrorNoControlado.Invoke(Me.apLinea, ex)
            DXMessageBox.Show(ex.Message, "Error btDiseño_Itemclick")
        End Try

    End Sub

    Private Sub btAbrirDiseñoGuardado_ItemClick(sender As Object, e As ItemClickEventArgs)
        Dim b = Me.apLinea.DelegadoDiseño.Invoke(Me.apLinea.Contexto, OperacionDiseñoEnum.ABRIR_DISEÑO_GUARDADO, Me.apLinea.uc.GetType.ToString, _DescripcionDiseño, _TodosUsuariosDiseño, Nothing)
        If b IsNot Nothing Then
            Dim ld As New DiseñoRejillas
            ld = tsl5.Utilidades.deserializar(System.Text.Encoding.Unicode.GetString(b), ld.GetType)
            Dim i As Integer
            Dim lg As List(Of tsGridControl) = Nothing
            tsWPF.ObtieneHijosDeTipo(Of tsGridControl)(Me, lg)
            For Each l In lg
                i += 1
                If l.Name = "" Then l.Name = "tsRejilla-" & i.ToString
                Try
                    If ld.Rejillas.Any(Function(x) x.Nombre = l.Name) Then
                        Dim dr As DiseñoRejilla = ld.Rejillas.Where(Function(x) x.Nombre = l.Name).First
                        l.RestoreLayoutFromStream(New System.IO.MemoryStream(dr.Diseño))
                    End If
                Catch ex As Exception
                    If Me.apLinea.DelegadoErrorNoControlado IsNot Nothing Then Me.apLinea.DelegadoErrorNoControlado.Invoke(Me.apLinea, ex)
                    DXMessageBox.Show(ex.Message, "Error btDiseño_Itemclick")
                End Try
            Next
        End If
    End Sub

    Private Sub BtExportar_ItemClick(sender As Object, e As ItemClickEventArgs)

        Dim vista As TableView = Me.apLinea.Rejilla.View

        Dim sfd As New SaveFileDialog
        sfd.FileName = IO.Path.GetDirectoryName("Exportacion") & (Me.apLinea.Rejilla.NombreTablaBase.NothingAVacio & " Exportacion.xlsx").Trim
        sfd.Filter = "Fichero Excel (*.xls, *.xlsx, *.csv)|*.xls;*.xlsx;*.csv"
        sfd.DefaultExt = ".xlsx"
        If sfd.ShowDialog Then
            Select Case IO.Path.GetExtension(sfd.FileName).ToLower
                Case ".xls"
                    vista.ExportToXls(sfd.FileName)
                Case ".xlsx"
                    vista.ExportToXlsx(sfd.FileName)
                Case ".csv"
                    vista.ExportToCsv(sfd.FileName)
            End Select
            Process.Start(sfd.FileName)
        End If
    End Sub
    Private Sub BtCapturar_ItemClick(sender As Object, e As ItemClickEventArgs)
        Dim sficherojpg = tsl5.Utilidades.ObtieneFicheroAleatorio(System.IO.Path.GetTempPath, "jpg")
        IO.File.WriteAllBytes(sficherojpg, Me.apLinea.uc.ObtieneImagen(1, 100))
        Process.Start(sficherojpg)
    End Sub
End Class
