#ifndef __TCLIFOR_H
#include "tclifor.h"
#endif

#ifndef __CONFIG_H
#include "config.h"
#endif

#ifndef __VEUML1_H
#include "veuml1.h"
#endif

#ifndef __VE0100_H
#include "ve0100.h"
#endif


#ifndef __VE0100O_H
#include "ve0100o.h"
#endif

#ifndef __TABUTIL_H
#include <tabutil.h>
#endif

const TString& TData_picker::get( const TString& table, const TString& codtab, const TString& field )
{
  TTable tab(table);
  tab.zero();
  tab.put( "CODTAB", codtab);
  if (tab.read() != NOERR)
    tab.zero();
  return tab.get( field );
};

const TString& TData_picker::get( const int file, const TString& fieldname )
{
  return lfile( file ).get( fieldname );
}

int TData_picker::get_int( const int file, const TString& fieldname )
{
  return lfile( file ).get_int( fieldname );
}

long TData_picker::get_long( const int file, const TString& fieldname )
{
  return lfile( file ).get_long( fieldname );
}

bool TData_picker::get_bool( const int file, const TString& fieldname )
{
  return lfile( file ).get_bool( fieldname );
} 

int TCliFor::write_occas( )
{          
  int err = NOERR;
  if(occasionale()) 
  {
    TRelation occas( LF_OCCAS );
    occas_mask( ).autosave( occas );
    err = occas.write( ); 
    if (err == _isreinsert)
      err = occas.rewrite();
  }
  return err;
}

TCliFor::TCliFor( ) : TData_picker( LF_CLIFO ), _occas_mask( "ve0100o" ),
                      _tipocf(' '), _codcf(0L)
{
  _occas_mask.set_handler( O_CODICE, occas_code_handler );
  add( LF_CFVEN, "TIPOCF=TIPOCF|CODCF=CODCF" );
}  

bool TCliFor::load( const char tipocf, const long codcf, const TString& ocfpi )
{ 
  _valid = FALSE;
  
  _tipocf = tipocf;
  _codcf = codcf;
  zero( );                                    
  if (tipocf == ' ' || codcf == 0L)
    return TRUE;
  curr( ).put( "TIPOCF", tipocf );
  curr( ).put( "CODCF", codcf );
  lfile( ).setkey( 1 );
  if( read( ) == NOERR )
  {
    _occas = curr().get_bool( "OCCAS" );
    if ( occasionale( ) )
    {
      TRelation occrel( LF_OCCAS );
      occrel.curr().zero();
      occrel.curr().put( "CFPI", ocfpi );
      if (occrel.read() != NOERR)
        occrel.curr().zero();
      occas_mask().autoload( occrel );
    }        
    _valid = TRUE;
  } 
  return _valid;
}

