#include "modifierrecette.h"
#include "../../recettestriees/etatdesdus/etatdesdus.h"
#include "../../common/configure/pratid.h"
#include <common/constants.h>
#include <common/settings.h>
#include <common/icore.h>
#include <common/commandlineparser.h>
#include <common/print/qprintereasy.h>
#include <QtGui>
#include <QtCore>



using namespace Common;
using namespace Constants;
static inline Common::CommandLine *dataIn(){ return Common::ICore::instance()->commandLine();}

modifierrecette * modifierrecette::m_singleton = NULL;

modifierrecette::~modifierrecette() {}

modifierrecette::modifierrecette()

{
  //m_db1 = QSqlDatabase::database(Constants::DB_DRTUX);
  m_accountancyDb = QSqlDatabase::database(Constants::DB_ACCOUNTANCY);

  m_typeOfMoney = Common::ICore::instance()->settings()->value(Constants::S_TYPE_OF_MONEY).toString();
  setupUi(this);
  dateEdit->setDate(QDate::currentDate());
  dateEdit_2->setDate(QDate::currentDate());
  setAttribute(Qt::WA_DeleteOnClose);
  lineEdit   -> setWhatsThis(trUtf8("Vous pouvez écrire ici le nom d'un patient.\nModulo (%) est le caractère jocker."));
  comboBox   -> setWhatsThis(trUtf8("Vous pouvez choisir le type de filtrage"));
  pushButton -> setWhatsThis(trUtf8("Lance le logiciel de gestion des dus."));
  pushButton_5 -> setToolTip(trUtf8("Pour l'aide cliquez sur ce bouton,\ndéplacez la souris sur la zone voulue,\ncliquez "
                                    "pour afficher l'aide."));
  label_5->setWordWrap(true);
  label_5->setText("");
  m_modelHonoraires = new QSqlTableModel(this,m_accountancyDb);
  m_modelSeances = new QSqlTableModel(this,m_accountancyDb);
//model->setQuery("SELECT * FROM honoraires",db2)
  m_modelHonoraires->setTable("honoraires");
  m_modelHonoraires->setFilter(QString("id_usr = '%1%'").arg(m_user));
  m_modelSeances->setTable("seances");
  m_modelSeances->setFilter(QString("id_usr = '%1%'").arg(m_user));
  radioButton->setChecked(true);
  if(radioButton->isChecked()){
    emit honorairesIsChecked();
    }
  if(radioButton_2->isChecked()){
    seancesIsChecked();
   }
  //qDebug() << __FILE__ << " " << QString::number(__LINE__) << " doc = " <<  m_documentTotal ;
  //construction comboBox "selon"
  comboBox->setEditable(false);
  comboBox->setInsertPolicy(QComboBox::NoInsert);
  comboBox->addItems(m_listechamps);

  connect(pushButton,   SIGNAL(pressed()),this,SLOT(lancerGestionDus()));
  connect(pushButton_2, SIGNAL(pressed()),this,SLOT(effacer()));
  connect(pushButton_3, SIGNAL(pressed()),this,SLOT(close()));
  connect(pushButton_4, SIGNAL(pressed()),this,SLOT(rechercher()));
  connect(pushButton_5, SIGNAL(pressed()),this,SLOT(setWhatsThisMode()));
  connect(pushButton_6, SIGNAL(pressed()),this,SLOT(imprimer()));
  connect(radioButton,  SIGNAL(clicked()),this,SLOT(honorairesIsChecked()));
  connect(radioButton_2,SIGNAL(clicked()),this,SLOT(seancesIsChecked()));
}

void modifierrecette::setDatas(const QString & guid, const QString & user,const QString & site){
    m_user = user;
    m_site = site;
    m_guid = guid;
    qDebug() << __FILE__ << " " << QString::number(__LINE__)
             << " m_user = "+m_user
             << " m_site = "+m_site
             << " m_guid = "+m_guid;
    }

void modifierrecette::lancerGestionDus(){
  QString nom    = dataIn()->value(Common::CommandLine::CL_PatientName).toString();
  QString prenom = dataIn()->value(Common::CommandLine::CL_PatientFirstName).toString();
  etatdesdus *dus = new etatdesdus(nom,prenom,m_guid,m_user);
              dus-> show();
}

