VERSION 5.00
Object = "{0F987290-56EE-11D0-9C43-00A0C90F29FC}#1.0#0"; "ActBar.ocx"
Object = "{B02F3647-766B-11CE-AF28-C3A2FBE76A13}#2.5#0"; "ss32x25.ocx"
Object = "{CDF3B183-D408-11CE-AE2C-0080C786E37D}#2.1#0"; "Edt32x20.ocx"
Begin VB.Form FCO5015 
   Caption         =   "Archivo Planilla Integrada"
   ClientHeight    =   3405
   ClientLeft      =   60
   ClientTop       =   345
   ClientWidth     =   8010
   BeginProperty Font 
      Name            =   "Arial"
      Size            =   8.25
      Charset         =   0
      Weight          =   400
      Underline       =   0   'False
      Italic          =   0   'False
      Strikethrough   =   0   'False
   EndProperty
   Icon            =   "FCO5015 Archivo Planilla Integrada.frx":0000
   KeyPreview      =   -1  'True
   LinkTopic       =   "Form1"
   MaxButton       =   0   'False
   MDIChild        =   -1  'True
   ScaleHeight     =   3405
   ScaleWidth      =   8010
   Begin VB.CheckBox chkBorrar 
      Caption         =   "Borrar datos ya generados"
      Height          =   255
      Left            =   5160
      TabIndex        =   14
      Top             =   2400
      Width           =   2775
   End
   Begin VB.Frame fraFrame 
      Height          =   2775
      Left            =   120
      TabIndex        =   12
      Top             =   0
      Width           =   4935
      Begin EditLib.fpLongInteger txtFiltroAni 
         Height          =   315
         Left            =   120
         TabIndex        =   0
         Top             =   200
         Width           =   705
         _Version        =   131072
         _ExtentX        =   1244
         _ExtentY        =   556
         _StockProps     =   68
         BackColor       =   -2147483643
         ForeColor       =   -2147483640
         ThreeDInsideStyle=   1
         ThreeDInsideHighlightColor=   -2147483633
         ThreeDInsideShadowColor=   -2147483642
         ThreeDInsideWidth=   1
         ThreeDOutsideStyle=   1
         ThreeDOutsideHighlightColor=   16777215
         ThreeDOutsideShadowColor=   -2147483632
         ThreeDOutsideWidth=   1
         ThreeDFrameWidth=   0
         BorderStyle     =   0
         BorderColor     =   -2147483642
         BorderWidth     =   1
         ButtonDisable   =   0   'False
         ButtonHide      =   0   'False
         ButtonIncrement =   1
         ButtonMin       =   1
         ButtonMax       =   100
         ButtonStyle     =   1
         ButtonWidth     =   0
         ButtonWrap      =   -1  'True
         ButtonDefaultAction=   -1  'True
         ThreeDText      =   0
         ThreeDTextHighlightColor=   -2147483633
         ThreeDTextShadowColor=   -2147483632
         ThreeDTextOffset=   1
         AlignTextH      =   2
         AlignTextV      =   1
         AllowNull       =   0   'False
         NoSpecialKeys   =   3
         AutoAdvance     =   0   'False
         AutoBeep        =   0   'False
         CaretInsert     =   0
         CaretOverWrite  =   3
         UserEntry       =   0
         HideSelection   =   -1  'True
         InvalidColor    =   -2147483637
         InvalidOption   =   0
         MarginLeft      =   3
         MarginTop       =   3
         MarginRight     =   3
         MarginBottom    =   3
         NullColor       =   -2147483637
         OnFocusAlignH   =   0
         OnFocusAlignV   =   0
         OnFocusNoSelect =   0   'False
         OnFocusPosition =   0
         ControlType     =   0
         Text            =   "0"
         MaxValue        =   "2078"
         MinValue        =   "2002"
         NegFormat       =   1
         NegToggle       =   0   'False
         Separator       =   ""
         UseSeparator    =   0   'False
         IncInt          =   1
         BorderGrayAreaColor=   -2147483637
         ThreeDOnFocusInvert=   0   'False
         ThreeDFrameColor=   -2147483633
         Appearance      =   0
         BorderDropShadow=   0
         BorderDropShadowColor=   -2147483632
         BorderDropShadowWidth=   3
         MouseIcon       =   "FCO5015 Archivo Planilla Integrada.frx":030A
      End
      Begin EditLib.fpLongInteger txtFiltroMes 
         Height          =   315
         Left            =   840
         TabIndex        =   1
         Top             =   200
         Width           =   615
         _Version        =   131072
         _ExtentX        =   1085
         _ExtentY        =   556
         _StockProps     =   68
         BackColor       =   -2147483643
         ForeColor       =   -2147483640
         ThreeDInsideStyle=   1
         ThreeDInsideHighlightColor=   -2147483633
         ThreeDInsideShadowColor=   -2147483642
         ThreeDInsideWidth=   1
         ThreeDOutsideStyle=   1
         ThreeDOutsideHighlightColor=   16777215
         ThreeDOutsideShadowColor=   -2147483632
         ThreeDOutsideWidth=   1
         ThreeDFrameWidth=   0
         BorderStyle     =   0
         BorderColor     =   -2147483642
         BorderWidth     =   1
         ButtonDisable   =   0   'False
         ButtonHide      =   0   'False
         ButtonIncrement =   1
         ButtonMin       =   1
         ButtonMax       =   100
         ButtonStyle     =   1
         ButtonWidth     =   0
         ButtonWrap      =   -1  'True
         ButtonDefaultAction=   -1  'True
         ThreeDText      =   0
         ThreeDTextHighlightColor=   -2147483633
         ThreeDTextShadowColor=   -2147483632
         ThreeDTextOffset=   1
         AlignTextH      =   2
         AlignTextV      =   1
         AllowNull       =   0   'False
         NoSpecialKeys   =   3
         AutoAdvance     =   0   'False
         AutoBeep        =   0   'False
         CaretInsert     =   0
         CaretOverWrite  =   3
         UserEntry       =   0
         HideSelection   =   -1  'True
         InvalidColor    =   -2147483637
         InvalidOption   =   0
         MarginLeft      =   3
         MarginTop       =   3
         MarginRight     =   3
         MarginBottom    =   3
         NullColor       =   -2147483637
         OnFocusAlignH   =   0
         OnFocusAlignV   =   0
         OnFocusNoSelect =   0   'False
         OnFocusPosition =   0
         ControlType     =   0
         Text            =   "0"
         MaxValue        =   "12"
         MinValue        =   "1"
         NegFormat       =   1
         NegToggle       =   0   'False
         Separator       =   ""
         UseSeparator    =   0   'False
         IncInt          =   1
         BorderGrayAreaColor=   -2147483637
         ThreeDOnFocusInvert=   0   'False
         ThreeDFrameColor=   -2147483633
         Appearance      =   0
         BorderDropShadow=   0
         BorderDropShadowColor=   -2147483632
         BorderDropShadowWidth=   3
         MouseIcon       =   "FCO5015 Archivo Planilla Integrada.frx":0326
      End
      Begin VB.TextBox txtFiltroSuc 
         Height          =   315
         Left            =   1500
         MaxLength       =   40
         TabIndex        =   2
         Top             =   200
         Width           =   2805
      End
      Begin FPSpread.vaSpread sprDatos 
         Bindings        =   "FCO5015 Archivo Planilla Integrada.frx":0342
         Height          =   2025
         Left            =   120
         TabIndex        =   13
         Top             =   600
         Width           =   4695
         _Version        =   131077
         _ExtentX        =   8281
         _ExtentY        =   3572
         _StockProps     =   64
         BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
            Name            =   "Arial"
            Size            =   8.25
            Charset         =   0
            Weight          =   700
            Underline       =   0   'False
            Italic          =   0   'False
            Strikethrough   =   0   'False
         EndProperty
         MaxCols         =   1
         MaxRows         =   1
         SpreadDesigner  =   "FCO5015 Archivo Planilla Integrada.frx":0358
      End
   End
   Begin VB.Frame fraNuevo 
      Caption         =   "Nuevo Registro"
      ForeColor       =   &H00FF0000&
      Height          =   2295
      Left            =   5160
      TabIndex        =   11
      Top             =   0
      Width           =   2775
      Begin VB.ComboBox cboTipoPlanilla 
         Height          =   330
         ItemData        =   "FCO5015 Archivo Planilla Integrada.frx":04B1
         Left            =   1080
         List            =   "FCO5015 Archivo Planilla Integrada.frx":04B3
         Style           =   2  'Dropdown List
         TabIndex        =   10
         Top             =   1800
         Width           =   1575
      End
      Begin VB.ComboBox cboSuc 
         Height          =   330
         Left            =   1080
         Style           =   2  'Dropdown List
         TabIndex        =   8
         Top             =   1320
         Width           =   1455
      End
      Begin VB.ComboBox cboMes 
         Height          =   330
         ItemData        =   "FCO5015 Archivo Planilla Integrada.frx":04B5
         Left            =   1080
         List            =   "FCO5015 Archivo Planilla Integrada.frx":04DD
         Style           =   2  'Dropdown List
         TabIndex        =   6
         Top             =   840
         Width           =   1215
      End
      Begin VB.ComboBox cboAño 
         Height          =   330
         Left            =   1080
         Style           =   2  'Dropdown List
         TabIndex        =   4
         Top             =   360
         Width           =   975
      End
      Begin VB.Label lblLabels 
         AutoSize        =   -1  'True
         BackStyle       =   0  'Transparent
         Caption         =   "&Tipo:"
         Height          =   210
         Index           =   1
         Left            =   240
         TabIndex        =   9
         Top             =   1800
         Width           =   345
      End
      Begin VB.Label lblLabels 
         AutoSize        =   -1  'True
         BackStyle       =   0  'Transparent
         Caption         =   "&Sucursal:"
         Height          =   210
         Index           =   0
         Left            =   240
         TabIndex        =   7
         Top             =   1320
         Width           =   690
      End
      Begin VB.Label lblLabels 
         AutoSize        =   -1  'True
         BackStyle       =   0  'Transparent
         Caption         =   "&Mes:"
         Height          =   210
         Index           =   8
         Left            =   240
         TabIndex        =   5
         Top             =   840
         Width           =   345
      End
      Begin VB.Label lblLabels 
         AutoSize        =   -1  'True
         BackStyle       =   0  'Transparent
         Caption         =   "&Año:"
         Height          =   210
         Index           =   2
         Left            =   240
         TabIndex        =   3
         Top             =   360
         Width           =   345
      End
   End
   Begin VB.Label lblCerrado 
      BackStyle       =   0  'Transparent
      Caption         =   "Período cerrado en autoliquidación"
      ForeColor       =   &H00C00000&
      Height          =   255
      Left            =   5400
      TabIndex        =   15
      Top             =   2400
      Visible         =   0   'False
      Width           =   2535
   End
   Begin ActiveBarLibraryCtl.ActiveBar abToolbar 
      Left            =   240
      Top             =   2880
      _ExtentX        =   847
      _ExtentY        =   847
      BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851} 
         Name            =   "Arial"
         Size            =   8.25
         Charset         =   0
         Weight          =   400
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      Bands           =   "FCO5015 Archivo Planilla Integrada.frx":0546
   End
