#include <alloc.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#include <graphics.h>

#include "c:\program\src_dos\libs\make_bot\make_bot.h"
#include "c:\program\src_dos\libs\bdatos\bdatos.hh"
#include "tpv_def.h"

#define NLINEAS_GEMP   7

#define NORMAL     0
#define BARRAS     1

extern BDatos B_IVentas3;             // Archivo de Ventas 3 de 3 ( Ventas Empleados   )
extern INFORME3_VENTAS S_IVentas3;    // Ventas Empleados   ( 3 de 3 )

                               // Dia y mes actual para la gestion
extern char DiaActual, MesActual;
extern long RegCompras[31 + 2];// Indice para cado uno de los dias del mes + 2

extern char EmpresaActual[9];  // Empresa a la que se le realizan las gestiones

extern char AjusteCalendario;  // Ajuste para los dias del calendario
extern char DiasMes;           // Dias que tiene el mes actual

extern unsigned long GastosCompras;   // Gastos del dia a evaluar

extern unsigned long GastosComprasD[32];

 /*************************************\
|                                       |
|      Parte Principal del M�dulo       |
|                                       |
 \*************************************/
void ObtenCoordenadasGEmp( char columna, char linea, int *X0, int *Y0, int *X1, int *Y1 );
void GraficasEmpleadosMes( void );

extern void MuestraGEmp( char columna, long linea, char como );
extern void MuestraMesActual( char MesMostrar );
extern void MuestraAyudaGEmp ( char columna );

void MuestraDatosGEmp( long RowStart );


//  ���������������������������������������������������������������������
// �                     Parte principal del m�dulo                       �
//  ���������������������������������������������������������������������


 /**************************************************************************\
|*                                                                          *|
|*  GraficaVentaEmpleados                                                          *|
|*                                                                          *|
|*  Descripci�n:                                                            *|
|*              Recorre el mes dado, y nos ofrece una gr�fica de las ventas *|
|*              por empleado...                                             *|
|*                                                                          *|
|*  Entradas: (ninguna)                                                     *|
|*  Salidas:  (ninguna)                                                     *|
|*                                                                          *|
 \**************************************************************************/