void modifierrecette::effacer()
{
  QString textOnLabelFive ;
  QModelIndex index = tableView->QAbstractItemView::currentIndex();
  if(!index.isValid()){
      QMessageBox::warning(0,tr("Erreur"),tr("Veuillez sélectionner une ligne à effacer."),QMessageBox::Ok);
      return;
      }
  int i = index.row();
  if(tableView->model() == m_modelHonoraires){
      if(m_modelHonoraires->removeRows(i,1,QModelIndex())){
          textOnLabelFive = textOfSums(m_modelHonoraires);
          label_5->setText(textOnLabelFive);
          QMessageBox::information(0,tr("Information"),trUtf8("La ligne a été effacée."),QMessageBox::Ok);
      }
  }
  else if(tableView->model() == m_modelSeances){
      if(m_modelSeances->removeRows(i,1,QModelIndex())){
          textOnLabelFive = textOfSums(m_modelSeances);
          label_5->setText(textOnLabelFive);
          QMessageBox::information(0,tr("Information"),trUtf8("La ligne a été effacée."),QMessageBox::Ok);
      }
  }
  else if(tableView->model() == m_modelfiltre){
      if(m_modelfiltre->removeRows(i,1,QModelIndex())){
          textOnLabelFive = textOfSums(m_modelfiltre);
          label_5->setText(textOnLabelFive);
          QMessageBox::information(0,tr("Information"),trUtf8("La ligne a été effacée."),QMessageBox::Ok);
      }
  }
  else {QMessageBox::warning(0,tr("Erreur"),trUtf8("Strange thing"),QMessageBox::Ok);}
}
///////////////////////////////////////////////////////////////////////////////
//---------------TRI ET RECHERCHE----------------------------------------------
//////////////////////////////////////////////////////////////////////////////
void modifierrecette::rechercher()
{
  m_documentTotal = "";
  QString filtre;
  QString filtremodulo;
  filtre = lineEdit->text();
  QString champ = comboBox->currentText();
  if(filtre == ""){
      filtremodulo = "%";
      }
  else filtremodulo = filtre+"%";

  QDate datedebut = dateEdit->date();
  QString datedebutstring = datedebut.toString("yyyy-MM-dd");
  QDate datefin = dateEdit_2->date();
  QString datefinstring = datefin.toString("yyyy-MM-dd");
  //la base filtrée
  QString tableName = "";
  if(radioButton->isChecked()){
      tableName = "honoraires";
      }
  else if (radioButton_2->isChecked()){
      tableName = "seances";
      champ = "acte";
      }
  else {QMessageBox::warning(0,tr("Erreur"),trUtf8("Strange thing ")+QString(__FILE__)+" "+trUtf8("line = ")+QString::number(__LINE__),QMessageBox::Ok);}

  //le code du filtre
  QString filtremodel ;
  filtremodel = QString("%1 LIKE '%2' AND %1 NOT LIKE '%3%' AND DATE BETWEEN '%4' AND '%5'").
                arg(champ,
                    filtremodulo,
                    QString::number(0),
                    datedebutstring,
                    datefinstring);
  if(comboBox->currentText() == "praticien"){
      QString id_usr;
      pratid *prat = new pratid();
      if(prat->exec() == QDialog::Accepted){
          id_usr = prat->recupPrat();
          m_user = prat->lineEdit->text().split(",")[1];
          qDebug() << __FILE__ << QString::number(__LINE__) << " id_usr et m_user = " << id_usr << " " << m_user;
      }
      champ = "id_usr";

     /* QSqlQuery qPrat(m_accountancyDb);
                qPrat.exec("SELECT id_usr FROM utilisateurs WHERE login = '"+m_user+"'");
      while(qPrat.next()){
          id_usr = qPrat.value(0).toString();
      }*/
     filtremodel = QString("%1 LIKE '%2' AND DATE BETWEEN '%3' AND '%4'").
                arg(champ,
                    id_usr,
                    datedebutstring,
                    datefinstring);
  }
  if(comboBox->currentText() == "site"){
      champ = "id_site";
      QString idSite;
      QSqlQuery qSite(m_accountancyDb);
                qSite.exec("SELECT id_site FROM sites WHERE site = '"+m_site+"'");
      while(qSite.next()){
          idSite = qSite.value(0).toString();
      }
      filtremodel = QString("%1 LIKE '%2' AND DATE BETWEEN '%3' AND '%4'").
                    arg(champ,
                    idSite,
                    datedebutstring,
                    datefinstring);
  }
  m_modelfiltre = new QSqlTableModel(this,m_accountancyDb);
  m_modelfiltre->setTable(tableName);
  m_modelfiltre->setFilter(filtremodel);
  m_modelfiltre->select();
  qDebug() << __FILE__ << "tableName ="+m_modelfiltre->tableName();
  tableView->setModel(m_modelfiltre);
  tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
  tableView->setSelectionMode(QAbstractItemView::SingleSelection);
  QStringList m_listechamps;
  int numberOfRows = 0;
  if(tableName == "honoraires"){
      m_mapColumns.clear();
      m_documentTotal = "";
      tableView->setSortingEnabled(true);
      tableView->setColumnHidden(0,true);
      tableView->setColumnHidden(1,true);
      tableView->setColumnHidden(2,true);
      tableView->setColumnHidden(4,true);
      tableView->setColumnHidden(5,true);
      tableView->setColumnHidden(10,true);
      tableView->setColumnHidden(16,true);
      tableView->setColumnHidden(19,true);
      tableView->setColumnHidden(20,true);
      tableView->horizontalHeader()->setResizeMode(QHeaderView::Interactive);
      tableView->horizontalHeader()->setStretchLastSection ( true );
      QString textOfLabel = textOfSums(m_modelfiltre);
      label_5->setText(textOfLabel);
      //recuperer les donnees pour l'impression
      m_mapColumns.insert(3,"Nom,Prenom");
      m_mapColumns.insert(8,"Date");
      m_mapColumns.insert(12,"esp");
      m_mapColumns.insert(13,"chq");
      m_mapColumns.insert(14,"CB");
      m_mapColumns.insert(15,"DAF");
      m_mapColumns.insert(17,"Du");
      numberOfRows = m_modelfiltre->rowCount();
      for(int r = 0 ; r < numberOfRows ; r++){
          QString documentStr ;
          QMapIterator<int,QString> iMap(m_mapColumns);
          while(iMap.hasNext()){
              iMap.next();
              QModelIndex index = m_modelfiltre->index(r,iMap.key(),QModelIndex());
             QString dataMap = m_modelfiltre->data(index).toString();


                  documentStr += iMap.value()+" = "+dataMap+"   ";

          }
          qDebug() << __FILE__ << QString::number(__LINE__) << " data = " << documentStr;
          m_documentTotal += documentStr+"<br/>";
      }
      //qDebug() << "in docHono =" << m_documentTotal << __LINE__;
  }
  if(tableName == "seances"){
      m_mapColumns.clear();
      m_documentTotal = "";
      tableView->setSortingEnabled(true);
      tableView->setColumnHidden(0,true);
      tableView->setColumnHidden(1,true);
      tableView->setColumnHidden(3,true);
      tableView->setColumnHidden(11,true);
      //recuperer donnees pour impression
       m_mapColumns.insert(2,"date");
       m_mapColumns.insert(4,"acte");
       m_mapColumns.insert(5,"esp");
       m_mapColumns.insert(6,"chq");
       m_mapColumns.insert(7,"cb");
       m_mapColumns.insert(8,"daf");
       m_mapColumns.insert(10,"du");
       numberOfRows = m_modelfiltre->rowCount();
       for(int r = 0 ; r < numberOfRows ; r++){
          QString documentStr ;
          QMapIterator<int,QString> iMap(m_mapColumns);
          while(iMap.hasNext()){
              iMap.next();
              QModelIndex index = m_modelfiltre->index(r,iMap.key(),QModelIndex());
              documentStr += iMap.value()+" = "+m_modelfiltre->data(index).toString()+"   ";
          }
          m_documentTotal += documentStr+"<br/>";

        }
  }
  tableView->horizontalHeader()->setResizeMode(QHeaderView::Interactive);
  tableView->verticalHeader()->setResizeMode(QHeaderView::Stretch);
  tableView->resizeColumnsToContents();

  //qDebug() << "doc " << __LINE__ << m_documentTotal;

}