End
Attribute VB_Name = "FCO5015"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Private MAdo As ODBC.ODBCDirecto
Private Micx As Integer 'Conexión
Private MoBitacora As New ADAMBitacora.Bitacora
Private WithEvents clsSpread As NSpread
Attribute clsSpread.VB_VarHelpID = -1
Private MsSql As String
Private MsWhereAdi As String
Private MsOrden As String
Private MbOrdenAsc As Boolean
Private MsAntOrden As String
Private Enum Origenes
    Procesar = 1
    VistaPrevia = 2
End Enum
Private MsPath As String
Private clsCarpeta As New cdtCarpeta

Private Sub abToolbar_Click(ByVal Tool As ActiveBarLibraryCtl.Tool)
    Select Case LCase(Tool.Name)
        Case "tlseltodo": SeleccionaRegistros sprDatos, "1"
        Case "tlselnada": SeleccionaRegistros sprDatos, "0"
        Case "tlalta": Altas
        Case "tlbaja": Bajas
        Case "tlexpand": PedirPath
        Case "tlejecuta": MostrarReporte Procesar
        Case "tlpreview": MostrarReporte VistaPrevia
        Case "tlguarda": GuardaCambios
        Case "tlordena": OrdenarDatos
        Case "tlrenueva": RenuevaDatos
        Case "tlsalida": Unload Me
        Case "tltrabaja": TrabajarCon
    End Select
