unit frm_PedidosArticulosAcumulados;

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.Buttons, Vcl.Grids, Vcl.DBGrids, Data.DB, FireDAC.Comp.Client,
  FireDAC.Stan.Param, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.DatS,
  FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, uAppTheme, System.UITypes,
  System.Generics.Collections, frxClass, frxDBSet, frm_PrintOptions,
  uFormatosImpresionService;

type
  TfrmPedidosArticulosAcumulados = class(TForm)
    pnlHeader: TPanel;
    lblTitle: TLabel;
    lblSubtitle: TLabel;
    pnlKpiContainer: TPanel;
    pnlKpiPedidos: TPanel;
    lblKpiPedidosVal: TLabel;
    lblKpiPedidosLbl: TLabel;
    pnlKpiArticulos: TPanel;
    lblKpiArticulosVal: TLabel;
    lblKpiArticulosLbl: TLabel;
    pnlKpiUnidades: TPanel;
    lblKpiUnidadesVal: TLabel;
    lblKpiUnidadesLbl: TLabel;
    pnlKpiBultos: TPanel;
    lblKpiBultosVal: TLabel;
    lblKpiBultosLbl: TLabel;
    pnlKpiPalets: TPanel;
    lblKpiPaletsVal: TLabel;
    lblKpiPaletsLbl: TLabel;

    pnlFilter: TPanel;
    lblBuscar: TLabel;
    edtBuscar: TEdit;
    lblFamilia: TLabel;
    cbbFamilia: TComboBox;
    btnLimpiarFiltro: TBitBtn;

    pnlBody: TPanel;
    pnlMaster: TPanel;
    dbgArticulos: TDBGrid;
    splDetail: TSplitter;

    pnlDetail: TPanel;
    pnlDetailHeader: TPanel;
    lblDetailTitle: TLabel;
    dbgDetallePedidos: TDBGrid;

    pnlFooter: TPanel;
    btnImprimir: TBitBtn;
    btnExportarExcel: TBitBtn;
    btnCerrar: TBitBtn;

    qAcumulados: TFDQuery;
    dsAcumulados: TDataSource;
    qDetallePedidos: TFDQuery;
    dsDetallePedidos: TDataSource;
    frxDBAcumulados: TfrxDBDataset;

    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure FormResize(Sender: TObject);
    procedure edtBuscarChange(Sender: TObject);
    procedure cbbFamiliaChange(Sender: TObject);
    procedure btnLimpiarFiltroClick(Sender: TObject);
    procedure btnImprimirClick(Sender: TObject);
    procedure btnExportarExcelClick(Sender: TObject);
    procedure btnCerrarClick(Sender: TObject);
    procedure qAcumuladosAfterScroll(DataSet: TDataSet);
    procedure dbgArticulosDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure dbgArticulosTitleClick(Column: TColumn);
    procedure dbgDetallePedidosDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure dbgDetallePedidosDblClick(Sender: TObject);
  private
    FPedidoIds: TArray<Integer>;
    FPedidoIdsStr: string;
    FModoDescripcion: string;
    FFiltroEnProceso: Boolean;
    FTotPedidos: Integer;
    FTotArticulos: Integer;
    FTotUnidades: Double;
    FTotBultos: Double;
    FTotPalets: Double;
    procedure ConfigurarGrids;
    procedure CargarDatos;
    procedure CargarComboFamilias;
    procedure AplicarFiltroCliente;
    procedure RecalcularKPIs;
    procedure RefrescarDetalle;
  public
    class procedure MostrarAcumulado(AOwner: TComponent; const APedidoIds: TArray<Integer>;
      const AModoDescripcion: string = '');
  end;

var
  frmPedidosArticulosAcumulados: TfrmPedidosArticulosAcumulados;

implementation

uses
  dmg_Main, frm_PedidosEditor;

{$R *.dfm}

{ TfrmPedidosArticulosAcumulados }

class procedure TfrmPedidosArticulosAcumulados.MostrarAcumulado(AOwner: TComponent;
  const APedidoIds: TArray<Integer>; const AModoDescripcion: string);
var
  LFrm: TfrmPedidosArticulosAcumulados;