void TCliForVendite::update_mask( TMask& m, bool onload )
{  
  TString16 stato;           
  const TString16 codval(m.get(F_CODVAL));
  const TString16 datacambio(m.get(F_DATACAMBIO1));
  
  // Setta i campi che appartengono al file LF_CLIFO  
  const bool occas = app().config_ditta().get_bool("GESOCCAS") && occasionale();

  m.show(F_OCCASEDIT, occas);
  // In forse per l'Occasionale, sicuri per il Normale
  m.show(F_COFI, !occas);
  m.show(F_STATOPAIVA, !occas);
  m.show(F_PAIVA, !occas);    
  set(m, F_RAGSOC, LF_CLIFO, "RAGSOC" );
  m.enable(F_RAGSOC, !occas);
  if(!onload)    
  {                                      
    if (m.id2pos(F_CODVAL) >= 0 && m.field(F_CODVAL).active())
      set( m, F_CODVAL, LF_CLIFO, "CODVAL" );
    if (m.id2pos(F_CODVAL1) >= 0 && m.field(F_CODVAL1).active())
      set( m, F_CODVAL1, LF_CLIFO, "CODVAL" );
    if (m.id2pos(F_CODLIN) >= 0 && m.field(F_CODLIN).active())
      set( m, F_CODLIN, LF_CLIFO, "CODLIN" );
    set( m, F_CODPAG, LF_CLIFO, "CODPAG" );
    set( m, F_CODABIA, LF_CLIFO, "CODABI" );
    set( m, F_CODCABA, LF_CLIFO, "CODCAB" );
    // Setta i campi che appartengono al file LF_CFVEN
    set( m, F_CODABIP, LF_CFVEN, "CODABIPR" );
    set( m, F_CODCABP, LF_CFVEN, "CODCABPR" );
    set( m, F_RAGGR, LF_CFVEN, "RAGGDOC" );
    set( m, F_CODINDSP, LF_CFVEN, "CODINDSP" );
    set( m, F_CODAG, LF_CFVEN, "CODAG" );
    set( m, F_CODSPMEZZO, LF_CFVEN, "CODSPMEZZO" );
    set( m, F_CODPORTO, LF_CFVEN, "CODPORTO" );
    set( m, F_CODNOTESP1, LF_CFVEN, "CODNOTESP1" );
    set( m, F_CODNOTESP2, LF_CFVEN, "CODNOTESP2" );
    set( m, F_CODVETT1, LF_CFVEN, "CODVETT1" );
    set( m, F_CODVETT2, LF_CFVEN, "CODVETT2" );
    set( m, F_CODVETT3, LF_CFVEN, "CODVETT3" );
    set( m, F_SPESEINC, LF_CFVEN, "PERCSPINC" );  
    set( m, F_ADDBOLLI, LF_CFVEN, "ADDBOLLI" );
    set(m, F_CATVEN, LF_CFVEN, "CATVEN");
    if (m.id2pos(F_CODLIST) >= 0 && m.field(F_CODLIST).active())
      set(m, F_CODLIST, LF_CFVEN, "CODLIST");
    if (m.id2pos(F_CODLIST1) >= 0 && m.field(F_CODLIST1).active())
      set(m, F_CODLIST1, LF_CFVEN, "CODLIST");
    if (m.id2pos(F_CODAG) >= 0 && m.field(F_CODAG).active())
      set(m, F_CODAG, LF_CFVEN, "CODAG");
    set(m, F_CODZON, LF_CFVEN, "CODZONA");
    set(m, F_RAGGR, LF_CFVEN, "RAGGDOC");
  }
  if ( occasionale ( ) ) 
  {    
    m.set( F_COFI, "" );
    m.set( F_PAIVA, "" );
    m.set( F_LOCALITACF, "");
    m.set( F_OCFPI, occas_mask( ).get( O_CODICE ) );   
    m.set( F_RAGSOC, occas_mask( ).get( O_RAGSOC ) );
    m.set( F_INDCF, occas_mask( ).get( O_INDIRIZZO ) );
    m.set( F_CIVCF, occas_mask( ).get( O_NUMERO ) );
    m.set( F_CAPCF, occas_mask( ).get( O_CAP ) );
    m.set( F_COMCF, occas_mask( ).get( O_COMUNE ) );    
    m.set( F_STATOCF, stato = occas_mask( ).get( O_STATO ) );  
  }
  else
  {
    set( m, F_COFI, LF_CLIFO, "COFI" );
    set( m, F_INDCF, LF_CLIFO, "INDCF" );
    set( m, F_CIVCF, LF_CLIFO, "CIVCF" );
    set( m, F_STATOPAIVA, LF_CLIFO, "STATOPAIV" );
    set( m, F_PAIVA, LF_CLIFO, "PAIV" );
    set( m, F_LOCALITACF, LF_CLIFO, "LOCALITACF" );
    set( m, F_CAPCF, LF_CLIFO, "CAPCF" );
    set( m, F_COMCF, LF_CLIFO, "COMCF" );
    stato = get( LF_CLIFO, "STATOCF" );
    m.set( F_STATOCF, stato );
  }
//  m.set( F_DESSTATOCF, get( "%STA", stato, "S0" ) );   
  const TString16 newcodval(m.get(F_CODVAL));
  const TString16 newdatacambio(m.get(F_DATACAMBIO1));

  if ((m.id2pos(F_CAMBIO) >= 0) && (newcodval.empty() || newdatacambio.empty()))
    m.reset(F_CAMBIO);  
  if (m.id2pos(F_CODVAL) >= 0 && m.field(F_CODVAL).active())
    m.check_field(F_CODVAL);
  if (m.id2pos(F_CODVAL1) >= 0 && m.field(F_CODVAL1).active())
    m.check_field(F_CODVAL1);
  if (m.id2pos(F_DATACAMBIO1) >= 0 && m.field(F_DATACAMBIO1).active() &&
     (codval != newcodval || datacambio != newdatacambio))
    m.check_field(F_DATACAMBIO1);
  m.check_field(F_COMCF);
  m.check_field(F_STATOCF);
  m.check_field( F_CODPAG );
  if (m.id2pos(F_CODLIN) >= 0 && m.field(F_CODLIN).active())
    m.check_field( F_CODLIN );
  // m.check_field( F_CODABIA );
  m.check_field( F_CODCABA );
  // m.check_field( F_CODABIP );
  if (m.id2pos(F_CODLIST) >= 0 && m.field(F_CODLIST).active())
    m.check_field( F_CODLIST );
  if (m.id2pos(F_CODLIST1) >= 0 && m.field(F_CODLIST1).active())
    m.check_field( F_CODLIST1);
  m.check_field( F_CODCABP );
  m.check_field( F_CODINDSP );
  if (m.id2pos(F_CODAG) >= 0 && m.field(F_CODAG).active())
    m.check_field( F_CODAG );
  m.check_field( F_CODSPMEZZO );
  m.check_field( F_CODPORTO );
  m.check_field( F_CODNOTESP1 );
  m.check_field( F_CODNOTESP2 );
  m.check_field( F_CODVETT1 );
  m.check_field( F_CODVETT2 );
  m.check_field( F_CODVETT3 );    
  m.check_field( F_CATVEN );    
  m.check_field( F_CODZON );    
//  imposta_dati_comune( m );
  imposta_indirizzo_spedizione( m );
  imposta_sconto_testa( m );
//  imposta_valuta( m  );
}