End Sub

Private Sub cboAño_KeyPress(KeyAscii As Integer)
    If KeyAscii = vbKeyReturn Then
        KeyAscii = 0
        SendEnter
    End If
End Sub

Private Sub cboMes_KeyPress(KeyAscii As Integer)
    If KeyAscii = vbKeyReturn Then
        KeyAscii = 0
        SendEnter
    End If
End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
    If Not bGuardarCambios Then Cancel = True
End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    Select Case KeyCode
        Case vbKeyF3: Unload Me
        Case vbKeyF5: RenuevaDatos
        Case vbKeyF6: Altas
        Case vbKeyF7: Bajas
    End Select
End Sub

Private Sub Form_Load()
    GbAError = False
    Me.Tag = GiVenMax%
    Gven(Val(Me.Tag)).icx = Gicx%
    Micx = Gven(Val(Me.Tag)).icx
    Set MAdo = Gtc(Micx).Ado
    
    'Checa nivel de seguridad
    Gven(Val(Me.Tag)).iNivSeguridad = iObtenNivSeguridad(GsOper, GsUid, Micx)
    If Gven(Val(Me.Tag)).iNivSeguridad = 0 Then
        Screen.MousePointer = vbDefault
        Me.Top = -10000
        GbAError = True
        Exit Sub
    End If
        
    Set clsSpread = New NSpread
    GAdam.ObtieneColores
        
    'Tamaño de la forma
    If WindowState = 0 Then
        Width = 8139
        Height = 3915
    End If
    
    Caption = GsDsn & " / " & GsCveCia & " - Archivo Planilla Integrada"
    GbAlterarToolBar = True
    AsignaIconos abToolbar, 3, LSELTODO, LSELNADA, LEXPAND, LALTA, LBAJA, LPREVIEW, LEJECUTA, LTRABAJA, LORDENA, LRENUEVA, LGUARDA, LSALIDA
    GbAlterarToolBar = False
    ToolInicioGrupo abToolbar, 3, True, 2, 3, 5, 7, 8, 9, 10
    
    LlenarCombos
    
    MsSql = "SELECT procesar, anio, mes, sucursal, suc_des, sit_periodo, tipo_planilla FROM vw_fco_procesos_pi WHERE compania = '" & GsCveCia & "'"
    MsWhereAdi = ""
    MsOrden = " ORDER BY 4"
    txtFiltroAni = IIf(Month(Date) = 12, Year(Date) - 1, Year(Date))
    txtFiltroMes = IIf(Month(Date) = 1, 12, Month(Date) - 1)
    RenuevaDatos
    
    If sprDatos.MaxRows > 0 Then
        sprDatos_LeaveCell 1, 1, 1, 1, False
    End If
    
    sprDatos.ShadowColor = GAdam.GLSPREADINACTIVO
    sprDatos.ShadowText = GAdam.GLTEXTOINACTIVO
    
    CreaBitacora
    
    MsPath = sLeerIni("FCO.ini", "General", "Ruta")

