﻿unit ftratamientos;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, ZAbstractRODataset,
  ZAbstractDataset, ZDataset, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls,
  Vcl.DBCtrls, Vcl.ComCtrls, frxClass, frxDBSet, URLMon, IdBaseComponent,
  IdComponent, IdTCPConnection, IdTCPClient, IdHTTP,shellapi, Vcl.Mask, System.IOUtils; // Asegúrate de tener estas unidades en el interface o implementation

type
  Ttratamientos = class(TForm)
    Panel2: TPanel;
    Panel3: TPanel;
    DBGrid1: TDBGrid;
    Panel5: TPanel;
    Panel4: TPanel;
    DBGrid2: TDBGrid;
    qtratamientosbase: TZQuery;
    qtratamientosbasedetalle: TZQuery;
    qtratamientosbasedetalleide: TIntegerField;
    qtratamientosbasedetalleidt: TIntegerField;
    qtratamientosbasedetalleidaf: TIntegerField;
    qtratamientosbasedetalleidma: TIntegerField;
    qtratamientosbasedetalledescripcion_af: TWideStringField;
    qtratamientosbasedetallecantidad_base: TFloatField;
    qtratamientosbasedetalledosis: TFloatField;
    qtratamientosbasedetalleunidad_medida: TWideStringField;
    qtratamientosbasedetalledescripcion_ma: TWideStringField;
    qtratamientosbasedetalleregistro: TWideStringField;
    qtratamientosbasedetalleplazo: TIntegerField;
    Panel6: TPanel;
    Panel7: TPanel;
    Label36: TLabel;
    btAreutilizar: TButton;
    btAmodificar: TButton;
    btAborrar: TButton;
    btAnuevo: TButton;
    btAguardar: TButton;
    btAcancelar: TButton;
    dsqtratamientosbasedetalle: TDataSource;
    dsqtratamientosbase: TDataSource;
    qtratamientos: TZQuery;
    qtratamientosdetalle: TZQuery;
    dsqtratamientos: TDataSource;
    dsqtratamientosdetalle: TDataSource;
    qcentrocoste: TZReadOnlyQuery;
    qcentrocosteempresa: TIntegerField;
    qcentrocostecodpar: TWideStringField;
    qcentrocostenombre: TWideStringField;
    dsqcentrocoste: TDataSource;
    Panel9: TPanel;
    DBGrid3: TDBGrid;
    Panel10: TPanel;
    Panel11: TPanel;
    Panel12: TPanel;
    DBGrid4: TDBGrid;
    qtratamientosdetalleide: TIntegerField;
    qtratamientosdetalleidt: TIntegerField;
    qtratamientosdetalleidaf: TIntegerField;
    qtratamientosdetalleidma: TIntegerField;
    qtratamientosdetalledescripcion_af: TWideStringField;
    qtratamientosdetalledescripcion_ma: TWideStringField;
    qtratamientosdetallecantidad_base: TFloatField;
    qtratamientosdetalleunidad_medida: TWideStringField;
    qtratamientosdetalleregistro: TWideStringField;
    qtratamientosdetalleplazo: TIntegerField;
    qtratamientosdetalleficha: TBlobField;
    Panel13: TPanel;
    Panel1: TPanel;
    Button2: TButton;
    Button3: TButton;
    qresponsables: TZReadOnlyQuery;
    dsqresponsables: TDataSource;
    qresponsablesnif: TWideStringField;
    qresponsablesnombre: TWideStringField;
    qresponsablesfirma: TBlobField;
    qaux: TZQuery;
    Ffecha: TDateTimePicker;
    combocentrocoste: TDBLookupComboBox;
    comboresponsables: TDBLookupComboBox;
    Panel8: TPanel;
    Button1: TButton;
    Panel15: TPanel;
    Label2: TLabel;
    DBMemo2: TDBMemo;
    Button4: TButton;
    Button5: TButton;
    dbempresa: TfrxDBDataset;
    informes: TfrxReport;
    dbtratamiento: TfrxDBDataset;
    dbtratamientosdetalle: TfrxDBDataset;
    qtratamientosdetalleen_cuaderno: TIntegerField;
    gcrpagado: TDBCheckBox;
    Button7: TButton;
    dsqcentrocoste2: TDataSource;
    qcentrocoste2: TZReadOnlyQuery;
    dsqresponsable2: TDataSource;
    qresponsables2: TZReadOnlyQuery;
    Label4: TLabel;
    Label5: TLabel;
    combobuscarresponsables: TDBLookupComboBox;
    combobuscarparcelas: TDBLookupComboBox;
    btfiltrar: TButton;
    Button9: TButton;
    Button6: TButton;
    Label3: TLabel;
    qcentrocoste2empresa: TIntegerField;
    qcentrocoste2codpar: TWideStringField;
    qcentrocoste2nombre: TWideStringField;
    qresponsables2nif: TWideStringField;
    qresponsables2nombre: TWideStringField;
    qresponsables2firma: TBlobField;
    qtratamientosdetalleconficha: TStringField;
    qtratamientosbasedetalleficha: TBlobField;
    qtratamientosbasedetallecantidad_materia: TFloatField;
    qtratamientosdetallecantidad_mezcla: TFloatField;
    dsqconsumos: TDataSource;
    qconsumos: TZQuery;
    qconsumosid: TIntegerField;
    qconsumoside: TIntegerField;
    qconsumosidcc: TWideStringField;
    qconsumosidgrupo: TIntegerField;
    qconsumosidfamilia: TIntegerField;
    qconsumosidaf: TIntegerField;
    qconsumoscodigo: TWideStringField;
    qconsumosdescripcion: TWideStringField;
    qconsumosregistro: TWideStringField;
    qconsumosprecio: TFloatField;
    qconsumoscantidad: TFloatField;
    qconsumostotal: TFloatField;
    qconsumostotal_amortizado: TFloatField;
    qconsumosnumplazos: TIntegerField;
    qconsumoslote: TWideStringField;
    qconsumosidentrada: TIntegerField;
    qconsumosfecha: TDateField;
    qconsumosidfraccionado: TIntegerField;
    qconsumosamortizacion: TIntegerField;
    qarticulo: TZQuery;
    qarticuloidempresa: TIntegerField;
    qarticuloidaf: TIntegerField;
    qarticulodescripcion: TWideStringField;
    qarticulopreciocoste: TFloatField;
    qarticuloidgrupo: TIntegerField;
    qarticuloidfamilia: TIntegerField;
    qarticulocodigo: TWideStringField;
    qarticuloregistro: TWideStringField;
    qtratamientosdetalleidconsumo: TIntegerField;
    qaux2: TZReadOnlyQuery;
    qstock: TZReadOnlyQuery;
    qstockid: TIntegerField;
    qstockidempresa: TIntegerField;
    qstocklote: TWideStringField;
    qstockfecha: TDateField;
    qtractores: TZReadOnlyQuery;
    qtractorestractor: TWideStringField;
    qvelocidad: TZReadOnlyQuery;
    qventilador: TZReadOnlyQuery;
    qpresiones: TZReadOnlyQuery;
    qdepositos: TZReadOnlyQuery;
    qboquillas: TZReadOnlyQuery;
    qdepositosdeposito: TWideStringField;
    combotractores: TDBLookupComboBox;
    combovelocidad: TDBLookupComboBox;
    combodepositos: TDBLookupComboBox;
    comboboquillas: TDBLookupComboBox;
    comboventilador: TDBLookupComboBox;
    combopresiones: TDBLookupComboBox;
    dsqtractores: TDataSource;
    dsqvelocidad: TDataSource;
    dsqdepositos: TDataSource;
    dsqboquillas: TDataSource;
    dsqventilador: TDataSource;
    dsqpresiones: TDataSource;
    qboquillasboquilla: TWideStringField;
    qtratamientosbasedetallecantidad_mezcla: TIntegerField;
    qtratamientosbasedetalleorden: TIntegerField;
    qtratamientosdetalleorden: TIntegerField;
    combooperarios: TDBLookupComboBox;
    dsqoperarios: TDataSource;
    qoperarios: TZReadOnlyQuery;
    qoperariosoperario: TWideStringField;
    Label301: TLabel;
    combocampanyas: TDBLookupComboBox;
    dsqcampanyas: TDataSource;
    qcampanyas: TZReadOnlyQuery;
    qtratamientosbaseide: TIntegerField;
    qtratamientosbaseid: TIntegerField;
    qtratamientosbasedescripcion: TWideStringField;
    qtratamientosbasetipo: TWideStringField;
    qtratamientosbaseobservaciones: TWideStringField;
    qtratamientosbasefecha: TDateField;
    qcampanyasid: TIntegerField;
    qcampanyasidempresa: TIntegerField;
    qcampanyasid_anterior: TIntegerField;
    qcampanyasdescripcion: TWideStringField;
    qcampanyasfechainicio: TDateField;
    qcampanyasfechafin: TDateField;
    qcampanyasult_pesada: TIntegerField;
    fdesde: TDateTimePicker;
    fhasta: TDateTimePicker;
    Label1: TLabel;
    Label6: TLabel;
    chkimptodo: TCheckBox;
    qmateriaprima: TZReadOnlyQuery;
    qmateriaprimadescripcion: TWideStringField;
    Label7: TLabel;
    combovariedades: TDBLookupComboBox;
    qmateriaprima2: TZReadOnlyQuery;
    dsmateriasprimas: TDataSource;
    qmateriaprima2descripcion: TWideStringField;
    Button8: TButton;
    qinsertarencuaderno: TZQuery;
    qinsertarencuadernodetalle: TZQuery;
    DBGrid5: TDBGrid;
    qresumenproductos: TZReadOnlyQuery;
    dsqresumenproductos: TDataSource;
    qnombrecampanya: TZReadOnlyQuery;
    qnombrecampanyadescripcion: TWideStringField;
    qtratamientosdetalleidentrada: TIntegerField;
    qtratamientosdetallecantidadprevista_mezcla: TFloatField;
    qtratamientosdetallefecha: TDateField;
    qtratamientoside: TIntegerField;
    qtratamientosid: TIntegerField;
    qtratamientosfecha: TDateField;
    qtratamientosidcc: TWideStringField;
    qtratamientosdesc_cc: TWideStringField;
    qtratamientosresponsable: TWideStringField;
    qtratamientosidrecomendacion: TIntegerField;
    qtratamientoscontabilizado: TIntegerField;
    qtratamientosnif_responsable: TWideStringField;
    qtratamientosobservaciones: TWideStringField;
    qtratamientosoperario: TWideStringField;
    qtratamientosidjustificacion: TIntegerField;
    qtratamientoscondiciones_metereologicas: TWideStringField;
    qtratamientoshora_fin: TTimeField;
    qtratamientostractor: TWideStringField;
    qtratamientosdeposito: TWideStringField;
    qtratamientosvelocidad: TFloatField;
    qtratamientosboquilla: TWideStringField;
    qtratamientosventilador: TWideStringField;
    qtratamientosmostrar: TIntegerField;
    qtratamientosvariedad: TWideStringField;
    qtratamientosnum_boquillas: TIntegerField;
    qtratamientoslitros_hect: TIntegerField;
    qtratamientosdesc_boquilla: TWideStringField;
    qtratamientoslitros_minutos: TFloatField;
    qtratamientossuperficie: TFloatField;
    qtratamientosfecha_fin: TDateField;
    qtratamientoshora_inicio: TTimeField;
    qtratamientosfecha_inicio: TDateField;
    qtratamientosancho_calle: TFloatField;

    qventiladorventilador: TWideStringField;
    qtratamientoscompletado: TIntegerField;
    Button10: TButton;
    qcargas: TZReadOnlyQuery;
    dbtratamientoscargas: TfrxDBDataset;
    dsqcargas: TDataSource;
    qcargasid: TIntegerField;
    qcargaside: TIntegerField;
    qcargasidt: TIntegerField;
    qcargasfecha: TDateField;
    qcargashora_inicio: TTimeField;
    qcargashora_fin: TTimeField;
    qcargasid_emp: TIntegerField;
    qcargasoperario: TWideStringField;
    qcargasid_tractor: TWideStringField;
    qcargastractor: TWideStringField;
    qcargasid_fumigadora: TWideStringField;
    qcargasfumigadora: TWideStringField;
    qcargascondiciones_meteorologicas: TWideStringField;
    qcargascantidad: TIntegerField;
    qtratamientospresion: TFloatField;

    qtratamientosdetalledosis: TFloatField;
    qtratamientosdetallecantidad_materia: TFloatField;
    qtratamientosdetallecantidadprevista_materia: TFloatField;
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure dsqtratamientosStateChange(Sender: TObject);
    procedure btAreutilizarClick(Sender: TObject);
    procedure btAnuevoClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure DBGrid3DrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure btAmodificarClick(Sender: TObject);
    procedure btAcancelarClick(Sender: TObject);
    procedure btAguardarClick(Sender: TObject);
    procedure DBGrid3TitleClick(Column: TColumn);
    procedure Button2Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure qtratamientosdetalleAfterPost(DataSet: TDataSet);
    procedure btAborrarClick(Sender: TObject);
    procedure DBGrid4DrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure DBGrid4CellClick(Column: TColumn);
    procedure dsqtratamientosDataChange(Sender: TObject; Field: TField);
    procedure DBGrid3ColExit(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure FfechaChange(Sender: TObject);
    procedure Button7Click(Sender: TObject);
    procedure DBGrid4TitleClick(Column: TColumn);
    procedure Button9Click(Sender: TObject);
    procedure btfiltrarClick(Sender: TObject);
    procedure Button6Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure qtratamientosdetalleCalcFields(DataSet: TDataSet);
    procedure qtratamientosBeforePost(DataSet: TDataSet);
    procedure qtratamientosdetalleBeforePost(DataSet: TDataSet);
    procedure qtratamientosdetalleBeforeDelete(DataSet: TDataSet);
    procedure qtratamientosBeforeDelete(DataSet: TDataSet);
    procedure Button5Click(Sender: TObject);
    procedure qtratamientosAfterPost(DataSet: TDataSet);
    procedure DBGrid4KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure dsqcampanyasDataChange(Sender: TObject; Field: TField);
    procedure DBGrid3CellClick(Column: TColumn);
    procedure Button8Click(Sender: TObject);
    procedure qtratamientosdetalleAfterDelete(DataSet: TDataSet);
    procedure dsqtratamientosdetalleDataChange(Sender: TObject; Field: TField);
    procedure DBGrid5DrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure Button10Click(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
  private
    { Private declarations }
    procedure BtnAyudaClick(Sender: TObject);
  public
    { Public declarations }
  end;

var
  tratamientos: Ttratamientos;
  contabilizando:integer;

implementation

{$R *.dfm}

uses datos, principal, fbuscararticulos, fcargastratamientos, fentradas;

procedure Ttratamientos.btAborrarClick(Sender: TObject);
begin
  qtratamientos.Delete;
end;

procedure Ttratamientos.btAcancelarClick(Sender: TObject);
begin
   qtratamientos.Cancel;
end;

procedure Ttratamientos.btAguardarClick(Sender: TObject);
begin
    qtratamientosidcc.value:=qcentrocostecodpar.AsString;
    qtratamientoside.Value:=qcentrocosteempresa.Asinteger;
    qtratamientosresponsable.Value:=qresponsablesnombre.AsString;
    qtratamientosnif_responsable.Value:=qresponsablesnif.asstring;
    qtratamientosfecha.Value:=ffecha.Date;
    qtratamientos.Post;
    qtratamientos.Refresh;
end;

procedure Ttratamientos.btAmodificarClick(Sender: TObject);
begin
    qtratamientos.Edit;
end;

procedure Ttratamientos.btAnuevoClick(Sender: TObject);
begin
    ffecha.Date:=date;
    qtratamientos.Append;
    qaux.Close;
    qaux.ParamByName('EMPRESA').AsInteger:=dm.tempresaid.asinteger;
    qaux.Prepare;
    qaux.Open;
    qtratamientoside.value:=dm.tempresaid.AsInteger;
    qtratamientosid.Value:=qaux.Fields[0].AsInteger;
    qtratamientosfecha.Value:=ffecha.Date;
    dbgrid3.setfocus;
    dbgrid3.SelectedIndex:=1;

end;

procedure Ttratamientos.btAreutilizarClick(Sender: TObject);
begin
    panel2.Visible:=not panel2.Visible;
    button1.Visible:=not button1.Visible;
end;

procedure Ttratamientos.Button10Click(Sender: TObject);
begin
  cargastratamientos := Tcargastratamientos.Create(nil);
  try
    cargastratamientos.vempresa:=qtratamientoside.AsInteger;
    cargastratamientos.vtratamiento:=qtratamientosid.AsInteger;
    cargastratamientos.ShowModal();
  finally
    cargastratamientos.Free;
    qtratamientosdetalle.Refresh;
    qtratamientos.Refresh;
  end;
end;

procedure Ttratamientos.Button1Click(Sender: TObject);
var idtratamiento,idempresa:integer;
begin
    idtratamiento:=qtratamientosid.asinteger;
    idempresa:=qtratamientoside.AsInteger;
    qtratamientosbasedetalle.First;
    while not qtratamientosbasedetalle.Eof do
    begin
      qtratamientosdetalle.First;
      qtratamientosdetalle.Append;
      qtratamientosdetalleide.value:=idempresa;
      qtratamientosdetalleidaf.value:=qtratamientosbasedetalleidaf.asinteger;
      qtratamientosdetalleidma.value:=qtratamientosbasedetalleidma.asinteger;
      qtratamientosdetalledescripcion_af.value:=qtratamientosbasedetalledescripcion_af.asstring;
      qtratamientosdetalledescripcion_ma.value:=qtratamientosbasedetalledescripcion_ma.asstring;
      qtratamientosdetallecantidad_base.value:=qtratamientosbasedetallecantidad_base.asinteger;
      qtratamientosdetalledosis.value:=qtratamientosbasedetalledosis.asfloat;
      qtratamientosdetalleunidad_medida.value:=qtratamientosbasedetalleunidad_medida.asstring;
      qtratamientosdetalleregistro.value:=qtratamientosbasedetalleregistro.asstring;
      qtratamientosdetalleplazo.value:=qtratamientosbasedetalleplazo.asinteger;
      qtratamientosdetalleorden.value:=qtratamientosbasedetalleorden.asinteger;
      qtratamientosdetalle.Post;
      qtratamientosbasedetalle.Next;
    end;

    qtratamientos.Edit;
    qtratamientosobservaciones.Value:=qtratamientosbaseobservaciones.AsString;
    qtratamientos.Post;
    qtratamientos.Locate('ide,id',vararrayof([idempresa,idtratamiento]),[locaseinsensitive]);
end;

procedure Ttratamientos.Button2Click(Sender: TObject);
begin
    qtratamientosdetalle.Delete;
end;

procedure Ttratamientos.Button3Click(Sender: TObject);
begin
    if qtratamientosdetalleficha.AsString<>'' then
    begin
      qtratamientosdetalleficha.SaveToFile('c:\agrigest\tmp\'+qtratamientosdetalleregistro.AsString+'.pdf');
      ShellExecute(Handle,nil,PChar('c:\agrigest\tmp\'+qtratamientosdetalleregistro.AsString+'.pdf'),'','',SW_SHOWNORMAL);
    end;

end;

procedure Ttratamientos.Button4Click(Sender: TObject);
var imprimirtodo,vparcela,vresponsable:string;
begin

   if combobuscarparcelas.keyvalue=null then vparcela:='%' else vparcela:=combobuscarparcelas.keyvalue;
   if combobuscarresponsables.keyvalue=null then vresponsable:='%' else vresponsable:=combobuscarresponsables.keyvalue;
   if chkimptodo.Checked then imprimirtodo:='%' else imprimirtodo:='1';
   qtratamientos.Close;
   qtratamientos.Prepare;
   qtratamientos.ParamByName('parcela').AsString:=vparcela;
   qtratamientos.ParamByName('responsable').AsString:=vresponsable;
   qtratamientos.ParamByName('DESDE').AsDate:=fdesde.Date;
   qtratamientos.ParamByName('HASTA').AsDate:=fhasta.Date;
   qtratamientos.ParamByName('MOSTRAR').asstring:=imprimirtodo;
   qtratamientos.Open;
    qcargas.Close;
    qcargas.Prepare;
    qcargas.ParamByName('EMPRESA').AsInteger:=qtratamientoside.AsInteger;
    qcargas.ParamByName('TRATAMIENTO').AsString:='%';
    qcargas.Open;
    qtratamientosdetalle.Filter:='en_cuaderno=1';
    qtratamientosdetalle.Filtered:=true;
    informes.Report.Clear;
    informes.LoadFromFile('c:\agrigest\informes\inftratamientos.fr3');
    informes.ShowReport();
    qtratamientos.Filtered:=false;
    qtratamientosdetalle.Filtered:=false;
end;

procedure Ttratamientos.Button5Click(Sender: TObject);
begin
    if qtratamientoscontabilizado.AsInteger=0 then
    begin
    contabilizando:=1;
    try
      qconsumos.Open;
      qtratamientosdetalle.First;
      while not qtratamientosdetalle.Eof do
      begin

        qarticulo.Close;
        qarticulo.Prepare;
        qarticulo.ParamByName('IDAF').AsString:=qtratamientosdetalleidaf.AsString;
        qarticulo.ParamByName('IDEMPRESA').AsString:=qtratamientoside.AsString;
        qarticulo.Open;
        qstock.Close;
        qstock.Prepare;
        qstock.ParamByName('CODIGO').AsString:=qarticulocodigo.AsString;
        qstock.ParamByName('EMPRESA').AsString:=qtratamientoside.AsString;
        qstock.Open;
        try
          qconsumos.Append;
          qaux2.Close;
          qaux2.Open;
          qconsumosid.Value:=qaux2.Fields[0].asinteger;
          qconsumosidfraccionado.Value:=qaux2.Fields[0].asinteger;;
          qconsumoside.Value:=dm.tempresaid.asinteger;
          qconsumosnumplazos.value:=1;
          qconsumosdescripcion.Value:=qtratamientosdetalledescripcion_af.AsString;
          qconsumoscantidad.Value:=qtratamientosdetallecantidad_materia.Asfloat;
          qconsumosprecio.Value:=qarticulopreciocoste.AsFloat;
          qconsumostotal.Value:=qtratamientosdetallecantidad_materia.Asfloat*qarticulopreciocoste.AsFloat;
          qconsumostotal_amortizado.value:=qtratamientosdetallecantidad_materia.Asfloat*qarticulopreciocoste.AsFloat;
          qconsumosfecha.Value:=qtratamientosfecha.AsDateTime;
          qconsumosidcc.Value:=qtratamientosidcc.Asstring;
          qconsumoscodigo.Value:=qarticulocodigo.AsString;
          qconsumosidgrupo.Value:=qarticuloidgrupo.AsInteger;
          qconsumosidfamilia.Value:=qarticuloidfamilia.Asinteger;
          qconsumoslote.AsString:=qstocklote.AsString;
          qconsumosregistro.AsString:=qarticuloregistro.AsString;
          qconsumosidentrada.Value:=qstockid.AsInteger;
          qconsumosamortizacion.Value:=0;
          qconsumos.Post;
        finally
          qtratamientosdetalle.Edit;
          qtratamientosdetalleidconsumo.value:=qaux2.Fields[0].AsInteger;
          qtratamientosdetalle.Post;
          qtratamientosdetalle.Next;
        end;
      end;
    finally
        qtratamientos.Edit;
        qtratamientoscontabilizado.Value:=1;
        qtratamientos.Post;
    end;
        contabilizando:=0;
  end;
end;

procedure Ttratamientos.Button6Click(Sender: TObject);
begin
    qcargas.Close;
    qcargas.Prepare;
    qcargas.ParamByName('EMPRESA').AsInteger:=qtratamientoside.AsInteger;
    qcargas.ParamByName('TRATAMIENTO').AsString:=qtratamientosid.AsString;
    qcargas.Open;
    qtratamientos.Filter:='id='+qtratamientosid.Asstring;
    qtratamientos.Filtered:=true;
    qtratamientosdetalle.Filter:='en_cuaderno=1';
    qtratamientosdetalle.Filtered:=true;
    informes.Report.Clear;
    informes.LoadFromFile('c:\agrigest\informes\inftratamientos.fr3');
    informes.ShowReport();
    qtratamientos.Filtered:=false;
    qtratamientosdetalle.Filtered:=false;
end;

procedure Ttratamientos.Button7Click(Sender: TObject);
var direccion:pwidechar;
    registro,cadena:string;
begin
   while not qtratamientosdetalle.eof do
   begin

    registro:= qtratamientosdetalleregistro.AsString;
    if registro<>'' then
    begin
      qaux.SQL.Clear;
      qaux.SQL.Add('select registro,autorizado from productos_fitosanitarios where registro=:REGISTRO');
      qaux.Prepare;
      qaux.ParamByName('REGISTRO').AsString:=registro;
      qaux.Open;
      if qaux.RecordCount>0 then
      begin
        if qaux.Fields[1].AsInteger=1 then
        begin
//          TWebHelper.AbrirURL('https://servicio.mapa.gob.es/regfiweb/VerFicha/Index?numRegistro='+dtarticulosfinalregistro.AsString);
          cadena:='https://servicio.mapa.gob.es/regfiweb/VerFicha/Index?numRegistro='+registro;
          direccion:=pwidechar(widestring(cadena));
          URLDownloadToFile(nil, direccion, 'C:\agrigest\tmp\ficha.pdf', 0, nil);
          qtratamientosdetalle.Edit;
          qtratamientosdetalleficha.LoadFromFile('c:\agrigest\tmp\ficha.pdf');
        end else showmessage('PRODUCTO NO AUTORIZADO EN PRODUCTOS FITOSANITARIOS AUTORIZADOS');
      end else showmessage('PRODUCTO NO ENCONTRADO EN PRODUCTOS FITOSANITARIOS AUTORIZADOS');
    end;
    qtratamientosdetalle.Next;
   end;

end;

procedure Ttratamientos.Button8Click(Sender: TObject);
var vparcela,vresponsable,vvariedad:string;
begin
   if combobuscarparcelas.keyvalue=null then vparcela:='%' else vparcela:=combobuscarparcelas.keyvalue;
   if combobuscarresponsables.keyvalue=null then vresponsable:='%' else vresponsable:=combobuscarresponsables.keyvalue;
   if combovariedades.keyvalue=null then vvariedad:='%' else vvariedad:=combovariedades.keyvalue;
   qinsertarencuaderno.Close;
   qinsertarencuaderno.Prepare;
   qinsertarencuaderno.ParamByName('parcela').AsString:=vparcela;
   qinsertarencuaderno.ParamByName('responsable').AsString:=vresponsable;
   qinsertarencuaderno.ParamByName('variedad').AsString:=vvariedad;
   qinsertarencuaderno.ParamByName('DESDE').AsDate:=fdesde.Date;
   qinsertarencuaderno.ParamByName('HASTA').AsDate:=fhasta.Date;
   qinsertarencuaderno.ExecSQL;
   qinsertarencuadernodetalle.Close;
   qinsertarencuadernodetalle.Prepare;
   qinsertarencuadernodetalle.ParamByName('parcela').AsString:=vparcela;
   qinsertarencuadernodetalle.ParamByName('responsable').AsString:=vresponsable;
   qinsertarencuadernodetalle.ParamByName('variedad').AsString:=vvariedad;
   qinsertarencuadernodetalle.ParamByName('DESDE').AsDate:=fdesde.Date;
   qinsertarencuadernodetalle.ParamByName('HASTA').AsDate:=fhasta.Date;
   qinsertarencuadernodetalle.ExecSQL;
end;

procedure Ttratamientos.btfiltrarClick(Sender: TObject);
var vparcela,vresponsable,vvariedad:string;
begin
   if combobuscarparcelas.keyvalue=null then vparcela:='%' else vparcela:=combobuscarparcelas.keyvalue;
   if combobuscarresponsables.keyvalue=null then vresponsable:='%' else vresponsable:=combobuscarresponsables.keyvalue;
   if combovariedades.keyvalue=null then vvariedad:='%' else vvariedad:=combovariedades.keyvalue;

   qtratamientos.Close;
   qtratamientos.Prepare;
   qtratamientos.ParamByName('parcela').AsString:=vparcela;
   qtratamientos.ParamByName('responsable').AsString:=vresponsable;
   qtratamientos.ParamByName('variedad').AsString:=vvariedad;
   qtratamientos.ParamByName('DESDE').AsDate:=fdesde.Date;
   qtratamientos.ParamByName('HASTA').AsDate:=fhasta.Date;
   qtratamientos.ParamByName('MOSTRAR').asstring:='%';
   qtratamientos.Open;

end;


procedure Ttratamientos.Button9Click(Sender: TObject);
begin
    combobuscarparcelas.KeyValue:=null;
    combobuscarresponsables.KeyValue:=null;
    combovariedades.KeyValue:=null;
    btfiltrar.click;
end;

procedure Ttratamientos.DBGrid3CellClick(Column: TColumn);
begin
    if column.Field.FieldName ='completado' then
    begin
        if qtratamientoscompletado.asinteger=1 then
         begin
           qtratamientos.Edit;
           qtratamientoscompletado.Value:=0;
           qtratamientos.Post;
           dbgrid3.selectedIndex:=1;
         end else
               begin
                 qtratamientos.Edit;
                 qtratamientoscompletado.Value:=1;
                 qtratamientos.Post;
                 qtratamientos.Refresh;
                 dbgrid3.SelectedIndex:=1;
               end;
    end;
end;

procedure Ttratamientos.DBGrid3ColExit(Sender: TObject);
begin
     if qtratamientos.State in [dsinsert,dsedit] then
     begin
       qtratamientosfecha.Value:=ffecha.Date;
     end else
     begin
//         qtratamientos.Edit;
//         qtratamientosfecha.Value:=ffecha.Date;
     end;
end;

procedure Ttratamientos.DBGrid3DrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
const IsChecked : array[Boolean] of Integer =
 (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED);
var
  DrawState,imgindex,bmpwidth: Integer;
  DrawRect: TRect;
begin
    if (qtratamientoscontabilizado.Asinteger=0)then
    begin
        DBGrid3.Canvas.brush.Color := rojo;
    end else DBGrid3.Canvas.brush.Color := verde;
    if (qtratamientoscompletado.Asinteger=1) and (qtratamientoscontabilizado.Asinteger=0)then
    begin
        DBGrid3.Canvas.brush.Color := azul;
    end;
    DBGrid3.DefaultDrawColumnCell(Rect, DataCol, Column, State);


if (gdFocused in State) then
begin

    if (Column.Field.FieldName = 'contabilizado') then
     begin
       gcrpagado.Left := Rect.Left + DBgrid3.Left + 2;
       gcrpagado.Top := Rect.Top + DBgrid3.top + 2;
       gcrpagado.Width := Rect.Right - Rect.Left;
       gcrpagado.Height := Rect.Bottom - Rect.Top;
       gcrpagado.Visible := True;
     end;
end else
     begin

       if (Column.Field.FieldName = 'contabilizado') then
       begin
         DrawRect:=Rect;
         InflateRect(DrawRect,-1,-1);
         if column.Field.Asinteger=0  then DrawState := ischecked[false];
         if column.Field.Asinteger=1  then DrawState := ischecked[true];
         DBgrid3.Canvas.FillRect(Rect);
         DrawFrameControl(DBgrid3.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState);
       end;
    end;

if (gdFocused in State) then
begin

    if (Column.Field.FieldName = 'completado') then
     begin
       gcrpagado.Left := Rect.Left + DBgrid3.Left + 2;
       gcrpagado.Top := Rect.Top + DBgrid3.top + 2;
       gcrpagado.Width := Rect.Right - Rect.Left;
       gcrpagado.Height := Rect.Bottom - Rect.Top;
       gcrpagado.Visible := True;
     end;
end else
     begin

       if (Column.Field.FieldName = 'completado') then
       begin
         DrawRect:=Rect;
         InflateRect(DrawRect,-1,-1);
         if column.Field.Asinteger=0  then DrawState := ischecked[false];
         if column.Field.Asinteger=1  then DrawState := ischecked[true];
         DBgrid3.Canvas.FillRect(Rect);
         DrawFrameControl(DBgrid3.Canvas.Handle, DrawRect,DFC_BUTTON, DrawState);
       end;
    end;
    gcrpagado.visible:=false;

  if (gdFocused in State) then
  begin
    if (Column.Field.FieldName = combocentrocoste.DataField) then
    with combocentrocoste do
    begin
      Left := Rect.Left + DBGrid3.Left + 2;
      Top := Rect.Top + DBGrid3.Top + 2;
      Width := Rect.Right - Rect.Left;
      Width := Rect.Right - Rect.Left;
      Height := Rect.Bottom - Rect.Top;
      Visible := True;
      setfocus;
      dropdown;
    end else combocentrocoste.Visible:=false;
    if (Column.Field.FieldName = comboresponsables.DataField) then
    with comboresponsables do
    begin
      Left := Rect.Left + DBGrid3.Left + 2;
      Top := Rect.Top + DBGrid3.Top + 2;
      Width := Rect.Right - Rect.Left;
      Width := Rect.Right - Rect.Left;
      Height := Rect.Bottom - Rect.Top;
      Visible := True;
      setfocus;
      dropdown;
    end else comboresponsables.Visible:=false;
    if (Column.Field.FieldName = combotractores.DataField) then
    with combotractores do
    begin
      Left := Rect.Left + DBGrid3.Left + 2;
      Top := Rect.Top + DBGrid3.Top + 2;
      Width := Rect.Right - Rect.Left;
      Width := Rect.Right - Rect.Left;
      Height := Rect.Bottom - Rect.Top;
      Visible := True;
      setfocus;
      dropdown;
    end else combotractores.Visible:=false;
    if (Column.Field.FieldName = combodepositos.DataField) then
    with combodepositos do
    begin
      Left := Rect.Left + DBGrid3.Left + 2;
      Top := Rect.Top + DBGrid3.Top + 2;
      Width := Rect.Right - Rect.Left;
      Width := Rect.Right - Rect.Left;
      Height := Rect.Bottom - Rect.Top;
      Visible := True;
      setfocus;
      dropdown;
    end else combodepositos.Visible:=false;
    if (Column.Field.FieldName = combovelocidad.DataField) then
    with combovelocidad do
    begin
      Left := Rect.Left + DBGrid3.Left + 2;
      Top := Rect.Top + DBGrid3.Top + 2;
      Width := Rect.Right - Rect.Left;
      Width := Rect.Right - Rect.Left;
      Height := Rect.Bottom - Rect.Top;
      Visible := True;
      setfocus;
      dropdown;
    end else combovelocidad.Visible:=false;
    if (Column.Field.FieldName = combopresiones.DataField) then
    with combopresiones do
    begin
      Left := Rect.Left + DBGrid3.Left + 2;
      Top := Rect.Top + DBGrid3.Top + 2;
      Width := Rect.Right - Rect.Left;
      Width := Rect.Right - Rect.Left;
      Height := Rect.Bottom - Rect.Top;
      Visible := True;
      setfocus;
      dropdown;
    end else combopresiones.Visible:=false;
    if (Column.Field.FieldName = comboboquillas.DataField) then
    with comboboquillas do
    begin
      Left := Rect.Left + DBGrid3.Left + 2;
      Top := Rect.Top + DBGrid3.Top + 2;
      Width := Rect.Right - Rect.Left;
      Width := Rect.Right - Rect.Left;
      Height := Rect.Bottom - Rect.Top;
      Visible := True;
      setfocus;
      dropdown;
    end else comboboquillas.Visible:=false;
    if (Column.Field.FieldName = comboventilador.DataField) then
    with comboventilador do
    begin
      Left := Rect.Left + DBGrid3.Left + 2;
      Top := Rect.Top + DBGrid3.Top + 2;
      Width := Rect.Right - Rect.Left;
      Width := Rect.Right - Rect.Left;
      Height := Rect.Bottom - Rect.Top;
      Visible := True;
      setfocus;
      dropdown;
    end else comboventilador.Visible:=false;
    if (Column.Field.FieldName = combooperarios.DataField) then
    with combooperarios do
    begin
      Left := Rect.Left + DBGrid3.Left + 2;
      Top := Rect.Top + DBGrid3.Top + 2;
      Width := Rect.Right - Rect.Left;
      Width := Rect.Right - Rect.Left;
      Height := Rect.Bottom - Rect.Top;
      Visible := True;
      setfocus;
      dropdown;
    end else combooperarios.Visible:=false;
    if (Column.Field.FieldName = 'fecha') then
    with ffecha do
    begin
      Left := Rect.Left + DBGrid3.Left + 2;
      Top := Rect.Top + DBGrid3.Top + 2;
      Width := Rect.Right - Rect.Left;
      Width := Rect.Right - Rect.Left;
      Height := Rect.Bottom - Rect.Top;
      Visible := True;
    end else
    begin
     ffecha.Visible:=false;
    end;
  end;

end;

procedure Ttratamientos.DBGrid3TitleClick(Column: TColumn);
var
  st:ZAbstractRODataset.TSortType;
begin
  st:=qtratamientos.SortType;
  qtratamientos.SortedFields:=Column.FieldName;
  If st = stAscending then qtratamientos.SortType:=stDescending else qtratamientos.SortType:=stAscending;
  dsqtratamientos.DataSet.First;
end;



procedure Ttratamientos.DBGrid4CellClick(Column: TColumn);
var
  TempPath: string;
  FileName: string;
  BlobField: TBlobField;
  frmEntradas: Tentradas;
  idEntrada_Entradas: integer;
begin
  // 1. Identificamos si se ha pulsado en la columna de la Ficha
  if (CompareText(Column.FieldName, 'ficha') = 0) then
  begin
    // 2. Validamos si el campo tiene datos
    if not Column.Field.IsNull and (Column.Field.AsString <> '') then
    begin
      // En Delphi XE3, tratamos el campo como TBlobField para mayor seguridad
      BlobField := Column.Field as TBlobField;

      // 3. Definimos una ruta temporal segura
      // Sugerencia: El nombre del archivo podría incluir el ID del tratamiento
      FileName := TPath.Combine(TPath.GetTempPath,
                  Format('Ficha_producto_%s.pdf', [qtratamientosdetalle.FieldByName('descripcion_af').AsString]));

      try
        // 4. Extraemos el BLOB de MySQL al disco local
        // Nota: SaveToFile es sumamente eficiente en XE3/FireDAC
        BlobField.SaveToFile(FileName);

        // 5. Ejecutamos el archivo con el visor predeterminado (Adobe, Navegador, etc.)
        ShellExecute(Handle, 'open', PChar(FileName), nil, nil, SW_SHOWNORMAL);
      except
        on E: Exception do
          ShowMessage('Error al exportar la ficha: ' + E.Message);
      end;
    end;
  end;


  if (CompareText(Column.FieldName, 'identrada') = 0) then
  begin
    if (qtratamientosdetalleidentrada.AsInteger > 0) then
    begin
      qaux.Close;
      qaux.SQL.Text := 'SELECT identrada FROM entradas_detalle WHERE id = :id';
      qaux.ParamByName('id').AsInteger := qtratamientosdetalleidentrada.AsInteger;
      qaux.Open;

      if not qaux.IsEmpty then
      begin
        idEntrada_Entradas := qaux.FieldByName('identrada').AsInteger;
        frmEntradas := Tentradas.Create(nil);
        try
          frmEntradas.tbuscar.Text := IntToStr(idEntrada_Entradas);
          frmEntradas.ShowModal();
        finally
          frmEntradas.Free;
        end;
      end;
      qaux.Close;
    end;
  end;
end;
procedure Ttratamientos.dsqtratamientosDataChange(Sender: TObject; Field: TField);
begin
  if not qtratamientos.Active then Exit;

  if qtratamientos.IsEmpty then
  begin
    qtratamientosdetalle.Close;
    qnombrecampanya.Close;
    qresumenproductos.Close;
    Exit;
  end;

  if qtratamientos.State in [dsbrowse] then
  begin
     ffecha.Date:=qtratamientosfecha.AsDateTime;
     comboresponsables.Visible:=false;
     combocentrocoste.Visible:=false;
  end;

  qtratamientosdetalle.Close;
  qtratamientosdetalle.Prepare;
  qtratamientosdetalle.ParamByName('EMPRESA').AsInteger := qtratamientoside.AsInteger;
  qtratamientosdetalle.ParamByName('TRATAMIENTO').AsInteger := qtratamientosid.AsInteger;
  qtratamientosdetalle.Open;

  qnombrecampanya.Close;
  qnombrecampanya.Prepare;
  qnombrecampanya.ParamByName('FECHA').AsDateTime := qtratamientosfecha.AsDateTime;
  qnombrecampanya.Open;

  qresumenproductos.Close;
  qresumenproductos.Prepare;
  qresumenproductos.ParamByName('PARCELA').AsString := qtratamientosidcc.AsString;
  if not qnombrecampanya.IsEmpty then
    qresumenproductos.ParamByName('CAMPANYA').AsString := qnombrecampanyadescripcion.AsString
  else
    qresumenproductos.ParamByName('CAMPANYA').AsString := '';
  qresumenproductos.Open;
end;

procedure Ttratamientos.DBGrid4KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
    if (key=115) then
    begin
      buscararticulos := Tbuscararticulos.Create(nil);
      try
        fbuscararticulos.filtro:=qtratamientosdetalledescripcion_af.AsString;
        buscararticulos.Edit1.Text:=qtratamientosdetalledescripcion_af.AsString;
        buscararticulos.showmodal();
      finally
        if qtratamientosdetalle.State in [dsbrowse] then qtratamientosdetalle.Edit;
        qtratamientosdetalleidaf.Value:=buscararticulos.qarticulosid.Asinteger;
        qtratamientosdetalleregistro.Value:=buscararticulos.qarticulosregistro.Asstring;
        qtratamientosdetalledescripcion_af.value:=buscararticulos.qarticulosdescripcion.AsString;
        qtratamientosdetalledescripcion_ma.Value:=buscararticulos.qarticulosmateria_activa.Asstring;
        qtratamientosdetalledosis.value:=0;
        qtratamientosdetalleplazo.value:=buscararticulos.qarticulosplazo_seguridad.Asinteger;
        buscararticulos.Free;
      end;
    end;
end;

procedure Ttratamientos.DBGrid4TitleClick(Column: TColumn);
var
  st:ZAbstractRODataset.TSortType;
begin
  st:=qtratamientosdetalle.SortType;
  qtratamientos.SortedFields:=Column.FieldName;
  If st = stAscending then qtratamientosdetalle.SortType:=stDescending else qtratamientosdetalle.SortType:=stAscending;
  dsqtratamientosdetalle.DataSet.First;
end;

procedure Ttratamientos.DBGrid5DrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
    if (qresumenproductos.FieldByName('num_tratamientos').AsInteger > qresumenproductos.FieldByName('num_aplicaciones').AsInteger) then
    begin
        DBGrid5.Canvas.brush.Color := rojo;
    end ;
    DBGrid5.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure Ttratamientos.dsqcampanyasDataChange(Sender: TObject; Field: TField);
begin
   qtratamientosbase.Close;
   qtratamientosbase.Prepare;
   qtratamientosbase.ParamByName('FINICIO').AsDate:=qcampanyasfechainicio.asdatetime;
   qtratamientosbase.ParamByName('FFIN').AsDate:=qcampanyasfechafin.asdatetime;
   qtratamientosbase.ParamByName('EMPRESA').Asinteger:=qcampanyasidempresa.AsInteger;
   qtratamientosbase.Open;
end;

procedure Ttratamientos.dsqtratamientosdetalleDataChange(Sender: TObject;
  Field: TField);
begin
      qresumenproductos.Locate('descripcion_af',qtratamientosdetalledescripcion_af.AsString,[loCaseInsensitive]);
end;

procedure Ttratamientos.BtnAyudaClick(Sender: TObject);
var
  Dialog: TTaskDialog;
begin
  Dialog := TTaskDialog.Create(Self);
  try
    Dialog.Caption := 'Guía de Procesos: Gestión de Tratamientos';
    Dialog.Title := 'Ayuda Contextual - Pantalla de Tratamientos';

    // Contenido detallado de los procesos de esta pantalla
    Dialog.Text :=
      'En esta pantalla puede gestionar los tratamientos técnicos. ' + sLineBreak + sLineBreak +
      '📌 ICONOS DE LA TABLA:' + sLineBreak +
      '• Columna [Cuaderno]: Indica si el registro ha sido validado para el cuaderno de explotación.' + sLineBreak +
      '• Icono [Diamante]: Indica que existe una ficha técnica vinculada. Haga clic sobre el diamante para abrir el documento.' + sLineBreak + sLineBreak +
      '✅ PROCESOS VERI*FACTU:' + sLineBreak +
      'Los registros con diamante ya han generado su huella digital y están listos para el envío a la AEAT.';

    Dialog.CommonButtons := [tcbClose];
    Dialog.MainIcon := tdiInformation;
    Dialog.Execute;
  finally
    Dialog.Free;
  end;
end;
procedure Ttratamientos.DBGrid4DrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
  DrawRect: TRect;
  ImgIndex: Integer;
  Bitmap: TBitmap;
  DrawState: Integer;
begin
  // 1. COLUMNA DE CHECKBOX (en_cuaderno)
  if (Column.FieldName = 'en_cuaderno') then
  begin
    DBGrid4.Canvas.FillRect(Rect);
    DrawRect := Rect;
    InflateRect(DrawRect, -2, -2);

    if Column.Field.AsInteger = 1 then
      DrawState := DFCS_BUTTONCHECK or DFCS_CHECKED
    else
      DrawState := DFCS_BUTTONCHECK;

    DrawFrameControl(DBGrid4.Canvas.Handle, DrawRect, DFC_BUTTON, DrawState);

    // Gestión del control flotante (solo si tiene el foco)
    if (gdFocused in State) then
    begin
      gcrpagado.SetBounds(Rect.Left + DBGrid4.Left + 1,
                          Rect.Top + DBGrid4.Top + 1,
                          Rect.Width - 1, Rect.Height - 1);
      if not gcrpagado.Visible then gcrpagado.Visible := True;
    end
    else
      gcrpagado.Visible := False;

    Exit; // Salimos para evitar que DefaultDraw dibuje nada encima
  end;

  // 2. COLUMNA DE FICHA (Icono sin texto BLOB)
  if (Column.FieldName = 'ficha') then // Asegúrate que este sea el FieldName real en MySQL
  begin
    // Limpiamos el fondo de la celda (esto borra cualquier texto previo)
    DBGrid4.Canvas.FillRect(Rect);

    if qtratamientosdetalleficha.AsString <> '' then
      ImgIndex := 88
    else
      ImgIndex := -1;

    if ImgIndex >= 0 then
    begin
      Bitmap := TBitmap.Create;
      try
        base.listaiconos.GetBitmap(ImgIndex, Bitmap);

        // Centramos el icono en la celda
        DrawRect.Left := Rect.Left + ((Rect.Width - Bitmap.Width) div 2);
        DrawRect.Top := Rect.Top + ((Rect.Height - Bitmap.Height) div 2);
        DrawRect.Right := DrawRect.Left + Bitmap.Width;
        DrawRect.Bottom := DrawRect.Top + Bitmap.Height;

        DBGrid4.Canvas.Draw(DrawRect.Left, DrawRect.Top, Bitmap);
      finally
        Bitmap.Free;
      end;
    end;

    { CRUCIAL: No llamamos a DefaultDrawColumnCell aquí.
      Al no llamarlo, evitamos que Delphi pinte el texto "(BLOB)" }
    Exit;
  end;

  // 3. DIBUJO POR DEFECTO PARA EL RESTO DE COLUMNAS
  // 3. COLUMNA DE ENTRADA (Icono de Info)
  if (Column.FieldName = 'identrada') then
  begin
    // Limpiamos el rectángulo para ocultar el número del ID que Delphi pinta por defecto
    DBGrid4.Canvas.FillRect(Rect);

    // Dibujamos el icono en forma de texto
    if (qtratamientosdetalleidentrada.AsInteger > 0) then
    begin
      DBGrid4.Canvas.Font.Color := clBlue;
      DBGrid4.Canvas.Font.Size := 10;
      DBGrid4.Canvas.Font.Style := [fsBold];
      DBGrid4.Canvas.TextOut(Rect.Left + (Rect.Width div 2) - 4, Rect.Top + 2, 'ⓘ');
    end;

    Exit;
  end;

      qresumenproductos.Locate('descripcion_af',qtratamientosdetalledescripcion_af.AsString,[loCaseInsensitive]);
end;

procedure Ttratamientos.dsqtratamientosStateChange(Sender: TObject);
begin
    if qtratamientos.State in [dsedit,dsinsert] then
    begin
        btanuevo.Enabled:=false;
        btamodificar.Enabled:=false;
        btaborrar.Enabled:=false;
        btacancelar.Enabled:=true;
        btaguardar.Enabled:=true;
        btareutilizar.enabled:=false;
        button3.Enabled:=false;
        button2.Enabled:=false;


    end else
    begin
        btanuevo.Enabled:=true;
        btamodificar.Enabled:=true;
        btaborrar.Enabled:=true;
        btacancelar.Enabled:=false;
        btaguardar.Enabled:=false;
        panel2.Visible:=false;
        button1.Visible:=false;
        btareutilizar.enabled:=true;
        button2.Enabled:=true;
        button3.Enabled:=true;
        ffecha.visible:=false;
        comboresponsables.Visible:=false;
        combocentrocoste.Visible:=false;

    end;
end;

procedure Ttratamientos.FfechaChange(Sender: TObject);
begin
   qtratamientos.Edit;
end;


procedure Ttratamientos.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_F1 then
    BtnAyudaClick(nil);
end;

procedure Ttratamientos.FormKeyPress(Sender: TObject; var Key: Char);
begin
   key:=upcase(key);
    if (key='.') and (activecontrol is tdbgrid) then
    begin
        key:=','
    end;
    if (activecontrol is tdbgrid) then
    begin
        if Key = #13 then Key :=#9;
    end;

    if (key=#13) then
    begin
        Perform(WM_NextDLGCtl,0,0);
        key:=#0;
    end;
// si presionamos ESC
    if (key=#$1B)  and (activecontrol is tdblookupcombobox )then
    begin
      activecontrol.Visible:=false;
    end;


end;

procedure Ttratamientos.FormShow(Sender: TObject);
var anyo,mes,dia:word;
begin
   decodedate(date,anyo,mes,dia);
   fdesde.Date:=(strtodate('01/01/'+inttostr(anyo)));
   fhasta.Date:=(strtodate('31/12/'+inttostr(anyo)));
   ffecha.Date:=date;

   qcampanyas.Open;
   combocampanyas.KeyValue:=qcampanyasdescripcion.Asstring;
   qtratamientosbasedetalle.Close;
   qcentrocoste.close;
   qresponsables.Close;
   qtratamientos.Close;
   qtratamientosdetalle.close;
   qcentrocoste2.close;
   qresponsables2.Close;
   qmateriaprima2.Close;
   qtractores.close;
   qvelocidad.close;
   qdepositos.close;
   qboquillas.close;
   qpresiones.close;
   qventilador.close;
   qtratamientosbasedetalle.open;
   qcentrocoste.open;
   qresponsables.open;
   qcentrocoste2.open;
   qresponsables2.open;
   qmateriaprima2.open;
    // Removed premature open to prevent database exception
    // Removed premature open to prevent database exception
    // Removed premature open to prevent database exception
   qtratamientos.ParamByName('parcela').AsString:='%';
   qtratamientos.ParamByName('responsable').AsString:='%';
   qtratamientos.ParamByName('DESDE').AsDate:=fdesde.Date;
   qtratamientos.ParamByName('HASTA').AsDate:=fhasta.Date;
   qtratamientos.ParamByName('MOSTRAR').asstring:='%';
   qtratamientos.Prepare;
   qtratamientos.open;

   qtractores.Open;
   qvelocidad.Open;
   qdepositos.Open;
   qboquillas.Open;
   qpresiones.Open;
   qventilador.Open;
   qoperarios.Open;
   button9.Click;

end;

procedure Ttratamientos.qtratamientosAfterPost(DataSet: TDataSet);
begin
   qtractores.refresh;
   qvelocidad.refresh;
   qdepositos.refresh;
   qboquillas.refresh;
   qpresiones.refresh;
   qventilador.refresh;
   qoperarios.Refresh;
end;

procedure Ttratamientos.qtratamientosBeforeDelete(DataSet: TDataSet);
begin
   case dm.PedirConfirmacion('¿Confirma que desea borrar este tratamiento?',true,true,false) of
        mrno:Abort;
   end;
end;

procedure Ttratamientos.qtratamientosBeforePost(DataSet: TDataSet);
var x:integer;
begin
if contabilizando=0 then
begin
    qmateriaprima.Close;
    qmateriaprima.Prepare;
    qmateriaprima.ParamByName('EMPRESA').AsInteger:=qtratamientoside.asinteger;
    qmateriaprima.ParamByName('PARCELA').Asstring:=qtratamientosidcc.asstring;
    qmateriaprima.Open;
    qtratamientosvariedad.asstring:=qmateriaprimadescripcion.AsString;
    qtratamientosidcc.Value:=qcentrocostecodpar.AsString;
    if qtratamientos.state=dsinsert then x:=dm.PedirConfirmacion('¿Confirma que desea dar de alta este tratamiento?',true,true,true)
                                     else x:=dm.PedirConfirmacion('¿Confirma que desea modificar este tratamiento?',true,true,true);
    case x of
        mrno: begin
                 qtratamientos.cancel;
                 abort;
              end;
        mrcancel:BEGIN
                 abort;
                 END;

    end;
end;
end;

procedure Ttratamientos.qtratamientosdetalleAfterDelete(DataSet: TDataSet);
begin
    qresumenproductos.Refresh;
end;

procedure Ttratamientos.qtratamientosdetalleAfterPost(DataSet: TDataSet);
begin
    qtratamientosdetalle.Refresh;
    qresumenproductos.Refresh;
end;

procedure Ttratamientos.qtratamientosdetalleBeforeDelete(DataSet: TDataSet);
begin
   case dm.PedirConfirmacion('¿Confirma que desea borrar este tratamiento?',true,true,false) of
        mrno:Abort;
   end;
end;

procedure Ttratamientos.qtratamientosdetalleBeforePost(DataSet: TDataSet);
var x:integer;
begin
qtratamientosdetalleide.Value:=qtratamientoside.AsInteger;
qtratamientosdetalleidt.Value:=qtratamientosid.AsInteger;
if contabilizando=0 then
begin
    if qtratamientosdetalle.state=dsinsert then x:=dm.PedirConfirmacion('¿Confirma que desea dar de alta este producto?',true,true,true)
                                     else x:=dm.PedirConfirmacion('¿Confirma que desea modificar este producto?',true,true,true);
    case x of
        mrno: begin
                 qtratamientosdetalle.cancel;
                 abort;
              end;
        mrcancel:BEGIN
                 abort;
                 END;

    end;
end;
end;

procedure Ttratamientos.qtratamientosdetalleCalcFields(DataSet: TDataSet);
begin
    if qtratamientosdetalleficha.AsString<>'' then qtratamientosdetalleconficha.Value:=' ' else qtratamientosdetalleconficha.Value:='';

end;

end.