void GraficaVentaEmpleados( void )
{
 char ok = 0, i;
 int BPush;
 int CurrRow, CurrCol, oldCol;
 long CurrGEmp;
 char buffer[80];

 // Actualizasmos el mes y dia actual en curso
 MesActual = FechaGestionActual.da_mon;

 // Rellenamos la pantalla con un fondo atractivo...
 setfillstyle( Config.FillBgS, Config.FillBgC ); bar( 0, 0, 640, 480 );
 Imprime_Estaticos( 72, "systm\\Tpv.img");     // Imprime botones estaticos 'Seccion 40'

 // Calculamos los dias que tiene el mes y el ajuste necesario
 CalculaAjusteDias( &AjusteCalendario, &DiasMes, MesActual, FechaGestionActual.da_year );

 // Archivo de ventas por empleados ( 3 de 3 )
 sprintf( buffer, "datos\\%s\\VT3-%04d.M--", NEmpresa, FechaGestionActual.da_year/*, MesActual*/ );
 if ( B_IVentas3.AbrirReg( buffer, sizeof( INFORME3_VENTAS ) ) == ERROR )
                                                           Error( 0x01, "Imposible abrir archivo, Ventas diarias 3 de 3" );
 if ( B_IVentas3.Registros() == 0 )
 {
  sprintf( buffer, "A�o seleccionado: %04d", FechaGestionActual.da_year );
  Optar( 0, "Ventas por empleados", " No hay ventas de empleados", "en el a�o seleccionado", buffer, NULL );
  B_IVentas3.CerrarReg();
  return;
 }

 GastosCompras = 0;
 for ( i = 1; i <= DiasMes && i <= 31; i++ )
 {
          GastosComprasD[i] = S_IVentas3.TotalVendido[i-1][MesActual];
          GastosCompras += GastosComprasD[i];
 }

 MuestraDatosGEmp( 0 );

 CurrRow  = 0;
 CurrGEmp = 0;
 CurrCol  = 0; oldCol = -1;

 if ( B_IVentas3.LeeReg( (void *)&S_IVentas3, (CurrGEmp + CurrRow ) ) == ERROR )
                                                              Error(0x01, B_IVentas3.cError );

                         // Mostramos el mes Actual
                         MuestraMesActual( MesActual );
                         GraficasEmpleadosMes();

 ok = 0;
 do {
      if ( CurrCol != oldCol )
      {
       oldCol = CurrCol;       MuestraAyudaGEmp ( CurrCol );
      }

      MuestraGEmp( CurrCol, CurrRow, INTENSO );
      BPush = Comprueba_Secuencia( 2, NULL );
      MuestraGEmp( CurrCol, CurrRow, NORMAL  );

      switch ( BPush )
      {
       case  0:				  // No se pulso ningun BOTON
	       while( kbhit() ) getch();  // Limpiamos posibles teclas en BUFFER
               break;
       case -2:				  // Hay una tecla normal en BUFFER
	       while( kbhit() ) getch();  // Limpiamos posibles teclas en BUFFER
               break;
       case -1:				  // Hay una tecla especial en BUFFER
               switch( getch() )
               {
                 // Flecha Izquierda
                 case  75:
                 case  15:
                       CurrCol--;
                       if ( CurrCol < 0 ) CurrCol = 4;
                       break;
                 // Flecha Derecha
                 case  77:
                 case   9:
                       // Solo se permite acceder a Todo cuando el Codigo es 0
                       CurrCol++;
                       if ( CurrCol > 4 ) CurrCol = 0;
                       break;
                 // Flecha Arriba
                 case  72:
                        if ( (CurrRow + CurrGEmp ) > 0 )
                        {
                         if ( ( CurrRow ) <= 0 )
                         {
                          CurrRow = NLINEAS_GEMP - 1;          CurrGEmp -= NLINEAS_GEMP;
                          if ( CurrGEmp < 0 ) CurrGEmp = 0;

                          while( ( CurrRow + CurrGEmp ) >= B_IVentas3.Registros() && CurrRow > 0 ) CurrRow--;
                          while( ( CurrRow + CurrGEmp ) >= B_IVentas3.Registros() && CurrGEmp > 0 ) CurrGEmp++;

                          // Mostramos datos hasta que se nos acabe la pantalla
                          MuestraDatosGEmp( CurrGEmp );
                         } else {
                          CurrRow --; if ( CurrRow < 0 ) CurrRow = 0;
                         }

                         if ( B_IVentas3.LeeReg( (void *)&S_IVentas3, (CurrGEmp + CurrRow ) ) == ERROR )
                                                             Error(0x01, B_IVentas3.cError );
//                         GraficasEmpleadosMes();
                        }
                       break;
                // Flecha Abajo
                case  80:
                        if ( ( CurrRow + CurrGEmp ) < ( B_IVentas3.Registros() - 1 )  )
                        {
                         if ( ( CurrRow ) >= NLINEAS_GEMP - 1 )
                         {
                           CurrRow = 0;		CurrGEmp += NLINEAS_GEMP;

                           while ( (CurrGEmp + CurrRow) >= B_IVentas3.Registros() ) CurrGEmp--;

                           // Mostramos datos hasta que se nos acabe la pantalla
                           MuestraDatosGEmp( CurrGEmp );
                         } else
                         	CurrRow++;
                        }

                        if ( B_IVentas3.LeeReg( (void *)&S_IVentas3, (CurrGEmp + CurrRow ) ) == ERROR )
                                                                                     Error(0x01, B_IVentas3.cError );
//                         GraficasEmpleadosMes();
                       break;
                // Inicio
                case  71:
                        CurrRow = 0;
                        if ( CurrGEmp != 0 )
                        {
                         CurrGEmp = 0;

                         // Mostramos datos hasta que se nos acabe la pantalla
                         MuestraDatosGEmp( CurrGEmp );
                        }

                        if ( B_IVentas3.LeeReg( (void *)&S_IVentas3, (CurrGEmp + CurrRow ) ) == ERROR )
                                                              Error(0x01, B_IVentas3.cError );

//                         GraficasEmpleadosMes();
                       break;
                // Fin
                case  79:
                        CurrRow = 0;
                        if ( CurrGEmp != B_IVentas3.Registros() - NLINEAS_GEMP )
                        {
                         CurrGEmp = B_IVentas3.Registros() - NLINEAS_GEMP;
                         if ( CurrGEmp < 0 )
                         {
                          CurrGEmp = 0;
                          CurrRow  = B_IVentas3.Registros()-1;
                         }
                         // Mostramos datos hasta que se nos acabe la pantalla
                         MuestraDatosGEmp( CurrGEmp );
                        }

                        if ( B_IVentas3.LeeReg( (void *)&S_IVentas3, (CurrGEmp + CurrRow ) ) == ERROR )
                                                              Error(0x01, B_IVentas3.cError );
//                         GraficasEmpleadosMes();
                       break;
               }
	       break;
       // Imprimir Compras
       case  1:
	       break;
       // Menu Principal
       case  2:
               ok = 1;
               break;
#ifndef DEMOSTRACION
       // Mes Anterior
       case  3:
               MesActual --; if ( MesActual < 1 ) MesActual = 1;

               GastosCompras = 0;
               for ( i = 1; i <= DiasMes && i <= 31; i++ )
               {
                 GastosComprasD[i] = S_IVentas3.TotalVendido[i-1][MesActual];
                 GastosCompras += GastosComprasD[i];
               }

               // Mostramos el mes Actual
               MuestraMesActual( MesActual );

               CurrGEmp = CurrRow = 0;
               // Mostramos datos hasta que se nos acabe la pantalla
               MuestraDatosGEmp( CurrGEmp );

               // Leemos el registro sobre el que estamos posicionados
               if ( B_IVentas3.LeeReg( (void *)&S_IVentas3, CurrRow + CurrGEmp ) == ERROR )
                                                             Error(0x01, B_IVentas3.cError );
               GraficasEmpleadosMes();
	       break;
       // Mes Siguiente
       case  4:
               MesActual ++; if ( MesActual > 12 ) MesActual = 12;
               GastosCompras = 0;
               for ( i = 1; i <= DiasMes && i <= 31; i++ )
               {
                 GastosComprasD[i] = S_IVentas3.TotalVendido[i-1][MesActual];
                 GastosCompras += GastosComprasD[i];
               }

               // Mostramos el mes Actual
               MuestraMesActual( MesActual );

               CurrGEmp = CurrRow = 0;
                                                        // PosicionDia( DiaActual
               // Mostramos datos hasta que se nos acabe la pantalla
               MuestraDatosGEmp( CurrGEmp );

               // Leemos el registro sobre el que estamos posicionados
               if ( B_IVentas3.LeeReg( (void *)&S_IVentas3, CurrRow + CurrGEmp ) == ERROR )
                                                             Error(0x01, B_IVentas3.cError );
                         GraficasEmpleadosMes();
               break;
#else
       // Retroceder//Avanzar mes
       case  3:
       case  4:
            Optar( 0, "VERSION DEMOSTRACION", "En esta versi�n no se",  "permiten m�dificar la clave.", NULL );
            break;
#endif

       // Retroceso R�pido
       case  5:
#ifndef DEMOSTRACION
               CurrRow = NLINEAS_GEMP - 1;          CurrGEmp -= NLINEAS_GEMP;
               if ( CurrGEmp < 0 ) CurrGEmp = 0;

               while( ( CurrRow + CurrGEmp ) >= B_IVentas3.Registros() && CurrRow > 0 ) CurrRow--;
               while( ( CurrRow + CurrGEmp ) >= B_IVentas3.Registros() && CurrGEmp > 0 ) CurrGEmp++;

               // Mostramos datos hasta que se nos acabe la pantalla
               MuestraDatosGEmp( CurrGEmp );
               // Leemos el registro sobre el que estamos posicionados
               if ( B_IVentas3.LeeReg( (void *)&S_IVentas3, CurrRow + CurrGEmp ) == ERROR )
                                                             Error(0x01, B_IVentas3.cError );
//                         GraficasEmpleadosMes();
#endif
	       break;
       // P�gina principal de la compra
       case  6:
//               MuestraDatosGEmp( NUEVA_BUSQUEDA );
	       break;
       // Cambiar el mes a observar
       case  7:
	       break;
       // Siguiente p�guina de compras
       case  8:
//               MuestraDatosGEmp( ADELANTE );
	       break;
       // AvanceR�pido
       case  9:
#ifndef DEMOSTRACION
	       CurrRow = 0;		CurrGEmp += NLINEAS_GEMP;

               while ( (CurrGEmp + CurrRow) >= B_IVentas3.Registros() ) CurrGEmp--;

               // Mostramos datos hasta que se nos acabe la pantalla
               MuestraDatosGEmp( CurrGEmp );
               // Leemos el registro sobre el que estamos posicionados
               if ( B_IVentas3.LeeReg( (void *)&S_IVentas3, CurrRow + CurrGEmp ) == ERROR )
                                                             Error(0x01, B_IVentas3.cError );
//                         GraficasEmpleadosMes();
#endif
	       break;
       default:
	       break;
      }

 } while( !ok );


 B_IVentas3.CerrarReg();

}



 /**************************************************************************\
|*                                                                          *|
|*  GraficasEmpleadosMes                                                       *|
|*                                                                          *|
|*  Descripci�n:                                                            *|
|*              Muestra el porcentaje de compras por mesese                 *|
|*                                                                          *|
|*  Entradas: (ninguna)                                                     *|
|*  Salidas:  (ninguna)                                                     *|
|*                                                                          *|
 \**************************************************************************/