void TCliFor::edita_occasionale( )
{
  CHECK( occasionale( ), "Impossibile editare come occasionale un cliente non occasionale!" );
  _occas_mask.run( );  
};

bool TCliFor::occas_code_handler(TMask_field& f, KEY key)
{
  if (key == K_TAB)
  {
    const char* code = f.get();
    if (*code)
    {
      TRelation occas(LF_OCCAS);
      occas.lfile().put("CFPI", code);
      if (occas.read(_isequal) == NOERR)
      {
        f.mask().autoload(occas);
        f.mask().send_key(K_TAB, O_COMUNE);         // Forza decodifica comuni
        f.mask().send_key(K_TAB, O_COMUNENAS);
      }  
    }
  } 
  return TRUE;
}

void TCliForVendite::imposta_dati_comune( TMask& m )
{
  TLocalisamfile comuni(LF_COMUNI);
  comuni.setkey( 1 );
  if( occasionale( ) )
  {
    comuni.put( "COM", occas_mask( ).get( O_COMUNE ));
    comuni.put( "STATO", occas_mask( ).get( O_STATO ) );
  }
  else
  {
    comuni.put( "COM", get( LF_CLIFO, "COMCF" ));
    comuni.put( "STATO", get( LF_CLIFO, "STATOCF" ) );
  }
  if (comuni.read() != NOERR)
   comuni.zero();
  m.set( F_DENCOM, comuni.get( "DENCOM" ) );
  m.set( F_PROVCOM, comuni.get( "PROVCOM" ) );
}