begin
  if Length(APedidoIds) = 0 then
  begin
    ShowMessage('No se han especificado pedidos para calcular los artículos acumulados.');
    Exit;
  end;

  LFrm := TfrmPedidosArticulosAcumulados.Create(AOwner);
  try
    LFrm.FPedidoIds := APedidoIds;
    LFrm.FModoDescripcion := AModoDescripcion;
    LFrm.ShowModal;
  finally
    LFrm.Free;
  end;
end;

procedure TfrmPedidosArticulosAcumulados.FormCreate(Sender: TObject);
begin
  TAppTheme.ApplyToForm(Self);
  pnlHeader.Color := TAppTheme.COLOR_HEADER_BLACK;
  pnlKpiContainer.Color := TAppTheme.COLOR_HEADER_BLACK;
  lblDetailTitle.Font.Color := TAppTheme.COLOR_DARK_RED;

  pnlKpiPedidos.Color := RGB(45, 52, 64);
  pnlKpiArticulos.Color := RGB(45, 52, 64);
  pnlKpiUnidades.Color := RGB(45, 52, 64);
  pnlKpiBultos.Color := RGB(45, 52, 64);
  pnlKpiPalets.Color := RGB(45, 52, 64);

  qAcumulados.Connection := dmgMain.dbConn;
  qDetallePedidos.Connection := dmgMain.dbConn;

  ConfigurarGrids;
end;

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

procedure TfrmPedidosArticulosAcumulados.FormShow(Sender: TObject);
begin
  if FModoDescripcion <> '' then
    lblSubtitle.Caption := FModoDescripcion
  else
    lblSubtitle.Caption := Format('Artículos acumulados de %d pedido(s)', [Length(FPedidoIds)]);

  CargarDatos;
  FormResize(nil);
end;

procedure TfrmPedidosArticulosAcumulados.FormResize(Sender: TObject);
var
  LAvailableWidth: Integer;
begin
  if dbgArticulos.Columns.Count >= 8 then
  begin
    // Ajustar proporcionalmente la columna de descripción
    LAvailableWidth := dbgArticulos.ClientWidth - (70 + 110 + 130 + 75 + 75 + 70 + 95 + 30);
    if LAvailableWidth > 200 then
      dbgArticulos.Columns[2].Width := LAvailableWidth;
  end;

  if dbgDetallePedidos.Columns.Count >= 8 then
  begin
    LAvailableWidth := dbgDetallePedidos.ClientWidth - (105 + 90 + 90 + 160 + 65 + 65 + 85 + 30);
    if LAvailableWidth > 180 then
      dbgDetallePedidos.Columns[3].Width := LAvailableWidth;
  end;
end;

procedure TfrmPedidosArticulosAcumulados.ConfigurarGrids;
begin
  // Grid de Artículos Acumulados
  dbgArticulos.Columns.Clear;

  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'codigo';
    Title.Caption := 'Código';
    Width := 70;
    Alignment := taCenter;
    Title.Alignment := taCenter;
  end;

  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'ean';
    Title.Caption := 'EAN / Código Barras';
    Width := 115;
    Alignment := taCenter;
    Title.Alignment := taCenter;
  end;

  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'descripcion';
    Title.Caption := 'Artículo / Descripción';
    Width := 320;
  end;

  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'familia';
    Title.Caption := 'Familia';
    Width := 130;
  end;

  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'num_pedidos';
    Title.Caption := 'Nº Pedidos';
    Width := 75;
    Alignment := taRightJustify;
    Title.Alignment := taRightJustify;
  end;

  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'total_bultos';
    Title.Caption := 'Total Bultos';
    Width := 75;
    Alignment := taRightJustify;
    Title.Alignment := taRightJustify;
  end;

  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'total_palets';
    Title.Caption := 'Total Palets';
    Width := 70;
    Alignment := taRightJustify;
    Title.Alignment := taRightJustify;
  end;

  with dbgArticulos.Columns.Add do
  begin
    FieldName := 'total_unidades';
    Title.Caption := 'Total Unidades';
    Width := 95;
    Alignment := taRightJustify;
    Title.Alignment := taRightJustify;
  end;

  // Grid de Detalle de Pedidos
  dbgDetallePedidos.Columns.Clear;

  with dbgDetallePedidos.Columns.Add do
  begin
    FieldName := 'numero_pedido';
    Title.Caption := 'Nº Pedido';
    Width := 105;
  end;

  with dbgDetallePedidos.Columns.Add do
  begin
    FieldName := 'fecha_pedido';
    Title.Caption := 'Fecha Pedido';
    Width := 90;
    Alignment := taCenter;
    Title.Alignment := taCenter;
  end;

  with dbgDetallePedidos.Columns.Add do
  begin
    FieldName := 'fecha_entrega';
    Title.Caption := 'Fecha Entrega';
    Width := 90;
    Alignment := taCenter;
    Title.Alignment := taCenter;
  end;

  with dbgDetallePedidos.Columns.Add do
  begin
    FieldName := 'cliente_nombre';
    Title.Caption := 'Cliente';
    Width := 220;
  end;

  with dbgDetallePedidos.Columns.Add do
  begin
    FieldName := 'destino_nombre';
    Title.Caption := 'Destino / Entrega';
    Width := 160;
  end;

  with dbgDetallePedidos.Columns.Add do
  begin
    FieldName := 'bultos';
    Title.Caption := 'Bultos';
    Width := 65;
    Alignment := taRightJustify;
    Title.Alignment := taRightJustify;
  end;

  with dbgDetallePedidos.Columns.Add do
  begin
    FieldName := 'palets';
    Title.Caption := 'Palets';
    Width := 65;
    Alignment := taRightJustify;
    Title.Alignment := taRightJustify;
  end;

  with dbgDetallePedidos.Columns.Add do
  begin
    FieldName := 'cantidad';
    Title.Caption := 'Unidades';
    Width := 85;
    Alignment := taRightJustify;
    Title.Alignment := taRightJustify;
  end;