void GraficasEmpleadosMes( void )
{
 char Mensajes[][12] =  {  "1", "2", "3", "4", "5", "6", "7", "8", "9","10",
                         "11","12","13","14","15","16","17","18","19","20",
                         "21","22","23","24","25","26","27","28","29","30",
                         "31"
                       };
 char buffer[80], buffer1[80];
 int x, y;

 // Mostramos la grafica
 MuestraGraficas( 10,  15, 380, 95, DiasMes, (long *)GastosComprasD, Mensajes );

 setfillstyle( SOLID_FILL, Config.TxtBgN );
 bar(   5, 160,  80, 295 ); bar(  86, 160, 210, 295 );

 bar( 215, 160, 290, 295 ); bar( 296, 160, 420, 295 );

 bar( 425, 160, 500, 295 ); bar( 506, 160, 635, 295 );

 settextstyle( SMALL_FONT, HORIZ_DIR, 4 );

 // Mostramos los datos num�ricos
 for ( x = 0; x < 3; x++ )
  for ( y = 0; y < 11; y ++ )
  {
   if ( (x*11+y+1) <= DiasMes )
   {
    formatea_long( GastosComprasD[x*11+y+1], buffer1 );
    sprintf( buffer, "%02d-%02d-%04d   %20s", (x*11+y+1), MesActual, FechaGestionActual.da_year, buffer1 );
    outtextxy( 11 + x*210, 165 + y*11, buffer );
   }
  }

    formatea_long( GastosCompras, buffer1 );
    sprintf( buffer, "TOTAL:       %20s", buffer1 );
    outtextxy( 11 + 2*210, 165 + 10*11, buffer );


}

 /**************************************************************************\
|*                                                                          *|
|*  MuestraDatosGEmp                                                         *|
|*                                                                          *|
|*  Descripci�n:                                                            *|
|*              Dado un registro, se muestran sucesivamente este y todos    *|
|*              los que hay por debajo de �l, hasta que se agote la base    *|
|*              o no quepan mas en la pantalla.                             *|
|*                                                                          *|
|*  Entradas: Registro por el que comenzar                                  *|
|*  Salidas:  (ninguna)                                                     *|
|*                                                                          *|
 \**************************************************************************/