End Sub

Private Sub Form_Unload(Cancel As Integer)
    Set MAdo = Nothing
    Set MoBitacora = Nothing
    Set clsSpread = Nothing
    Gtc(Micx).ihijas = Gtc(Micx).ihijas - 1
    Set FCO5015 = Nothing
End Sub

Private Sub sprDatos_Change(ByVal Col As Long, ByVal Row As Long)
    MoBitacora.mCambia
End Sub

Private Sub sprDatos_Click(ByVal Col As Long, ByVal Row As Long)
    If Row > 0 Then
        With sprDatos
            .Col = -1
            .Row = -1
            .BackColor = vbWhite
            .Row = Row
            .BackColor = vbCyan
        End With
        RecuperarDatos Row
    End If
End Sub

Private Sub sprDatos_DblClick(ByVal Col As Long, ByVal Row As Long)
    MostrarReporte VistaPrevia
End Sub

Private Sub sprDatos_EditMode(ByVal Col As Long, ByVal Row As Long, ByVal Mode As Integer, ByVal ChangeMade As Boolean)
    MoBitacora.mCambia
End Sub

Private Sub sprDatos_GotFocus()
    sprDatos.ShadowColor = GAdam.GLSPREADACTIVO
    sprDatos.ShadowText = GAdam.GLTEXTOACTIVO
    abToolbar.Bands(0).Tools(1).Enabled = True
End Sub

Private Sub sprDatos_LeaveCell(ByVal Col As Long, ByVal Row As Long, ByVal NewCol As Long, ByVal NewRow As Long, Cancel As Boolean)
    Dim vaux As Variant
    chkBorrar.Value = vbUnchecked
    
    If NewRow > 0 Then
        sprDatos.GetText 6, NewRow, vaux
        If Val(vaux) = 2 Then
            chkBorrar.Visible = False
            lblCerrado.Visible = True
        Else
            chkBorrar.Visible = True
            lblCerrado.Visible = False
        End If
    End If
End Sub

Private Sub sprDatos_LostFocus()
    sprDatos.ShadowColor = GAdam.GLSPREADINACTIVO
    sprDatos.ShadowText = GAdam.GLTEXTOINACTIVO
    abToolbar.Bands(0).Tools(1).Enabled = False