/*QString modifierrecette::adapteCheminWindows(QString & chemin){
    QString str           = chemin;
    QString nouveauChemin = "";
    QStringList listStr   = str.split("/");
    for(int i = 0;i < listStr.size();i++){
        QString partie    = listStr[i];
        if(listStr[i].contains(" ")){
             partie = "\""+listStr[i]+"\"";
            }
        QString apres = "\\";
        if(i == listStr.size()-1){
            apres     = ".exe";
            }
            nouveauChemin += partie+apres;
        }

    return nouveauChemin;
}*/

void modifierrecette::errorMessage(QString & error){
    QMessageBox::warning(0,trUtf8("Erreur"),trUtf8("Erreur lancement processus :")+error,QMessageBox::Ok);
    }

void modifierrecette::setWhatsThisMode(){
  QWhatsThis::enterWhatsThisMode();
}

void modifierrecette::imprimer(){
  QString   pHeadText = "tete";
  QString   pFootText = "foot";
  //-------tete------------------
  QStringList headList;
  QFile fileHead(Common::ICore::instance()->settings()->applicationResourcesPath()+"/txt/"+m_user+"_headUtf8.txt");
  qDebug() << __FILE__ << " " << QString::number(__LINE__) << " "
           << Common::ICore::instance()->settings()->applicationResourcesPath()+"/txt/"+m_user+"_headUtf8.txt";
  if(!fileHead.open(QIODevice::ReadOnly)){
     QMessageBox::warning(0,tr("Erreur"),trUtf8("headUtf8.txt ne peut pas être ouvert"),QMessageBox::Ok);
        }
    QTextStream streamHead(&fileHead);
    while(!streamHead.atEnd()){
       QString ligneH = streamHead.readLine();
       headList        << ligneH+"<br/>";
    }
  pHeadText = headList.join("<br/>");

  //-------pied---------------
  QStringList listePied;
  QFile fileFoot(Common::ICore::instance()->settings()->applicationResourcesPath()+"/txt/"+m_user+"_footUtf8.txt");
    if(!fileFoot.open(QIODevice::ReadOnly)){
        QMessageBox::warning(0,tr("Erreur"),trUtf8("footUtf8.txt ne peut pas être ouvert"),QMessageBox::Ok);
        }
    QTextStream streamFoot(&fileFoot);
    while(!streamFoot.atEnd()){
       QString lignepied = streamFoot.readLine();
       listePied        << lignepied+"<br/>";
    }
  pFootText                = listePied.join("<br/>");
  QPrinterEasy pe;
  pe.askForPrinter();
  pe.setHeader(pHeadText);
  pe.setContent(m_documentTotal);
  pe.setFooter(pFootText);
  pe.previewDialog();
    /*QPrinter printer;
    QPrintDialog *printdialog = new QPrintDialog(&printer,this);
    printdialog               ->setWindowTitle(tr("Imprimer"));
    printdialog               ->exec();
    qDebug() << "print"<< __LINE__;
    m_affichage               ->print(&printer);
    qDebug() << "print"<< __LINE__;*/
}