void MuestraDatosGEmp( long RowStart )
{
 int linea, campo;
 char dev;
 int X0, Y0, X1, Y1;

 settextstyle( SMALL_FONT, HORIZ_DIR, 5 );

 // Imprimo la NLINEAS_PROVcmp que caben en la pantalla
 dev = OK;
 for ( linea=0; linea < NLINEAS_GEMP && dev == OK; linea++ )
 {
   dev = B_IVentas3.LeeReg( (void *)&S_IVentas3, RowStart + linea );
   if ( dev == OK )
   {
      // Por cada linea hay 4 campos, ehhh!!!
      for  ( campo=0; campo < 4; campo++ )
                                  MuestraGEmp( campo, linea, NORMAL );
   }
 }

  // Ahora limpio los restantes huecos si los hay
  if ( dev != OK ) linea--;

  if ( linea < NLINEAS_GEMP )
  {
   setfillstyle( SOLID_FILL, Config.TxtBgN );
   for ( ; linea < NLINEAS_GEMP; linea++ )
     for  ( campo=0; campo < 4; campo++ )
     {
        ObtenCoordenadasGEmp( campo, linea, &X0, &Y0, &X1, &Y1 );
        bar( X0, Y0, X1, Y1 );
     }
  }
}



 /**************************************************************************\
|*                                                                          *|
|*  ObtenCoordenadasGEmp                                                     *|
|*                                                                          *|
|*  Descripci�n:                                                            *|
|*              Obtiene las coordenadas de acotacion para el campo pedido   *|
|*                                                                          *|
|*  Entradas:                                                               *|
|*            columna    campo del que obtener las coordenadas              *|
|*            linea      linea en la que nos encontramos                    *|
|*            X0 Y0 X1 Y1  Punteros para devolver las coordenadas           *|
|*                                                                          *|
|*  Salidas:  (ninguna)                                                     *|
|*                                                                          *|
 \**************************************************************************/