end;

procedure TfrmPedidosArticulosAcumulados.CargarDatos;
var
  LSb: TStringBuilder;
  I: Integer;
  LSql: string;
begin
  if Length(FPedidoIds) = 0 then Exit;

  Screen.Cursor := crHourGlass;
  try
    LSb := TStringBuilder.Create;
    try
      for I := 0 to High(FPedidoIds) do
      begin
        if I > 0 then
          LSb.Append(',');
        LSb.Append(IntToStr(FPedidoIds[I]));
      end;
      FPedidoIdsStr := LSb.ToString;
    finally
      LSb.Free;
    end;

    qAcumulados.Close;
    LSql :=
      'SELECT ' +
      '  COALESCE(pl.id_articulo, 0) AS id_articulo, ' +
      '  COALESCE(NULLIF(a.id, 0), pl.id_articulo, 0) AS codigo, ' +
      '  COALESCE(NULLIF(TRIM(a.descripcion), ''''), TRIM(pl.descripcion)) AS descripcion, ' +
      '  COALESCE(NULLIF(TRIM(a.ean), ''''), NULLIF(TRIM(pl.ean_producto), ''''), '''') AS ean, ' +
      '  COALESCE(NULLIF(TRIM(fam.descripcion), ''''), ''Sin Familia'') AS familia, ' +
      '  SUM(pl.cantidad) AS total_unidades, ' +
      '  SUM(COALESCE(pl.bultos, 0)) AS total_bultos, ' +
      '  SUM(COALESCE(pl.numero_palets, 0)) AS total_palets, ' +
      '  COUNT(DISTINCT pl.id_pedido) AS num_pedidos ' +
      'FROM ge_pedidos_lineas pl ' +
      'JOIN ge_pedidos p ON pl.id_pedido = p.id ' +
      'LEFT JOIN ge_articulos a ON pl.id_articulo = a.id ' +
      'LEFT JOIN ge_familias fam ON a.id_familia = fam.id ' +
      'WHERE pl.id_pedido IN (' + FPedidoIdsStr + ') ' +
      'GROUP BY pl.id_articulo, codigo, descripcion, ean, familia ' +
      'ORDER BY familia ASC, descripcion ASC';

    qAcumulados.SQL.Text := LSql;
    qAcumulados.Open;

    // Configurar formatos de visualización en los campos
    if qAcumulados.FindField('total_unidades') is TNumericField then
      TNumericField(qAcumulados.FieldByName('total_unidades')).DisplayFormat := '#,##0.##';

    if qAcumulados.FindField('total_bultos') is TNumericField then
      TNumericField(qAcumulados.FieldByName('total_bultos')).DisplayFormat := '#,##0';

    if qAcumulados.FindField('total_palets') is TNumericField then
      TNumericField(qAcumulados.FieldByName('total_palets')).DisplayFormat := '#,##0';

    if qAcumulados.FindField('num_pedidos') is TNumericField then
      TNumericField(qAcumulados.FieldByName('num_pedidos')).DisplayFormat := '#,##0';

    CargarComboFamilias;
    RecalcularKPIs;
    RefrescarDetalle;
  finally
    Screen.Cursor := crDefault;
  end;
end;

procedure TfrmPedidosArticulosAcumulados.CargarComboFamilias;
var
  LBookmark: TBookmark;
  LFam: string;
  LList: TStringList;
begin
  cbbFamilia.Items.Clear;
  cbbFamilia.Items.Add('(Todas las Familias)');

  if qAcumulados.IsEmpty then
  begin
    cbbFamilia.ItemIndex := 0;
    Exit;
  end;

  LList := TStringList.Create;
  try
    LList.Duplicates := dupIgnore;
    LList.Sorted := True;

    qAcumulados.DisableControls;
    LBookmark := qAcumulados.GetBookmark;
    try
      qAcumulados.First;
      while not qAcumulados.Eof do
      begin
        LFam := Trim(qAcumulados.FieldByName('familia').AsString);
        if LFam <> '' then
          LList.Add(LFam);
        qAcumulados.Next;
      end;
    finally
      if qAcumulados.BookmarkValid(LBookmark) then
        qAcumulados.GotoBookmark(LBookmark);
      qAcumulados.FreeBookmark(LBookmark);
      qAcumulados.EnableControls;
    end;

    cbbFamilia.Items.AddStrings(LList);
  finally
    LList.Free;
  end;

  cbbFamilia.ItemIndex := 0;
end;

procedure TfrmPedidosArticulosAcumulados.edtBuscarChange(Sender: TObject);
begin
  AplicarFiltroCliente;
end;

procedure TfrmPedidosArticulosAcumulados.cbbFamiliaChange(Sender: TObject);
begin
  AplicarFiltroCliente;
end;

procedure TfrmPedidosArticulosAcumulados.btnLimpiarFiltroClick(Sender: TObject);
begin
  edtBuscar.Text := '';
  cbbFamilia.ItemIndex := 0;
  AplicarFiltroCliente;
end;

procedure TfrmPedidosArticulosAcumulados.AplicarFiltroCliente;
var
  LSearch: string;
  LFamilia: string;
  LFilterExpr: string;
  LParts: TList<string>;
  I: Integer;
begin
  if FFiltroEnProceso or not qAcumulados.Active then Exit;

  FFiltroEnProceso := True;
  try
    LSearch := Trim(edtBuscar.Text);
    LFamilia := '';
    if (cbbFamilia.ItemIndex > 0) then
      LFamilia := cbbFamilia.Items[cbbFamilia.ItemIndex];

    LParts := TList<string>.Create;
    try
      if LSearch <> '' then
      begin
        // Escapar comillas simples
        LSearch := StringReplace(LSearch, '''', '''''', [rfReplaceAll]);
        LParts.Add(Format(
          '(descripcion LIKE ''%%%s%%'' OR ean LIKE ''%%%s%%'' OR Convert(codigo, ''System.String'') LIKE ''%%%s%%'')',
          [LSearch, LSearch, LSearch]
        ));
      end;

      if LFamilia <> '' then
      begin
        LFamilia := StringReplace(LFamilia, '''', '''''', [rfReplaceAll]);
        LParts.Add(Format('familia = ''%s''', [LFamilia]));
      end;

      if LParts.Count > 0 then
      begin
        LFilterExpr := LParts[0];
        for I := 1 to LParts.Count - 1 do
          LFilterExpr := LFilterExpr + ' AND ' + LParts[I];

        qAcumulados.Filter := LFilterExpr;
        qAcumulados.Filtered := True;
      end
      else
      begin
        qAcumulados.Filter := '';
        qAcumulados.Filtered := False;
      end;
    finally
      LParts.Free;
    end;

    RecalcularKPIs;
    RefrescarDetalle;
  finally
    FFiltroEnProceso := False;
  end;