void modifierrecette::honorairesIsChecked(){
      int numberOfRows = 0;
      m_mapColumns.clear();
      m_documentTotal = "";
      m_modelHonoraires->select();
      tableView->setModel(m_modelHonoraires);
      tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
      tableView->setSelectionMode(QAbstractItemView::SingleSelection);
      tableView->setSortingEnabled(true);
      tableView->setColumnHidden(0,true);
      tableView->setColumnHidden(1,true);
      tableView->setColumnHidden(2,true);
      tableView->setColumnHidden(4,true);
      tableView->setColumnHidden(5,true);
      tableView->setColumnHidden(10,true);
      tableView->setColumnHidden(16,true);
      tableView->setColumnHidden(19,true);
      tableView->setColumnHidden(20,true);
      tableView->horizontalHeader()->setResizeMode(QHeaderView::Interactive);
      tableView->verticalHeader()  ->setResizeMode(QHeaderView::Stretch);
      tableView->resizeColumnsToContents();
      QString textOfLabel = textOfSums(m_modelHonoraires);
      //qDebug() << __FILE__ << QString::number(__LINE__) << " textOfLabel = " <<textOfLabel;
      label_5->setText(textOfLabel);
      m_listechamps.clear();
      //pour comboBox
      m_listechamps << "patient" << "praticien" << "site" << "remarque" << "esp" << "chq"
                    << "cb" << "daf" << "autre" << "du" << "valide" ;
      //recuperer les donnees pour l'impression
      m_mapColumns.insert(3,"Nom,Prenom");
      m_mapColumns.insert(8,"Date");
      m_mapColumns.insert(12,"esp");
      m_mapColumns.insert(13,"chq");
      m_mapColumns.insert(14,"CB");
      m_mapColumns.insert(15,"DAF");
      m_mapColumns.insert(17,"Du");
      numberOfRows = m_modelHonoraires->rowCount();
      for(int r = 0 ; r < numberOfRows ; r++){
          QString documentStr ;
          QMapIterator<int,QString> iMap(m_mapColumns);
          while(iMap.hasNext()){
              iMap.next();
              QModelIndex index = m_modelHonoraires->index(r,iMap.key(),QModelIndex());
              documentStr += iMap.value()+" = "+m_modelHonoraires->data(index).toString()+"   ";
          }
          m_documentTotal += documentStr+"<br/>";
      }
}