End Sub

Private Sub txtFiltroAni_KeyPress(KeyAscii As Integer)
    If KeyAscii = vbKeyReturn Then RenuevaDatos
End Sub

Private Sub txtFiltroMes_KeyPress(KeyAscii As Integer)
    If KeyAscii = vbKeyReturn Then RenuevaDatos
End Sub

Private Sub txtFiltroSuc_KeyPress(KeyAscii As Integer)
    If KeyAscii = vbKeyReturn Then RenuevaDatos
End Sub

Private Sub Altas()
    With sprDatos
        .Col = -1
        .Row = -1
        .BackColor = vbWhite
    End With
    LimpiarCampos
    chkBorrar.Visible = True
    lblCerrado.Visible = False
    cboAño.Enabled = True
    cboMes.Enabled = True
    If cboSuc.ListCount > 1 Then cboSuc.Enabled = True
    cboTipoPlanilla.Enabled = True
    fraNuevo.Caption = "Nuevo Registro"
    On Error Resume Next
    cboAño.SetFocus
End Sub

Private Sub AplicaFiltros()
    MsWhereAdi = ""
    If Trim(txtFiltroAni) <> "" Then MsWhereAdi = " AND anio = " & txtFiltroAni
    If Trim(txtFiltroMes) <> "" Then MsWhereAdi = MsWhereAdi & " AND mes = " & txtFiltroMes
    If Trim(txtFiltroSuc) <> "" Then MsWhereAdi = MsWhereAdi & " AND suc_des LIKE '%" & txtFiltroSuc & "%'"
End Sub

Private Sub Bajas()
    If sprDatos.VirtualMaxRows <= 0 Then Exit Sub
    MoBitacora.mBorra
    With sprDatos
        .Col = -1
        .Row = -1
        .BackColor = vbWhite
    End With
End Sub

Private Function bGuardarCambios() As Boolean
    bGuardarCambios = True
    If MoBitacora.pTransActual > 0 Then
        Select Case clsMsgbox.Mensaje("¿Desea guardar los cambios?", mSiNoCancelar, mConfirma, GsTitMsg)
            Case vbYes
                GuardaCambios
                bGuardarCambios = True
            Case vbNo
                MoBitacora.mVaciaBuffer
                bGuardarCambios = True
            Case vbCancel: bGuardarCambios = False
        End Select
    End If
End Function

Private Sub CreaBitacora()
   MoBitacora.mCreaBitacora sprDatos, MAdo.lhEnv, MAdo.lhDbc, MAdo.lhstmt, MAdo
   MoBitacora.p_ConfirmaBaja = True
   MoBitacora.mTablaSPInfo 1, "sp_fco_del_procesos_pi", "'" & GsCveCia & "'", 2, 3, 4, 7
   MoBitacora.mTablaSPInfo 2, "sp_fco_upd_procesos_pi", "'" & GsCveCia & "'", 2, 3, 4, 1, 7
End Sub

Private Sub GuardaCambios()
    Dim sSP As String
    Dim sSUC As String
    Dim bNoAct As Boolean

    If cboAño.ListIndex = -1 Then bNoAct = True
    If cboMes.ListIndex = -1 Then bNoAct = True
    If cboSuc.ListIndex = -1 Then bNoAct = True
    If cboTipoPlanilla.ListIndex = -1 Then bNoAct = True

    Screen.MousePointer = vbHourglass
    
    'Análisis de la Sucursal
    If Not bNoAct Then
        If cboSuc.ListIndex = 0 And cboSuc.ListCount = 1 Then sSUC = ""
        If cboSuc.ListIndex = 0 And cboSuc.ListCount > 1 Then sSUC = "0"
        If cboSuc.ListIndex > 0 Then sSUC = cboSuc.Text
        
        If cboAño.Enabled Then
            sSP = "sp_fco_ins_procesos_pi"
            MAdo.Sql = sSP & " '" & GsCveCia & "'," & cboAño.Text & "," & (cboMes.ListIndex + 1) & ",'" & sSUC & "', '" & Left(cboTipoPlanilla.Text, 1) & "'"
            MAdo.ExecSQL
        End If
    End If
    GbRen = MoBitacora.mActualizaBD
    MoBitacora.mVaciaBuffer
        
    txtFiltroAni = cboAño.Text
    txtFiltroMes = CStr(cboMes.ListIndex + 1)
    txtFiltroSuc = ""
    LimpiarCampos
    RenuevaDatos
    
    Screen.MousePointer = vbDefault
End Sub