void TCliForVendite::imposta_indirizzo_spedizione( TMask& m )
{
  TString16 stato; 
  const bool occas = occasionale();

  m.enable( F_CODINDSP , !occas);      
  if( occas )
  {
    m.set( F_CODINDSP, "" );
    m.set( F_RAGSOCSP, occas_mask( ).get( O_RAGSOC ) );
    m.set( F_INDSP, occas_mask( ).get( O_INDIRIZZO ) );
    m.set( F_CIVSP, occas_mask( ).get( O_NUMERO ) );
    // Sugli occasionali non c'è la località
    m.set( F_LOCALITASP, "" );
    m.set( F_CAPSP, occas_mask( ).get( O_CAP ) );
    m.set( F_COMSP, occas_mask( ).get( O_COMUNE ) );
    m.check_field(F_COMSP);
    m.set( F_STATOSP, stato = occas_mask( ).get( O_STATO ) );
    m.check_field(F_STATOSP);
  }
}

void TCliForVendite::imposta_sconto_testa( TMask& m )
{
  TConfig & ditta = app().config_ditta();
  
  const char tipogestione = ditta.get("GESSCO", "ve")[ 0 ];
  switch( tipogestione )
  {
    case 'N':  // Sconti non gestiti: pussa via!
      break;
    case 'P':  // Percentuale su anagrafica cliente
      m.set( F_SCONTOPERC, get( LF_CFVEN, "SCONTO" ) );
      break;
    case 'T':  // Gestione tabella sconti
      {
        const TString16 codsconto(get(LF_CFVEN, "CODSCC"));
        
        if (codsconto.not_empty())
        {
          TTable sconti("%SCC");
          sconti.setkey(1);
          sconti.zero();
          // sconti.put( "TIPO", "D" );
          sconti.put("CODTAB", codsconto);
          if (sconti.read( ) == NOERR)
            m.set(F_SCONTOPERC, sconti.get("S1"));
        }
      }
      break;
    case 'A':  // Gestione archivio sconti
      {
        TString16 codart;
        TLocalisamfile sconti( LF_SCONTI );
  
        sconti.setkey(1);
        sconti.zero();
        sconti.put("TIPO", "I");
        if(ditta.get_bool("SCOKEY", "ve", 1))
          sconti.put("CODCAT", get( LF_CFVEN, "CATVEN"));
        if(ditta.get_bool("SCOKEY", "ve", 2))
          codart = get( LF_CFVEN, "CODSCC" );
        else
          codart = "  ";
        if( ditta.get_bool("SCOKEY", "ve", 3))
          codart << get(LF_CFVEN, "CODZONA");
        else
          codart << "  ";
        if( ditta.get_bool("SCOKEY", "ve", 4))
          codart << get(LF_CLIFO, "CODPAG");
        sconti.put("CODART", codart);
        if(sconti.read() == NOERR)
          m.set(F_SCONTOPERC, sconti.get( "SCONTO"));
      }
      break;    
    default:
      break;  
  }  
  return;
}

void TCliForVendite::imposta_valuta( TMask& m )
{
   
  TConfig ditta( CONFIG_DITTA );
   
  if( ditta.get_bool( "GESVALAC", "ve" ) )
  {
    TTable cambi( "CAM" );
    cambi.zero( );
    TString16 val( m.get( F_CODVAL ) );
    TString16 codtab( ( const char * ) val );
    codtab << m.get( F_DATADOC );
    cambi.put( "CODTAB", codtab );
    const int result = cambi.read( _isgteq );
    if( result == _iseof )
      cambi.prev( );
    codtab = cambi.get( "CODTAB" );
    if ( codtab.sub( 0, 2 ) == val )
    {      
      m.set( F_CAMBIO, cambi.get( "R10" ) );
      m.set( F_DATACAMBIO1, cambi.get( "D0" ) );
      return;
    }    
  }
  TTable valuta( "%VAL" );
  valuta.zero( );
  valuta.put( "CODTAB", m.get( F_CODVAL ) );
  if( valuta.read( ) == NOERR )
  {
    m.set( F_CAMBIO, valuta.get( "R10" ) );
    m.set( F_DATACAMBIO, valuta.get( "D0" ) );
  }
}