end;

procedure TfrmPedidosArticulosAcumulados.RecalcularKPIs;
var
  LBookmark: TBookmark;
begin
  FTotPedidos := Length(FPedidoIds);
  FTotArticulos := 0;
  FTotUnidades := 0;
  FTotBultos := 0;
  FTotPalets := 0;

  if qAcumulados.Active and not qAcumulados.IsEmpty then
  begin
    qAcumulados.DisableControls;
    LBookmark := qAcumulados.GetBookmark;
    try
      qAcumulados.First;
      while not qAcumulados.Eof do
      begin
        Inc(FTotArticulos);
        FTotUnidades := FTotUnidades + qAcumulados.FieldByName('total_unidades').AsFloat;
        FTotBultos := FTotBultos + qAcumulados.FieldByName('total_bultos').AsFloat;
        FTotPalets := FTotPalets + qAcumulados.FieldByName('total_palets').AsFloat;
        qAcumulados.Next;
      end;
    finally
      if qAcumulados.BookmarkValid(LBookmark) then
        qAcumulados.GotoBookmark(LBookmark);
      qAcumulados.FreeBookmark(LBookmark);
      qAcumulados.EnableControls;
    end;
  end;

  lblKpiPedidosVal.Caption := FormatFloat('#,##0', FTotPedidos);
  lblKpiArticulosVal.Caption := FormatFloat('#,##0', FTotArticulos);
  lblKpiUnidadesVal.Caption := FormatFloat('#,##0.##', FTotUnidades);
  lblKpiBultosVal.Caption := FormatFloat('#,##0', FTotBultos);
  lblKpiPaletsVal.Caption := FormatFloat('#,##0', FTotPalets);

  pnlKpiPalets.Visible := (FTotPalets > 0);