Private Sub LimpiarCampos()
    cboAño.ListIndex = -1
    cboMes.ListIndex = -1
    If cboSuc.ListCount > 1 Then cboSuc.ListIndex = -1
End Sub

Private Sub LlenarCombos()
    'Combo de Años
    MAdo.Sql = "SELECT DISTINCT cp.anio" & _
    " FROM calendario_procesos cp, cal_proc_cias cpc" & _
    " WHERE cp.id_calendario = cpc.id_calendario" & _
    " AND cpc.compania = '" & GsCveCia & "' AND cpc.sit_periodo = 2" & _
    " ORDER BY 1 DESC"
    If MAdo.SendSQL Then
        Do Until MAdo.EOF
            cboAño.AddItem MAdo.GetField(1)
            MAdo.Mnext
        Loop
    End If
    
    'Combo de Sucursales
    MAdo.Sql = "SELECT forma_presentacion FROM vw_fco_cias_datos_adi WHERE compania = '" & GsCveCia & "'"
    MAdo.SendSQL
    If Not MAdo.EOF Then
        If UCase(MAdo.GetField(1)) = "S" Then
            cboSuc.AddItem "(Todas)"
            MAdo.Sql = "SELECT sucursal, RTRIM(descripcion)" & _
            " FROM vw_fco_sucursales" & _
            " WHERE compania = '" & GsCveCia & "'" & _
            " AND autoliquida = 1" & _
            " ORDER BY 1"
            If MAdo.SendSQL Then
                Do Until MAdo.EOF
                    cboSuc.AddItem MAdo.GetField(1)
                    MAdo.Mnext
                Loop
            End If
        Else
            cboSuc.AddItem "(Consolidado)"
        End If
    End If
    If cboSuc.ListCount = 1 Then
        cboSuc.ListIndex = 0
        cboSuc.Enabled = False
    End If
    
    'Combo Tipos de Planilla
    MAdo.Sql = "SELECT descripcion FROM criterios_valores_col WHERE campo = 'tipo_planilla' ORDER BY item"
    MAdo.SendSQL
    If Not MAdo.EOF Then
        Do Until MAdo.EOF
            cboTipoPlanilla.AddItem MAdo.GetField(1)
            MAdo.Mnext
        Loop
    End If
    If cboTipoPlanilla.ListCount > 0 Then cboTipoPlanilla.ListIndex = 0
End Sub

