unit frm_VentasPreciosHistorico;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
  Vcl.Grids, Vcl.DBGrids, Data.DB, Vcl.Buttons, Vcl.ComCtrls,
  FireDAC.Comp.Client, FireDAC.Stan.Param,
  frm_BaseList, uAppTheme, frm_PrintOptions;

type
  TfrmVentasPreciosHistorico = class(TfrmBaseList)
    procedure FormShow(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure btnRefreshClick(Sender: TObject); override;
  private
    FIdArticulo: Integer;
    FIdCliente: Integer;
    FIdGrupo: Integer;
    FOrigenTarifa: string;
    FTituloContextual: string;

    FcbbFiltroTipo: TComboBox;
    FlblFiltroTipo: TLabel;
    FlblContexto: TLabel;
    FbtnLimpiarContexto: TSpeedButton;
    FchkFiltrarFechas: TCheckBox;
    FdtpDesde: TDateTimePicker;
    FlblHasta: TLabel;
    FdtpHasta: TDateTimePicker;
    FbtnCerrar: TSpeedButton;

    procedure ConfigureColumns;
    procedure FormatNumericFields(DataSet: TDataSet);
    procedure dbGridCustomDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure cbbFiltroTipoChange(Sender: TObject);
    procedure FiltroFechasChange(Sender: TObject);
    procedure btnLimpiarContextoClick(Sender: TObject);
    procedure btnCerrarClick(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
  public
    class procedure MostrarHistorico(
      AOwner: TComponent;
      const AOrigenTarifa: string = '';
      AIdArticulo: Integer = 0;
      AIdCliente: Integer = 0;
      AIdGrupo: Integer = 0;
      const ATitulo: string = '');

    property IdArticulo: Integer read FIdArticulo write FIdArticulo;
    property IdCliente: Integer read FIdCliente write FIdCliente;
    property IdGrupo: Integer read FIdGrupo write FIdGrupo;
    property OrigenTarifa: string read FOrigenTarifa write FOrigenTarifa;
    property TituloContextual: string read FTituloContextual write FTituloContextual;
  end;

var
  frmVentasPreciosHistorico: TfrmVentasPreciosHistorico;

implementation

uses
  dmg_Main;

{$R *.dfm}

class procedure TfrmVentasPreciosHistorico.MostrarHistorico(
  AOwner: TComponent;
  const AOrigenTarifa: string;
  AIdArticulo, AIdCliente, AIdGrupo: Integer;
  const ATitulo: string);
var
  LForm: TfrmVentasPreciosHistorico;
begin
  LForm := TfrmVentasPreciosHistorico.Create(AOwner);
  try
    LForm.FOrigenTarifa := AOrigenTarifa;
    LForm.FIdArticulo := AIdArticulo;
    LForm.FIdCliente := AIdCliente;
    LForm.FIdGrupo := AIdGrupo;
    LForm.BorderStyle := bsSizeable;
    LForm.BorderIcons := [biSystemMenu, biMaximize];
    LForm.KeyPreview := True;

    if ATitulo <> '' then
      LForm.Caption := ATitulo
    else
      LForm.Caption := 'Histórico de Precios y Tarifas de Venta';

    LForm.Position := poOwnerFormCenter;
    LForm.ShowModal;
  finally
    LForm.Free;
  end;
end;

procedure TfrmVentasPreciosHistorico.FormShow(Sender: TObject);
var
  LOffsetLeft: Integer;
begin
  if not Assigned(frmVentasPreciosHistorico) then
    frmVentasPreciosHistorico := Self;
  OnDestroy := FormDestroy;

  // Ajustes de paneles y botones estándar
  KeyPreview := True;
  OnKeyDown := FormKeyDown;

  pnlSearch.Visible := True;
  lblSearch.Caption := 'Buscar:';
  pnlLeftFilter.Visible := False; // Maximizar área de datos para rejilla ancha

  btnNuevo.Visible := False;
  btnEditar.Visible := False;
  btnBorrar.Visible := False;
  btnPrint.Visible := True;

  // Botón Cerrar en la botonera de acciones
  if not Assigned(FbtnCerrar) then
  begin
    FbtnCerrar := TSpeedButton.Create(Self);
    FbtnCerrar.Tag := 999;
    FbtnCerrar.Parent := pnlActions;
    FbtnCerrar.Align := alRight;
    FbtnCerrar.Width := 60;
    FbtnCerrar.Height := 63;
    FbtnCerrar.Caption := 'Cerrar';
    FbtnCerrar.ImageIndex := 154;
    FbtnCerrar.ImageName := 'icon_salir';
    FbtnCerrar.Images := dmgMain.imgListRibbon;
    FbtnCerrar.Flat := True;
    FbtnCerrar.Font.Charset := DEFAULT_CHARSET;
    FbtnCerrar.Font.Color := clWindowText;
    FbtnCerrar.Font.Height := -11;
    FbtnCerrar.Font.Name := 'Segoe UI';
    FbtnCerrar.Font.Style := [fsBold];
    FbtnCerrar.Layout := blGlyphTop;
    FbtnCerrar.ParentFont := False;
    FbtnCerrar.OnClick := btnCerrarClick;
  end;

  // Si hay título contextual asignado
  if FTituloContextual <> '' then
    Caption := FTituloContextual;

  // Configuración de controles auxiliares de filtro (Tag = 999 para excluir de change tracking)
  LOffsetLeft := edtSearch.Left + edtSearch.Width + 12;

  // 1. Etiqueta y Combo Filtro Tipo
  if not Assigned(FlblFiltroTipo) then
  begin
    FlblFiltroTipo := TLabel.Create(Self);
    FlblFiltroTipo.Tag := 999;
    FlblFiltroTipo.Parent := pnlSearch;
    FlblFiltroTipo.Caption := 'Ámbito:';
    FlblFiltroTipo.Left := LOffsetLeft;
    FlblFiltroTipo.Top := edtSearch.Top + 3;
    LOffsetLeft := LOffsetLeft + FlblFiltroTipo.Width + 4;
  end;

  if not Assigned(FcbbFiltroTipo) then
  begin
    FcbbFiltroTipo := TComboBox.Create(Self);
    FcbbFiltroTipo.Tag := 999;
    FcbbFiltroTipo.Parent := pnlSearch;
    FcbbFiltroTipo.Style := csDropDownList;
    FcbbFiltroTipo.Items.Add('Todos los orígenes');
    FcbbFiltroTipo.Items.Add('Solo PVP Artículos');
    FcbbFiltroTipo.Items.Add('Solo Precios Cliente');
    FcbbFiltroTipo.Items.Add('Solo Precios Grupo');

    // Seleccionar según el contexto si fue especificado
    if FOrigenTarifa = 'PVP_ARTICULO' then
      FcbbFiltroTipo.ItemIndex := 1
    else if FOrigenTarifa = 'CLIENTE' then
      FcbbFiltroTipo.ItemIndex := 2
    else if FOrigenTarifa = 'GRUPO_CLIENTES' then
      FcbbFiltroTipo.ItemIndex := 3
    else
      FcbbFiltroTipo.ItemIndex := 0;

    FcbbFiltroTipo.Left := LOffsetLeft;
    FcbbFiltroTipo.Top := edtSearch.Top;
    FcbbFiltroTipo.Width := 160;
    FcbbFiltroTipo.Height := edtSearch.Height;
    FcbbFiltroTipo.OnChange := cbbFiltroTipoChange;
    LOffsetLeft := LOffsetLeft + FcbbFiltroTipo.Width + 14;
  end;

  // 2. Filtro por Fechas
  if not Assigned(FchkFiltrarFechas) then
  begin
    FchkFiltrarFechas := TCheckBox.Create(Self);
    FchkFiltrarFechas.Tag := 999;
    FchkFiltrarFechas.Parent := pnlSearch;
    FchkFiltrarFechas.Caption := 'Fechas:';
    FchkFiltrarFechas.Left := LOffsetLeft;
    FchkFiltrarFechas.Top := edtSearch.Top + 3;
    FchkFiltrarFechas.Width := 60;
    FchkFiltrarFechas.OnClick := FiltroFechasChange;
    LOffsetLeft := LOffsetLeft + FchkFiltrarFechas.Width + 2;
  end;

  if not Assigned(FdtpDesde) then
  begin
    FdtpDesde := TDateTimePicker.Create(Self);
    FdtpDesde.Tag := 999;
    FdtpDesde.Parent := pnlSearch;
    FdtpDesde.Format := 'dd/MM/yyyy';
    FdtpDesde.Date := Date - 365;
    FdtpDesde.Left := LOffsetLeft;
    FdtpDesde.Top := edtSearch.Top;
    FdtpDesde.Width := 90;
    FdtpDesde.Height := edtSearch.Height;
    FdtpDesde.Enabled := False;
    FdtpDesde.OnChange := FiltroFechasChange;
    LOffsetLeft := LOffsetLeft + FdtpDesde.Width + 6;
  end;

  if not Assigned(FlblHasta) then
  begin
    FlblHasta := TLabel.Create(Self);
    FlblHasta.Tag := 999;
    FlblHasta.Parent := pnlSearch;
    FlblHasta.Caption := 'a';
    FlblHasta.Left := LOffsetLeft;
    FlblHasta.Top := edtSearch.Top + 3;
    LOffsetLeft := LOffsetLeft + FlblHasta.Width + 6;
  end;

  if not Assigned(FdtpHasta) then
  begin
    FdtpHasta := TDateTimePicker.Create(Self);
    FdtpHasta.Tag := 999;
    FdtpHasta.Parent := pnlSearch;
    FdtpHasta.Format := 'dd/MM/yyyy';
    FdtpHasta.Date := Date;
    FdtpHasta.Left := LOffsetLeft;
    FdtpHasta.Top := edtSearch.Top;
    FdtpHasta.Width := 90;
    FdtpHasta.Height := edtSearch.Height;
    FdtpHasta.Enabled := False;
    FdtpHasta.OnChange := FiltroFechasChange;
    LOffsetLeft := LOffsetLeft + FdtpHasta.Width + 14;
  end;

  // 3. Etiqueta de contexto y botón de limpiar contexto
  if (FIdArticulo > 0) or (FIdCliente > 0) or (FIdGrupo > 0) then
  begin
    if not Assigned(FlblContexto) then
    begin
      FlblContexto := TLabel.Create(Self);
      FlblContexto.Tag := 999;
      FlblContexto.Parent := pnlSearch;
      FlblContexto.Font.Style := [fsBold];
      FlblContexto.Font.Color := clNavy;
      FlblContexto.Left := LOffsetLeft;
      FlblContexto.Top := edtSearch.Top + 3;
      FlblContexto.Caption := 'Filtro fijado';
      LOffsetLeft := LOffsetLeft + FlblContexto.Width + 8;
    end;

    if not Assigned(FbtnLimpiarContexto) then
    begin
      FbtnLimpiarContexto := TSpeedButton.Create(Self);
      FbtnLimpiarContexto.Tag := 999;
      FbtnLimpiarContexto.Parent := pnlSearch;
      FbtnLimpiarContexto.Caption := 'Ver Todo';
      FbtnLimpiarContexto.Left := LOffsetLeft;
      FbtnLimpiarContexto.Top := edtSearch.Top;
      FbtnLimpiarContexto.Width := 65;
      FbtnLimpiarContexto.Height := edtSearch.Height;
      FbtnLimpiarContexto.OnClick := btnLimpiarContextoClick;
    end;
  end;

  dbGridMain.OnDrawColumnCell := dbGridCustomDrawColumnCell;

  inherited;
end;

procedure TfrmVentasPreciosHistorico.FormDestroy(Sender: TObject);
begin
  if frmVentasPreciosHistorico = Self then
    frmVentasPreciosHistorico := nil;
end;

procedure TfrmVentasPreciosHistorico.cbbFiltroTipoChange(Sender: TObject);
begin
  btnRefreshClick(Self);
end;

procedure TfrmVentasPreciosHistorico.FiltroFechasChange(Sender: TObject);
begin
  if Assigned(FdtpDesde) and Assigned(FdtpHasta) and Assigned(FchkFiltrarFechas) then
  begin
    FdtpDesde.Enabled := FchkFiltrarFechas.Checked;
    FdtpHasta.Enabled := FchkFiltrarFechas.Checked;
  end;
  btnRefreshClick(Self);
end;

procedure TfrmVentasPreciosHistorico.btnCerrarClick(Sender: TObject);
begin
  if (Parent is TTabSheet) then
    TTabSheet(Parent).Free
  else
    Close;
end;

procedure TfrmVentasPreciosHistorico.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_ESCAPE then
  begin
    Key := 0;
    btnCerrarClick(Self);
  end;
end;

procedure TfrmVentasPreciosHistorico.btnLimpiarContextoClick(Sender: TObject);
begin
  FIdArticulo := 0;
  FIdCliente := 0;
  FIdGrupo := 0;
  FOrigenTarifa := '';
  if Assigned(FcbbFiltroTipo) then
    FcbbFiltroTipo.ItemIndex := 0;
  if Assigned(FlblContexto) then
    FlblContexto.Visible := False;
  if Assigned(FbtnLimpiarContexto) then
    FbtnLimpiarContexto.Visible := False;
  Caption := 'Histórico de Precios y Tarifas de Venta';
  btnRefreshClick(Self);
end;

procedure TfrmVentasPreciosHistorico.btnRefreshClick(Sender: TObject);
var
  LSql: string;
  LSearch: string;
begin
  LSearch := Trim(edtSearch.Text);
  FQryMain.Close;

  LSql :=
    'SELECT ' +
    '  h.id, ' +
    '  h.created_at, ' +
    '  h.origen_tarifa, ' +
    '  h.tarifa_codigo, ' +
    '  h.id_articulo, ' +
    '  COALESCE(a.descripcion, CONCAT(''Art. #'', h.id_articulo)) AS articulo_desc, ' +
    '  h.id_cliente, ' +
    '  c.nombre_fiscal AS cliente_nombre, ' +
    '  h.id_cliente_grupo, ' +
    '  cg.nombre AS grupo_nombre, ' +
    '  CASE ' +
    '    WHEN h.origen_tarifa = ''CLIENTE'' THEN COALESCE(c.nombre_fiscal, CONCAT(''Cliente #'', h.id_cliente)) ' +
    '    WHEN h.origen_tarifa = ''GRUPO_CLIENTES'' THEN COALESCE(cg.nombre, CONCAT(''Grupo #'', h.id_cliente_grupo)) ' +
    '    ELSE ''Venta al Público (PVP)'' ' +
    '  END AS destinatario, ' +
    '  h.precio_anterior, ' +
    '  h.precio_nuevo, ' +
    '  h.variacion_importe, ' +
    '  h.variacion_porc, ' +
    '  h.valido_desde, ' +
    '  h.valido_hasta, ' +
    '  h.und_min, ' +
    '  h.und_max, ' +
    '  h.motivo, ' +
    '  h.origen_evento, ' +
    '  COALESCE(u.nombre_completo, u.username, ''Sistema'') AS usuario_nombre ' +
    'FROM ge_ventas_precios_historico h ' +
    'LEFT JOIN ge_articulos a ON h.id_articulo = a.id ' +
    'LEFT JOIN ge_clientes c ON h.id_cliente = c.id ' +
    'LEFT JOIN ge_clientes_grupos cg ON h.id_cliente_grupo = cg.id ' +
    'LEFT JOIN ge_usuarios u ON h.id_user_creator = u.id ' +
    'WHERE (1 = 1) ';

  // Filtro por tipo de origen
  if Assigned(FcbbFiltroTipo) and (FcbbFiltroTipo.ItemIndex > 0) then
  begin
    case FcbbFiltroTipo.ItemIndex of
      1: LSql := LSql + 'AND h.origen_tarifa = ''PVP_ARTICULO'' ';
      2: LSql := LSql + 'AND h.origen_tarifa = ''CLIENTE'' ';
      3: LSql := LSql + 'AND h.origen_tarifa = ''GRUPO_CLIENTES'' ';
    end;
  end
  else if FOrigenTarifa <> '' then
  begin
    LSql := LSql + 'AND h.origen_tarifa = :origen_tarifa ';
  end;

  // Filtros contextuales
  if FIdArticulo > 0 then
    LSql := LSql + 'AND h.id_articulo = :id_articulo ';

  if FIdCliente > 0 then
    LSql := LSql + 'AND h.id_cliente = :id_cliente ';

  if FIdGrupo > 0 then
    LSql := LSql + 'AND h.id_cliente_grupo = :id_grupo ';

  // Filtro por rango de fechas
  if Assigned(FchkFiltrarFechas) and FchkFiltrarFechas.Checked then
    LSql := LSql + 'AND DATE(h.created_at) >= :fecha_desde AND DATE(h.created_at) <= :fecha_hasta ';

  // Búsqueda textual
  if LSearch <> '' then
  begin
    LSql := LSql +
      'AND (a.descripcion LIKE :search ' +
      '     OR CAST(h.id_articulo AS CHAR) LIKE :search ' +
      '     OR c.nombre_fiscal LIKE :search ' +
      '     OR cg.nombre LIKE :search ' +
      '     OR h.motivo LIKE :search ' +
      '     OR u.username LIKE :search ' +
      '     OR u.nombre_completo LIKE :search) ';
  end;

  LSql := LSql + 'ORDER BY h.created_at DESC, h.id DESC';

  FQryMain.SQL.Text := LSql;

  // Asignar parámetros con comprobación estricta y DataType seguro
  if FQryMain.FindParam('origen_tarifa') <> nil then
  begin
    FQryMain.ParamByName('origen_tarifa').DataType := ftWideString;
    FQryMain.ParamByName('origen_tarifa').AsWideString := FOrigenTarifa;
  end;

  if (FIdArticulo > 0) and (FQryMain.FindParam('id_articulo') <> nil) then
    FQryMain.ParamByName('id_articulo').AsInteger := FIdArticulo;

  if (FIdCliente > 0) and (FQryMain.FindParam('id_cliente') <> nil) then
    FQryMain.ParamByName('id_cliente').AsInteger := FIdCliente;

  if (FIdGrupo > 0) and (FQryMain.FindParam('id_grupo') <> nil) then
    FQryMain.ParamByName('id_grupo').AsInteger := FIdGrupo;

  if Assigned(FchkFiltrarFechas) and FchkFiltrarFechas.Checked then
  begin
    if (FQryMain.FindParam('fecha_desde') <> nil) and Assigned(FdtpDesde) then
      FQryMain.ParamByName('fecha_desde').AsDate := FdtpDesde.Date;
    if (FQryMain.FindParam('fecha_hasta') <> nil) and Assigned(FdtpHasta) then
      FQryMain.ParamByName('fecha_hasta').AsDate := FdtpHasta.Date;
  end;

  if (LSearch <> '') and (FQryMain.FindParam('search') <> nil) then
  begin
    FQryMain.ParamByName('search').DataType := ftWideString;
    FQryMain.ParamByName('search').AsWideString := '%' + LSearch + '%';
  end;

  FQryMain.Open;
  FormatNumericFields(FQryMain);
  ConfigureColumns;
end;

procedure TfrmVentasPreciosHistorico.FormatNumericFields(DataSet: TDataSet);
var
  Fld: TField;
begin
  Fld := DataSet.FindField('precio_anterior');
  if Fld is TNumericField then
    TNumericField(Fld).DisplayFormat := '#,##0.00';

  Fld := DataSet.FindField('precio_nuevo');
  if Fld is TNumericField then
    TNumericField(Fld).DisplayFormat := '#,##0.00';

  Fld := DataSet.FindField('variacion_importe');
  if Fld is TNumericField then
    TNumericField(Fld).DisplayFormat := '+#,##0.00;-#,##0.00;0.00';

  Fld := DataSet.FindField('variacion_porc');
  if Fld is TNumericField then
    TNumericField(Fld).DisplayFormat := '+#,##0.00;-#,##0.00;0.00';

  Fld := DataSet.FindField('created_at');
  if Fld is TDateTimeField then
    TDateTimeField(Fld).DisplayFormat := 'dd/mm/yyyy hh:nn';

  Fld := DataSet.FindField('valido_desde');
  if Fld is TDateField then
    TDateField(Fld).DisplayFormat := 'dd/mm/yyyy';

  Fld := DataSet.FindField('valido_hasta');
  if Fld is TDateField then
    TDateField(Fld).DisplayFormat := 'dd/mm/yyyy';
end;

procedure TfrmVentasPreciosHistorico.ConfigureColumns;
begin
  dbGridMain.Columns.Clear;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'created_at';
    Title.Caption := 'Fecha/Hora';
    Width := 115;
  end;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'origen_tarifa';
    Title.Caption := 'Ámbito';
    Title.Alignment := taCenter;
    Alignment := taCenter;
    Width := 95;
  end;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'tarifa_codigo';
    Title.Caption := 'Tarifa';
    Title.Alignment := taCenter;
    Alignment := taCenter;
    Width := 60;
  end;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'id_articulo';
    Title.Caption := 'Ref.';
    Title.Alignment := taCenter;
    Alignment := taCenter;
    Width := 55;
  end;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'articulo_desc';
    Title.Caption := 'Artículo / Producto';
    Width := 210;
  end;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'destinatario';
    Title.Caption := 'Destinatario (Cliente / Grupo / PVP)';
    Width := 200;
  end;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'precio_anterior';
    Title.Caption := 'P. Ant. (€)';
    Title.Alignment := taRightJustify;
    Alignment := taRightJustify;
    Width := 80;
  end;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'precio_nuevo';
    Title.Caption := 'P. Nuevo (€)';
    Title.Alignment := taRightJustify;
    Alignment := taRightJustify;
    Width := 85;
  end;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'variacion_importe';
    Title.Caption := 'Dif. (€)';
    Title.Alignment := taRightJustify;
    Alignment := taRightJustify;
    Width := 75;
  end;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'variacion_porc';
    Title.Caption := '% Var.';
    Title.Alignment := taRightJustify;
    Alignment := taRightJustify;
    Width := 65;
  end;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'valido_desde';
    Title.Caption := 'Val. Desde';
    Title.Alignment := taCenter;
    Alignment := taCenter;
    Width := 75;
  end;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'valido_hasta';
    Title.Caption := 'Val. Hasta';
    Title.Alignment := taCenter;
    Alignment := taCenter;
    Width := 75;
  end;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'motivo';
    Title.Caption := 'Motivo / Origen';
    Width := 140;
  end;

  with dbGridMain.Columns.Add do
  begin
    FieldName := 'usuario_nombre';
    Title.Caption := 'Usuario';
    Width := 95;
  end;
end;

procedure TfrmVentasPreciosHistorico.dbGridCustomDrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
  LGrid: TDBGrid;
  LVarImp: Double;
  LFieldName: string;
begin
  LGrid := Sender as TDBGrid;
  LFieldName := LowerCase(Column.FieldName);

  // Destacar variaciones de precio
  if (LFieldName = 'variacion_importe') or (LFieldName = 'variacion_porc') then
  begin
    if Assigned(Column.Field) and not Column.Field.IsNull then
    begin
      LVarImp := Column.Field.AsFloat;
      if not (gdSelected in State) then
      begin
        if LVarImp > 0.0001 then
        begin
          LGrid.Canvas.Font.Color := RGB(0, 130, 40); // Verde para subida de precio
          LGrid.Canvas.Font.Style := [fsBold];
        end
        else if LVarImp < -0.0001 then
        begin
          LGrid.Canvas.Font.Color := RGB(190, 20, 20); // Rojo para bajada de precio
          LGrid.Canvas.Font.Style := [fsBold];
        end;
      end;
    end;
  end;

  LGrid.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

end.