end;

procedure TfrmPedidosArticulosAcumulados.qAcumuladosAfterScroll(DataSet: TDataSet);
begin
  if not FFiltroEnProceso then
    RefrescarDetalle;
end;

procedure TfrmPedidosArticulosAcumulados.RefrescarDetalle;
var
  LArtId: Integer;
  LDesc: string;
  LSql: string;
begin
  if not qAcumulados.Active or qAcumulados.IsEmpty then
  begin
    qDetallePedidos.Close;
    lblDetailTitle.Caption := 'Desglose de pedidos: No hay ningún artículo seleccionado.';
    Exit;
  end;

  LArtId := qAcumulados.FieldByName('id_articulo').AsInteger;
  LDesc := qAcumulados.FieldByName('descripcion').AsString;

  lblDetailTitle.Caption := Format(
    'Desglose de pedidos con el artículo: %s (Cód. %s | %s)',
    [LDesc, qAcumulados.FieldByName('codigo').AsString, qAcumulados.FieldByName('familia').AsString]
  );

  qDetallePedidos.Close;
  LSql :=
    'SELECT ' +
    '  p.id AS pedido_id, ' +
    '  p.numero_pedido, ' +
    '  p.fecha_pedido, ' +
    '  p.fecha_entrega, ' +
    '  p.estado, ' +
    '  COALESCE(NULLIF(c.nombre_comercial, ''''), c.nombre_fiscal) AS cliente_nombre, ' +
    '  COALESCE(d.descripcion, ''—'') AS destino_nombre, ' +
    '  pl.cantidad, ' +
    '  COALESCE(pl.bultos, 0) AS bultos, ' +
    '  COALESCE(pl.numero_palets, 0) AS palets ' +
    'FROM ge_pedidos_lineas pl ' +
    'JOIN ge_pedidos p ON pl.id_pedido = p.id ' +
    'JOIN ge_clientes c ON p.cliente_id = c.id ' +
    'LEFT JOIN ge_clientes_destinos d ON p.clientedestino_id = d.id ' +
    'WHERE pl.id_pedido IN (' + FPedidoIdsStr + ') ';

  if LArtId > 0 then
    LSql := LSql + 'AND pl.id_articulo = :art_id '
  else
    LSql := LSql + 'AND pl.descripcion = :desc ';

  LSql := LSql + 'ORDER BY p.fecha_entrega ASC, p.numero_pedido ASC';

  qDetallePedidos.SQL.Text := LSql;
  if LArtId > 0 then
    qDetallePedidos.ParamByName('art_id').AsInteger := LArtId
  else
    qDetallePedidos.ParamByName('desc').AsString := LDesc;

  qDetallePedidos.Open;

  if qDetallePedidos.FindField('cantidad') is TNumericField then
    TNumericField(qDetallePedidos.FieldByName('cantidad')).DisplayFormat := '#,##0.##';

  if qDetallePedidos.FindField('bultos') is TNumericField then
    TNumericField(qDetallePedidos.FieldByName('bultos')).DisplayFormat := '#,##0';

  if qDetallePedidos.FindField('palets') is TNumericField then
    TNumericField(qDetallePedidos.FieldByName('palets')).DisplayFormat := '#,##0';
end;

procedure TfrmPedidosArticulosAcumulados.dbgArticulosDrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
  LGrid: TDBGrid;
begin
  LGrid := Sender as TDBGrid;

  if not (gdSelected in State) then
  begin
    if Odd(LGrid.DataSource.DataSet.RecNo) then
      LGrid.Canvas.Brush.Color := clWhite
    else
      LGrid.Canvas.Brush.Color := RGB(248, 249, 251);
  end
  else
  begin
    LGrid.Canvas.Brush.Color := RGB(218, 232, 252);
    LGrid.Canvas.Font.Color := clBlack;
  end;

  if (Column.FieldName = 'total_unidades') or (Column.FieldName = 'total_bultos') then
    LGrid.Canvas.Font.Style := [fsBold];

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

procedure TfrmPedidosArticulosAcumulados.dbgArticulosTitleClick(Column: TColumn);
begin
  if (qAcumulados is TFDQuery) and qAcumulados.Active then
  begin
    if qAcumulados.IndexFieldNames = Column.FieldName then
      qAcumulados.IndexFieldNames := Column.FieldName + ':D'
    else
      qAcumulados.IndexFieldNames := Column.FieldName;
  end;
end;

procedure TfrmPedidosArticulosAcumulados.dbgDetallePedidosDrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
  LGrid: TDBGrid;
begin
  LGrid := Sender as TDBGrid;

  if not (gdSelected in State) then
  begin
    if Odd(LGrid.DataSource.DataSet.RecNo) then
      LGrid.Canvas.Brush.Color := clWhite
    else
      LGrid.Canvas.Brush.Color := RGB(248, 249, 251);
  end
  else
  begin
    LGrid.Canvas.Brush.Color := RGB(218, 232, 252);
    LGrid.Canvas.Font.Color := clBlack;
  end;

  if Column.FieldName = 'cantidad' then
    LGrid.Canvas.Font.Style := [fsBold];

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

procedure TfrmPedidosArticulosAcumulados.dbgDetallePedidosDblClick(Sender: TObject);
var
  LPedidoIdStr: string;
begin
  if not qDetallePedidos.Active or qDetallePedidos.IsEmpty then Exit;

  LPedidoIdStr := qDetallePedidos.FieldByName('pedido_id').AsString;
  if LPedidoIdStr = '' then Exit;

  if not Assigned(frmPedidosEditor) then
    Application.CreateForm(TfrmPedidosEditor, frmPedidosEditor);

  frmPedidosEditor.ParentForm := Self;
  frmPedidosEditor.PedidoId := LPedidoIdStr;
  frmPedidosEditor.ShowModal;
end;

procedure TfrmPedidosArticulosAcumulados.btnImprimirClick(Sender: TObject);
var
  LReportPath: string;
  LComp: TfrxComponent;
  LBookmark: TBookmark;
  LFiltroDesc: string;
begin
  if not qAcumulados.Active or qAcumulados.IsEmpty then
  begin
    ShowMessage('No hay datos acumulados para imprimir.');
    Exit;
  end;

  // 1. Resolver ruta del archivo de informe FastReport
  LReportPath := TFormatosImpresionService.ResolverRutaArchivo('articulos_acumulados_pedidos.fr3');
  if (LReportPath = '') or not FileExists(LReportPath) then
    LReportPath := ExtractFilePath(ParamStr(0)) + 'reportes\articulos_acumulados_pedidos.fr3';
  if not FileExists(LReportPath) then
    LReportPath := 'reportes\articulos_acumulados_pedidos.fr3';

  if FileExists(LReportPath) then
  begin
    frxDBAcumulados.DataSet := qAcumulados;
    frxDBAcumulados.UserName := 'frxDBacumulados';

    dmgMain.frxInforme.Clear;
    dmgMain.frxInforme.PreviewPages.Clear;
    dmgMain.frxInforme.LoadFromFile(LReportPath);

    dmgMain.frxInforme.DataSets.Clear;
    dmgMain.frxInforme.DataSets.Add(frxDBAcumulados);

    dmgMain.frxInforme.EnabledDataSets.Clear;
    dmgMain.frxInforme.EnabledDataSets.Add(frxDBAcumulados);

    LComp := dmgMain.frxInforme.FindObject('MasterData1');
    if (LComp <> nil) and (LComp is TfrxMasterData) then
      TfrxMasterData(LComp).DataSet := frxDBAcumulados;

    LFiltroDesc := lblSubtitle.Caption;
    if qAcumulados.Filtered then
    begin
      if Trim(edtBuscar.Text) <> '' then
        LFiltroDesc := LFiltroDesc + ' [Búsqueda: ' + Trim(edtBuscar.Text) + ']';
      if (cbbFamilia.ItemIndex > 0) then
        LFiltroDesc := LFiltroDesc + ' [Familia: ' + cbbFamilia.Items[cbbFamilia.ItemIndex] + ']';
    end;

    // Asignar variables al informe
    dmgMain.frxInforme.Variables['TituloReporte'] := '''' + 'ARTÍCULOS ACUMULADOS EN PEDIDOS' + '''';
    dmgMain.frxInforme.Variables['FiltroModo'] := '''' + LFiltroDesc + '''';
    dmgMain.frxInforme.Variables['TotalPedidos'] := '''' + FormatFloat('#,##0', FTotPedidos) + '''';
    dmgMain.frxInforme.Variables['TotalArticulos'] := '''' + FormatFloat('#,##0', FTotArticulos) + '''';
    dmgMain.frxInforme.Variables['TotalBultos'] := '''' + FormatFloat('#,##0', FTotBultos) + '''';
    dmgMain.frxInforme.Variables['TotalPalets'] := '''' + FormatFloat('#,##0', FTotPalets) + '''';
    dmgMain.frxInforme.Variables['TotalUnidades'] := '''' + FormatFloat('#,##0.##', FTotUnidades) + '''';
    dmgMain.frxInforme.Variables['FechaHoraEmision'] := '''' + FormatDateTime('dd/mm/yyyy hh:nn', Now) + '''';

    // Asegurar posicionamiento al inicio y regenerar páginas del informe actual
    qAcumulados.DisableControls;
    LBookmark := qAcumulados.GetBookmark;
    try
      qAcumulados.First;
      dmgMain.frxInforme.PrepareReport(True);
    finally
      if qAcumulados.BookmarkValid(LBookmark) then
        qAcumulados.GotoBookmark(LBookmark);
      qAcumulados.FreeBookmark(LBookmark);
      qAcumulados.EnableControls;
    end;

    // Abrir diálogo estándar de opciones de impresión con FastReport habilitado
    TfrmPrintOptions.ShowOptions(
      Self,
      dmgMain.frxInforme,
      dbgArticulos,
      'Articulos_Acumulados_Pedidos_' + FormatDateTime('yyyymmdd_hhnn', Now)
    );
  end
  else
  begin
    // Si no está disponible el fichero .fr3, se ofrece el diálogo directo con exportación
    TfrmPrintOptions.ShowOptions(
      Self,
      nil,
      dbgArticulos,
      'Articulos_Acumulados_Pedidos_' + FormatDateTime('yyyymmdd_hhnn', Now)
    );
  end;
end;

procedure TfrmPedidosArticulosAcumulados.btnExportarExcelClick(Sender: TObject);
begin
  if not qAcumulados.Active or qAcumulados.IsEmpty then
  begin
    ShowMessage('No hay datos para exportar.');
    Exit;
  end;

  TfrmPrintOptions.ShowOptions(
    Self,
    nil,
    dbgArticulos,
    'Articulos_Acumulados_Pedidos_' + FormatDateTime('yyyymmdd_hhnn', Now)
  );
end;

procedure TfrmPedidosArticulosAcumulados.btnCerrarClick(Sender: TObject);
begin
  Close;
end;

end.