void modifierrecette::seancesIsChecked(){
       int numberOfRows = 0;
       m_mapColumns.clear();
       m_documentTotal = "";
       m_modelSeances->select();
       tableView->setModel(m_modelSeances);
       tableView->horizontalHeader()->setResizeMode(QHeaderView::Interactive);
       tableView->verticalHeader()  ->setResizeMode(QHeaderView::Stretch);
       tableView->setSortingEnabled(true);
       tableView->resizeColumnsToContents();
       QString textOfLabel = textOfSums(m_modelHonoraires);
       label_5->setText(textOfLabel);
       m_listechamps.clear();
       m_listechamps << "acte" << "praticien"  << "site" <<  "esp" << "chq" << "cb" << "daf" << "autre" << "du" << "valide" ;
       m_mapColumns.insert(2,"date");
       m_mapColumns.insert(4,"acte");
       m_mapColumns.insert(5,"esp");
       m_mapColumns.insert(6,"chq");
       m_mapColumns.insert(7,"cb");
       m_mapColumns.insert(8,"daf");
       m_mapColumns.insert(10,"du");
       numberOfRows = m_modelSeances->rowCount();
       for(int r = 0 ; r < numberOfRows ; r++){
          QString documentStr ;
          QMapIterator<int,QString> iMap(m_mapColumns);
          while(iMap.hasNext()){
              iMap.next();
              QModelIndex index = m_modelSeances->index(r,iMap.key(),QModelIndex());
              documentStr += iMap.value()+" = "+m_modelSeances->data(index).toString()+"   ";
          }
          m_documentTotal += documentStr+"<br/>";

        }
}

bool modifierrecette::isItShown(){
   show();
   return true;
}

QString modifierrecette::textOfSums(QSqlTableModel * model){
    QString labelText;
    QString labelTextStr;
    double esp = 0.00;
    double chq = 0.00;
    double visa = 0.00;
    double dus = 0.00;
    double daf = 0.00;
    double totalRecu = 0.00;
    double totaux = 0.00;
   int modelRowCount = model->rowCount(QModelIndex());
   for(int i = 0; i < modelRowCount ; i ++){
       QSqlRecord rowRecord = model->record(i);//ligne d'enregistrement
       esp  += rowRecord.value(12).toDouble();
       chq  += rowRecord.value(13).toDouble();
       visa += rowRecord.value(14).toDouble();
       daf  += rowRecord.value(15).toDouble();
       dus  += rowRecord.value(17).toDouble();
       }
    totaux = esp + chq + visa + dus + daf;
    totalRecu = esp + chq + visa;
    QString totauxStr = "<font size = 3 color = ""blue"">Totaux = </font><font size = 3 color = ""red"">"+QString::number(totaux)+" "+m_typeOfMoney+" </font><br/>";
    QString totRecus = "<font size = 3 color = ""blue"">Totaux reçus = </font><font size = 3 color = ""red"">"+QString::number(totalRecu)+" "+m_typeOfMoney+" </font><br/>";
    QString sumsStr = "<font size = 3 color = ""blue"">Esp = </font><font size = 3 color = ""red"">"+QString::number(esp)+" "+m_typeOfMoney+"  </font>"+
                "<font size = 3 color = ""blue"">Chq = </font><font size = 3 color = ""red"">"+QString::number(chq)+" "+m_typeOfMoney+"  </font>"+
                "<font size = 3 color = ""blue"">CB = </font><font size = 3 color = ""red"">"+QString::number(visa)+" "+m_typeOfMoney+"  </font>"+
                "<font size = 3 color = ""blue"">Tiers-payants = </font><font size = 3 color = ""red"">"+QString::number(daf)+" "+m_typeOfMoney+"  </font>"+
                "<font size = 3 color = ""blue"">Dus = </font><font size = 3 color = ""red"">"+QString::number(dus)+" "+m_typeOfMoney+"</font>";
    labelTextStr = trUtf8(totauxStr+
                totRecus+sumsStr
                );
    labelText = "<html><body>"+labelTextStr+"</body></html>";
    return labelText;
    }