void ObtenCoordenadasGEmp( char columna, char linea, int *X0, int *Y0, int *X1, int *Y1 )
{

 // Calculamos la Y0, Y1 para la linea dada ( SOLO columna < 6 )
 *Y0 = ( 337 + 15*linea );
 *Y1 = *Y0 + 17;

 switch( columna )
 {
  case 0:
       *X0 =   7;       *X1 =  78;
       break;
  case 1:
       *X0 =  87;       *X1 = 413;
       break;
  case 2:
       *X0 = 422;       *X1 = 503;
       break;
  case 3:
       *X0 = 512;       *X1 = 633;
       break;
 }

 *X0 += 2;
 *X1 -= 2;

}



 /**************************************************************************\
|*                                                                          *|
|*  MuestraAyudaGEmp                                                          *|
|*                                                                          *|
|*  Descripci�n:                                                            *|
|*              Muestra una peque�a descripcion del contenido para el campo *|
|*                                                                          *|
|*  Entradas:                                                               *|
|*            columna    campo ha mostar su ayuda                           *|
|*                                                                          *|
|*  Salidas:  (ninguna)                                                     *|
|*                                                                          *|
 \**************************************************************************/
void MuestraAyudaGEmp ( char columna )
{
 char buffer1[80];

 switch( columna )
 {
  // Codigo del empleado
  case  0:
       sprintf ( buffer1, "Codigo del Empleado" );
       break;
  // Nombre Completo
  case  1:
       sprintf ( buffer1, "Nombre y apellidos del vendedor" );
       break;
  // % de venta en el mes
  case  2:
       sprintf ( buffer1, "Procentaje que supone la venta frente al a�o" );
       break;
  // Venta Total en el a�o
  case  3:
       sprintf ( buffer1, "Venta total en el a�o" );
       break;
 }

 // Ayuda reducida
 setfillstyle( SOLID_FILL, EGA_BLACK );  bar( 7, 457, 498, 473 );
 // Imprime la ayudita
 setcolor( EGA_WHITE ); outtextxy( 7, 457, buffer1 );

}


 /**************************************************************************\
|*                                                                          *|
|*  MuestraGEmp                                                              *|
|*                                                                          *|
|*  Descripci�n:                                                            *|
|*              Reescribe el campo dado, seg�n la fila, y la intensidad     *|
|*                                                                          *|
|*  Entradas:                                                               *|
|*            columna    campo ha mostar                                    *|
|*            linea      linea en la que nos encontramos                    *|
|*            como       intensidad del texto (NORMAL/INTENSO)              *|
|*                                                                          *|
|*  Salidas:  (ninguna)                                                     *|
|*                                                                          *|
 \**************************************************************************/
void MuestraGEmp( char columna, long linea, char como )
{
 char buffer[80];
 char buffer1[80], i, j;
 long TotalVentas;

 int X0, Y0, X1, Y1;

 ObtenCoordenadasGEmp( columna, linea, &X0, &Y0, &X1, &Y1 );

 switch( columna )
 {
  // Parte 1 ( visualizaci�n de proveedores y compras a ellos )

  // Codigo Real del Vendedor
  case  0:
       sprintf ( buffer, "%08lu", S_IVentas3.CodigoR  );
       break;
  // Nombre completo del proveedor
  case  1:
       sprintf ( buffer, "%30s",  S_IVentas3.Vendedor );
       break;
  // % que supone esa compra, en todo el a�o
  case  2:
       TotalVentas = 0;
       for ( i = 0; i < 12; i++ )
        for ( j = 0; j < 31; j++ )
            TotalVentas += S_IVentas3.TotalVendido[j][i];
       sprintf ( buffer, "    %03d", TotalVentas != 0 ? ( GastosCompras*100 ) / TotalVentas : 0 );
       break;
   // Compras en ese mes
  case  3:
       formatea_long( GastosCompras, buffer1 );
       sprintf ( buffer, "%11s", buffer1 );
       break;

 }

 setfillstyle( SOLID_FILL, ( como == NORMAL ) ? Config.TxtBgN : Config.TxtBgI );
 bar( X0, Y0, X1, Y1 );
 setcolor ( ( como == NORMAL ) ? Config.TxtFgN : Config.TxtFgI );

 outtextxy( X0+2, Y0, buffer );

}