#include <applicat.h>
#include <execp.h>
#include <config.h>
#include <mask.h>
#include <relation.h>
#include <utility.h>
#include "..\cg\cgsaldac.h"
#include "cgp2100a.h"
#include "mov.h"
#include "rmov.h"
#include "doc.h"
#include "rdoc.h"
#include "partite.h"
#include "pagsca.h"
#include "clifo.h"

class TGenera_ord_bon : public TSkeleton_application
{
  TArray _files;
  TMask *_m;
  void add_totaledoc(TConfig *ordbon,int nrigadoc,const char * tiporiga, const char * codspesa, real & importo);
protected:
  bool create();
  bool destroy();
  void main_loop();
  void genera_ordini(TCursor & cur);
public:
  ~TGenera_ord_bon () 
    {;}
};

bool TGenera_ord_bon::create()
{
  _files.add(new TLocalisamfile(LF_PARTITE));
  _files.add(new TLocalisamfile(LF_SCADENZE));
  _files.add(new TLocalisamfile(LF_PAGSCA));

  _m = new TMask ("cgp2100a.msk");
  return TSkeleton_application::create();
}

bool TGenera_ord_bon::destroy()
{
  delete _m;        
  return TSkeleton_application::destroy();
}

void TGenera_ord_bon::main_loop()
{
  TConfig params("crpa.ini","Main"); // configurazione bonifici
  _m->set(F_CAUS,params.get("caus"));  
  _m->set(F_ABIPRES,params.get("abi_pres"));  
  _m->set(F_CABPRES,params.get("cab_pres"));  
  if (_m->run() != K_QUIT)
  {
    // build cursor
    TRectype from(LF_RMOV),to(LF_RMOV);
    TRelation *rel= new TRelation(LF_RMOV);
    rel->add(LF_MOV,"NUMREG==NUMREG");
    rel->add(LF_CLIFO,"TIPOCF==TIPOC|CODCF==SOTTOCONTO");

    from.put(RMV_NUMREG,_m->get(F_FROMREG));
    to.put(RMV_NUMREG,_m->get(F_TOREG));
    TString filter,sortexp;
    if (*_m->get(F_FROMDATA))
    {
      filter << '(' << LF_MOV << "->" << MOV_DATACOMP << ">=" << '"' << _m->get(F_FROMDATA) << '"' << ")";
      filter << "&&";
    }
    if (*_m->get(F_TODATA))
    {
      filter << '(' << LF_MOV << "->" << MOV_DATACOMP << "<=" << '"' << _m->get(F_TODATA) << '"' << ")";
      filter << "&&";
    }
    filter << '(' << LF_RMOV << "->" << RMV_SEZIONE << "==\"D\")";
    filter << "&&";
    filter << '(' << LF_RMOV << "->" << RMV_TIPOC << "==\"F\")";
    filter << "&&";
    filter << "(" <<LF_MOV << "->" << MOV_CODCAUS << "==" << '"'<< _m->get(F_CAUS)<< '"' << ')';

    sortexp << LF_RMOV << "->" << RMV_SOTTOCONTO   << "|" << LF_MOV << "->" << MOV_DATACOMP 
      << "|" << LF_MOV << "->" << MOV_NUMREG;
    
    TSorted_cursor movs(rel,sortexp);
    
    movs.setfilter(filter,TRUE);
    movs.setregion(from,to);
    genera_ordini(movs);
  }
}
void TGenera_ord_bon::genera_ordini(TCursor & cur)
{
  {
    TString_array transactions;
    list_files("crpat*.ini", transactions);
    FOR_EACH_ARRAY_ROW(transactions, row, name)
      remove(*name);
  }
  TConfig params("crpa.ini","Main"); // configurazione bonifici
  const TString16 tipodoc(params.get("tipodoc"));  
  const TString16 codnum(params.get("codnum"));  
  const TString16 tiporiga(params.get("tiporiga"));  
  const TString16 codspesa(params.get("codspesa"));  
  const TDate datadoc(_m->get(F_DATADOC));  
  const long firm(get_firm());  

  TString descrmov;

  TConfig *ordbon=NULL;

  TPartite_array partite;
  long abi(0),cab(0); // abi e cab di presentazione
  long curr_numreg(-1);
  int curr_numrig;
  long curr_codfor(-1);
  int ntransac=0; // contatore di transazione
  int nrigadoc=0; // contatore di riga
  real totaledoc(ZERO);
  
  const long items=cur.items();
  for (long c=0 ;c < items;  c++)
  {
    cur = c;
    if (cur.relation()->lfile(LF_RMOV).get_long(RMV_SOTTOCONTO)!=curr_codfor)
    {
      if (curr_codfor >=0)
      {
        if (abi==0)
        {
          abi=_m->get_long(F_ABIPRES);
          cab=_m->get_long(F_CABPRES);
        }
        ordbon->set_paragraph(format("%d",LF_DOC));
        ordbon->set(DOC_CODABIP,abi);
        ordbon->set(DOC_CODCABP,cab);
        add_totaledoc(ordbon,nrigadoc,tiporiga, codspesa, totaledoc);
        delete ordbon;
        if (nrigadoc)
        {
          nrigadoc=0;
          totaledoc=0;
          abi=0;
          cab=0;
        } else
          remove(format("crpat%03d.ini",ntransac));
      }
      curr_codfor=cur.relation()->lfile(LF_RMOV).get_long(RMV_SOTTOCONTO);
      // ciclo sui fornitori
      ntransac++;      
      ordbon = new TConfig(format("crpat%03d.ini",ntransac));
      ordbon->set_paragraph("Transaction");
      ordbon->set("Action","INSERT");
      ordbon->set("Mode","AUTO");
      ordbon->set("Firm",firm);
      ordbon->set_paragraph(format("%d",LF_DOC));
      ordbon->set("ANNO",cur.relation()->lfile(LF_MOV).get(MOV_ANNOES));
      ordbon->set("PROVV","D");
      ordbon->set("CODNUM",codnum);
      ordbon->set("TIPODOC",tipodoc);
      ordbon->set("DATADOC",datadoc);
      ordbon->set("TIPOCF","F");
      ordbon->set("CODCF",cur.relation()->lfile(LF_RMOV).get(RMV_SOTTOCONTO));
      ordbon->set(DOC_CODABIA,cur.relation()->lfile(LF_CLIFO).get(CLI_CODABI));
      ordbon->set(DOC_CODCABA,cur.relation()->lfile(LF_CLIFO).get(CLI_CODCAB));
    }
    if (cur.relation()->lfile(LF_MOV).get_long(MOV_NUMREG) != curr_numreg)
    {
      curr_numreg=cur.relation()->lfile(LF_MOV).get_long(MOV_NUMREG);
      partite.destroy();
      partite.add_numreg(curr_numreg);
      
    }
    curr_numrig=cur.relation()->lfile(LF_RMOV).get_int(RMV_NUMRIG);
    for (TPartita* game = partite.first(); game; game = partite.next())
    {
      const int r = game->mov2rig(curr_numreg,curr_numrig);
      if (r > 0)
      {
        // immette la riga
        TRiga_partite &rpart = game->riga(r);
        nrigadoc++;
        ordbon->set_paragraph(format("%d,%d",LF_RIGHEDOC, nrigadoc));
        ordbon->set(RDOC_TIPORIGA,tiporiga);
        ordbon->set(RDOC_CODART,codspesa);
        ordbon->set(RDOC_PREZZO,rpart.get(PART_IMPORTO));
        totaledoc+=rpart.get_real(PART_IMPORTO);
        // cerca il riferimento alla fattura per la descrizione
        descrmov.cut(0);
        TPartita & part=rpart.partita();
        const int rigafattura = part.prima_fattura();
        TRiga_partite &rpart_fatt = part.riga(rigafattura);
        const TDate datadocrif=rpart_fatt.get_date(PART_DATADOC);
        const int numdocrif=rpart_fatt.get_int(PART_NUMDOC);
        if (numdocrif)
          descrmov << "Documento" << format(" n.%d ",numdocrif) << "del " << datadocrif;
          
        if (descrmov.blank())
          descrmov=rpart.get(PART_DESCR);
        if (descrmov.blank())
          descrmov=cur.relation()->lfile(LF_RMOV).get(RMV_DESCR);
        if (descrmov.blank())
          descrmov=cur.relation()->lfile(LF_MOV).get(MOV_DESCR);
        ordbon->set(RDOC_DESCR,descrmov);
        ordbon->set(RDOC_LIVELLO,rpart.get(PART_NUMPART));
        // aggiunge la banca di presentazione
        if (abi==0)
        {
          const int numrate=rpart_fatt.rate();
          if (numrate)
          {
            abi = rpart_fatt.rata(1).get_long(PAGSCA_CODABIPR);
            cab = rpart_fatt.rata(1).get_long(PAGSCA_CODCABPR);
          }
        }
      }
    }  // cicloo partite
  } 
  // genera l'ultimo documento
  if (items)
  {
    if (abi==0)
    {
      abi=_m->get_long(F_ABIPRES);
      cab=_m->get_long(F_CABPRES);
    }
    ordbon->set_paragraph(format("%d",LF_DOC));
    ordbon->set(DOC_CODABIP,abi);
    ordbon->set(DOC_CODCABP,cab);

    add_totaledoc(ordbon,nrigadoc,tiporiga, codspesa, totaledoc);
    delete ordbon;
  }
  TExternal_app gestdoc("ve0.exe -1 -icrpat*.ini ");
  gestdoc.run();
}

void TGenera_ord_bon::add_totaledoc(TConfig *ordbon,int nrigadoc,const char * tiporiga, const char * codspesa, real & importo)
{
  return;
  nrigadoc++;
  ordbon->set_paragraph(format("%d,%d",LF_RIGHEDOC, nrigadoc));
  ordbon->set(RDOC_TIPORIGA,tiporiga);
  ordbon->set(RDOC_CODART,codspesa);
  ordbon->set(RDOC_PREZZO,importo);
  ordbon->set(RDOC_DESCR,"Totale");
}

int cgp2100 (int argc, char** argv)
{
  TGenera_ord_bon a;
  a.run(argc,argv,"Generazione ordini di bonifico");
  return 0;
}