Private Sub MostrarReporte(Origen As Origenes)
    Dim i As Long
    Dim j As Long
    Dim iFilaIni As Long
    Dim iFilaFin As Long
    Dim vaux As Variant
    Dim bJuega As Boolean
    Dim sAño As String
    Dim sMes As String
    Dim sSUC As String
    Dim sTip As String
    Dim sSep As String
    Dim sCarpeta As String
    Dim sArchivo As String
    Dim sFunSub As String

    On Error GoTo NoPude
    
    If Origen = VistaPrevia And sprDatos.ActiveRow < 1 Then
        clsMsgbox.Mensaje "No hay ningún registro seleccionado", mAceptar, mAdvierte, GsTitMsg
        Exit Sub
    End If
        
    Screen.MousePointer = vbHourglass
    
    If Origen = VistaPrevia Then
        iFilaIni = sprDatos.ActiveRow
        iFilaFin = iFilaIni
    Else
        iFilaIni = 1
        iFilaFin = sprDatos.MaxRows
    End If
    
    j = 0
    For i = iFilaIni To iFilaFin
        bJuega = True
        With sprDatos
            .GetText 1, i, vaux
            If Val(vaux) = 0 And Origen = Procesar Then
                bJuega = False
            Else
                .GetText 2, i, vaux
                sAño = CStr(vaux)
                .GetText 3, i, vaux
                sMes = CStr(vaux)
                .GetText 4, i, vaux
                sSUC = CStr(vaux)
                .GetText 7, i, vaux
                sTip = CStr(vaux)
            End If
        End With
        
        If bJuega Then
            j = j + 1
            MAdo.Sql = "sp_fco_planilla_integrada " & _
            "'" & GsCveCia & "'," & sAño & "," & sMes & ",'" & sSUC & "'," & _
            IIf(chkBorrar.Value = vbChecked, "1", "0") & ",'" & sTip & "'"
            If MAdo.ExecSQL = -1 Then GoTo NoPude
        End If
    Next i
    
    If j = 0 Then
        clsMsgbox.Mensaje "No se encontró ningún registro seleccionado para procesar", mAceptar, mAdvierte, GsTitMsg
    Else
        For i = iFilaIni To iFilaFin
            bJuega = True
            With sprDatos
                .GetText 1, i, vaux
                If Val(vaux) = 0 And Origen = Procesar Then
                    bJuega = False
                Else
                    .GetText 2, i, vaux
                    sAño = CStr(vaux)
                    .GetText 3, i, vaux
                    sMes = CStr(vaux)
                    .GetText 4, i, vaux
                    sSUC = CStr(vaux)
                    .GetText 7, i, vaux
                    sTip = CStr(vaux)
                End If
            End With
            If bJuega Then
                If MsPath = "" Then PedirPath
                If MsPath = "" Then
                    clsMsgbox.Mensaje "Debe elegir una ruta de salida válida para poder generar los archivos", mAceptar, mAdvierte, GsTitMsg
                    GoTo NoPude
                End If
                sSep = IIf(Trim(Right(MsPath, 1)) = "\", "", "\")
                'Carpetas por Compañia
                sCarpeta = Trim(MsPath) & sSep & Trim(GsCveCia)
                If Dir(sCarpeta, vbDirectory) = "" Then MkDir sCarpeta
                If sSUC <> "" Then 'Si son varias sucursales crear una carpeta por cada una
                    sCarpeta = sCarpeta & "\" & sSUC
                    If Dir(sCarpeta, vbDirectory) = "" Then MkDir sCarpeta
                End If
        
                sArchivo = sCarpeta & "\" & "PI " & GsCveCia & IIf(sSUC <> "", "-" & sSUC, "") & " - " & sAño & " " & sRellenar(sMes, "0", 0, 2) & sTip & ".txt"
        
                If MAdo.DBMS = "SQLSERVER" Then
                    sFunSub = "SubString"
                Else
                    sFunSub = "SubStr"
                End If
        
                Open sArchivo For Output As #1
        
                'Encabezado
                MAdo.Sql = "SELECT " & sFunSub & "(registro1,1,255)," & sFunSub & "(registro1, 256, 255) FROM vw_fco_integrada_rt01" & _
                " WHERE compania = '" & GsCveCia & "' AND anio = " & sAño & " AND mes = " & sMes & IIf(sSUC <> "", " AND sucursal = '" & sSUC & "'", "") & _
                " AND tipo_planilla = '" & sTip & "'"
                If MAdo.SendSQL Then
                    Do Until MAdo.EOF
                        Print #1, MAdo.GetField(1) & MAdo.GetField(2)
                        MAdo.Mnext
                    Loop
                End If
                'Detalle
                MAdo.Sql = "SELECT " & sFunSub & "(registro2,1,255)," & sFunSub & "(registro2, 256, 255) FROM vw_fco_integrada_rt02" & _
                " WHERE compania = '" & GsCveCia & "' AND anio = " & sAño & " AND mes = " & sMes & IIf(sSUC <> "", " AND sucursal = '" & sSUC & "'", "") & _
                " AND tipo_planilla = '" & sTip & "'" & _
                " ORDER BY secuencia"
                If MAdo.SendSQL Then
                    Do Until MAdo.EOF
                        Print #1, MAdo.GetField(1) & MAdo.GetField(2)
                        MAdo.Mnext
                    Loop
                End If
                
                'Totales
                For j = 4 To 5 '3 to 11 solo se muestran salud y riesgos
                    MAdo.Sql = "SELECT registro FROM vw_fco_integrada_rt" & sRellenar(CStr(j), "0", 0, 2) & _
                    " WHERE compania = '" & GsCveCia & "' AND anio = " & sAño & " AND mes = " & sMes & IIf(sSUC <> "", " AND sucursal = '" & sSUC & "'", "") & _
                    " AND tipo_planilla = '" & sTip & "'" & _
                    " ORDER BY secuencia"
                    If MAdo.SendSQL Then
                        Do Until MAdo.EOF
                            Print #1, MAdo.GetField(1)
                            MAdo.Mnext
                        Loop
                    End If
                Next j
        
                Close #1
            End If
        Next i
    End If
        
    If Origen = VistaPrevia Then
        Dim lValDev As Long
        lValDev = ShellExecute(Me.hwnd, "Open", sArchivo, "", "", 1)
    Else
        clsMsgbox.Mensaje "Los archivos fueron generados en la carpeta:" & vbCrLf & vbCrLf & Trim(MsPath) & sSep & Trim(GsCveCia), mAceptar, mAdvierte, GsTitMsg
    End If
    
    chkBorrar.Value = vbUnchecked
        
NoPude:
    Screen.MousePointer = vbDefault
    If Err > 0 Then
        clsMsgbox.Mensaje Err & " " & Err.Description, mAceptar, mAdvierte, GsTitMsg
    End If
End Sub

Private Sub OrdenarDatos()
    Screen.MousePointer = vbHourglass
    If MsAntOrden = CStr(sprDatos.ActiveCol) Then
        MbOrdenAsc = Not (MbOrdenAsc)
    Else
        MbOrdenAsc = True
    End If
    MsOrden = " Order By " & CStr(sprDatos.ActiveCol) & IIf(MbOrdenAsc, "", "DESC")
    MsAntOrden = CStr(sprDatos.ActiveCol)
    RenuevaDatos
    Screen.MousePointer = vbDefault
End Sub

Private Sub PedirPath()
    MsPath = clsCarpeta.PedirCarpeta(MsPath)
    If MsPath <> "" Then
        GuardarIni "FCO.ini", "General", "Ruta", MsPath
    End If
End Sub

Private Sub RecuperarDatos(Row As Long)
    Dim vaux As Variant

    LimpiarCampos
    fraNuevo.Caption = "Edición de Registro"
    sprDatos.GetText 2, Row, vaux
    cboAño.ListIndex = iBuscarDatoEnCombo(cboAño, CStr(vaux))
    sprDatos.GetText 3, Row, vaux
    cboMes.ListIndex = Val(vaux) - 1
    sprDatos.GetText 4, Row, vaux
    If cboSuc.ListCount = 1 And CStr(vaux) = "" Then
        cboSuc.ListIndex = 0
    Else
        cboSuc.ListIndex = iBuscarDatoEnCombo(cboSuc, CStr(vaux))
    End If
    cboAño.Enabled = False
    cboMes.Enabled = False
    cboSuc.Enabled = False
    cboTipoPlanilla.Enabled = False
End Sub

Private Sub RenuevaDatos()
    If Not bGuardarCambios Then Exit Sub
    
    Screen.MousePointer = vbHourglass

    sprDatos.VisibleCols = 4
    With sprDatos
        .Visible = False
        .Action = 28
        GAdam.ConfiguracionSpread sprDatos
        .Row = 0
        .Col = 1: .Text = " "
        .Col = 2: .Text = "Año"
        .Col = 3: .Text = "Mes"
        .Col = 4: .Text = "Codigo Sucursal (Oculto)"
        .Col = 5: .Text = "Sucursal"
        .Col = 6: .Text = "sit_periodo (oculto)"
        .Col = 7: .Text = "Tipo"
        ConfiguraSpreadJCL sprDatos
        .UserResizeCol = 2
    End With
    
    AplicaFiltros
    MAdo.Sql = MsSql & MsWhereAdi & MsOrden
    If Not MAdo.SendSQL Then Exit Sub
    clsSpread.LlenaSpread 0, sprDatos, MAdo, MAdo.lhDbc, MAdo.lhstmt
    
    With sprDatos
        .ColWidth(1) = 2
        .ColWidth(2) = 5
        .ColWidth(3) = 4
        .Col = 4: .ColHidden = True
        .ColWidth(5) = 24.9
        .ColWidth(7) = 4
        .Col = 1: .Row = -1: .CellType = 10
        .Col = 2: .Row = -1: .Lock = True
        .Col = 3: .Row = -1: .Lock = True
        .Col = 5: .Row = -1: .Lock = True
        .Col = 6: .ColHidden = True
        .Col = 7: .Row = -1: .Lock = True
    End With
    GAdam.AjustaSpread sprDatos, 5
    sprDatos.Visible = True
    
    If sprDatos.MaxRows > 0 Then
        sprDatos_LeaveCell 1, 1, 1, 1, True
    End If
    
    Screen.MousePointer = vbDefault
End Sub

Private Sub TrabajarCon()
    Dim vaux As Variant
    If sprDatos.ActiveRow > 0 And sprDatos.MaxRows > 0 Then
        Screen.MousePointer = vbHourglass
        With sprDatos
            .GetText 2, .ActiveRow, vaux
            GsAño = vaux
            .GetText 3, .ActiveRow, vaux
            GsMes = vaux
            .GetText 4, .ActiveRow, vaux
            GsDatoAux = vaux 'Sucursal
            .GetText 5, .ActiveRow, vaux
            GsTitulo = vaux
            .GetText 7, .ActiveRow, vaux
            GsTipo = vaux
        End With
        FCO5015T.Show 1
    End If
End Sub
