unit frm_InformePlanificacionProduccion;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons,
  Vcl.ExtCtrls, Vcl.Clipbrd, System.UITypes, uAppTheme, frxClass, Vcl.Printers;

type
  TfrmInformePlanificacionProduccion = class(TForm)
    pnlTop: TPanel;
    lblTitle: TLabel;
    lblSubtitle: TLabel;
    pnlBody: TPanel;
    mmoInforme: TMemo;
    pnlFooter: TPanel;
    btnCopiar: TBitBtn;
    btnGuardarArchivo: TBitBtn;
    btnImprimir: TBitBtn;
    btnCerrar: TBitBtn;
    saveDlgTxt: TSaveDialog;
    procedure FormCreate(Sender: TObject);
    procedure btnCopiarClick(Sender: TObject);
    procedure btnGuardarArchivoClick(Sender: TObject);
    procedure btnImprimirClick(Sender: TObject);
    procedure btnCerrarClick(Sender: TObject);
    procedure PrepararReporteFastReport(AReport: TfrxReport; const ATitulo, ASubtitulo, ATexto: string);
  public
    class procedure MostrarInforme(AOwner: TComponent; const ATextoInforme: string;
      const AFecha: TDateTime; const AObrador: string);
  end;

var
  frmInformePlanificacionProduccion: TfrmInformePlanificacionProduccion;

implementation

{$R *.dfm}

uses
  dmg_Main, frm_PrintOptions, System.StrUtils, System.Math;

procedure TfrmInformePlanificacionProduccion.FormCreate(Sender: TObject);
begin
  TAppTheme.ApplyToForm(Self);
end;

class procedure TfrmInformePlanificacionProduccion.MostrarInforme(AOwner: TComponent;
  const ATextoInforme: string; const AFecha: TDateTime; const AObrador: string);
var
  LFrm: TfrmInformePlanificacionProduccion;
begin
  LFrm := TfrmInformePlanificacionProduccion.Create(AOwner);
  try
    LFrm.lblSubtitle.Caption := Format('Fecha de Producción: %s | Obrador: %s | Consolidado de fabricación y materias primas',
      [FormatDateTime('dd/mm/yyyy', AFecha), AObrador]);
    LFrm.mmoInforme.Lines.Text := ATextoInforme;
    LFrm.ShowModal;
  finally
    LFrm.Free;
  end;
end;

procedure TfrmInformePlanificacionProduccion.btnCopiarClick(Sender: TObject);
begin
  Clipboard.AsText := mmoInforme.Lines.Text;
  MessageDlg('Informe copiado al portapapeles con éxito.', mtInformation, [mbOK], 0);
end;

procedure TfrmInformePlanificacionProduccion.btnGuardarArchivoClick(Sender: TObject);
var
  LFileName: string;
begin
  LFileName := 'Informe_Fabricacion_' + FormatDateTime('yyyymmdd_hhnnss', Now) + '.txt';
  saveDlgTxt.FileName := LFileName;
  if saveDlgTxt.Execute then
  begin
    mmoInforme.Lines.SaveToFile(saveDlgTxt.FileName, TEncoding.UTF8);
    MessageDlg('Informe guardado correctamente en:' + sLineBreak + saveDlgTxt.FileName,
      mtInformation, [mbOK], 0);
  end;
end;

type
  TEstiloLineaMemo = (
    elmNormal,
    elmLoteMasa,
    elmTotalMasaBase,
    elmFormatoSabor,
    elmCabeceraInclusiones,
    elmIngredienteInclusion
  );

function ClasificarLinea(const ALine: string; var AEnInclusiones: Boolean): TEstiloLineaMemo;
var
  LTrim: string;
begin
  LTrim := Trim(ALine);

  if StartsText('[A]', LTrim) or StartsText('[B]', LTrim) or StartsText('===', LTrim) or
     StartsText('---', LTrim) or StartsText('1.', LTrim) or StartsText('2.', LTrim) or
     StartsText('3.', LTrim) or StartsText('4.', LTrim) or StartsText('5.', LTrim) or
     StartsText('[ ] Verificado', LTrim) or StartsText('ELABORACION FORMATO:', LTrim) or
     StartsText('Artículo Final:', LTrim) or StartsText('[TOTAL MASA BASE]', LTrim) then
  begin
    AEnInclusiones := False;
  end;

  if Pos('[C] INCLUSIONES', ALine) > 0 then
  begin
    AEnInclusiones := True;
    Result := elmCabeceraInclusiones;
  end
  else if Pos('(Lote Masa:', ALine) > 0 then
    Result := elmLoteMasa
  else if (Pos('[TOTAL MASA BASE]', ALine) > 0) or StartsText('MASA BASE (Receta', LTrim) then
    Result := elmTotalMasaBase
  else if StartsText('ELABORACION FORMATO:', LTrim) then
    Result := elmFormatoSabor
  else if AEnInclusiones and StartsText('-', LTrim) then
    Result := elmIngredienteInclusion
  else
    Result := elmNormal;
end;

procedure TfrmInformePlanificacionProduccion.PrepararReporteFastReport(
  AReport: TfrxReport; const ATitulo, ASubtitulo, ATexto: string);
const
  PAGE_BREAK_MARKER = '>>> CORTE DE PÁGINA (SIGUIENTE HOJA) <<<';
var
  LPage: TfrxReportPage;
  LPageHeader: TfrxPageHeader;
  LTitleMemo, LSubMemo: TfrxMemoView;
  LPageFooter: TfrxPageFooter;
  LFooterMemo: TfrxMemoView;
  LDataBand: TfrxMasterData;
  LPaginas: TArray<string>;
  p, i: Integer;
  LChunk, LLineRaw: string;
  LLines, LBloqueLines: TStringList;
  LEnInclusiones: Boolean;
  LEstiloActual, LEstiloLinea: TEstiloLineaMemo;
  LCurrentTop: Extended;

  procedure EmitirBloque(AEstilo: TEstiloLineaMemo; ALines: TStrings);
  var
    LMemo: TfrxMemoView;
  begin
    if (ALines = nil) or (ALines.Count = 0) then Exit;

    LMemo := TfrxMemoView.Create(LDataBand);
    LMemo.CreateUniqueName;
    LMemo.Left := 0;
    LMemo.Top := LCurrentTop;
    LMemo.Width := 718;
    LMemo.StretchMode := smActualHeight;
    LMemo.ShiftMode := smAlways;
    LMemo.AllowExpressions := False;
    LMemo.AllowHTMLTags := False;
    LMemo.WordWrap := True;
    LMemo.Font.Name := 'Consolas';

    case AEstilo of
      elmNormal:
      begin
        LMemo.Font.Size := 8;
        LMemo.Font.Style := [];
        LMemo.Font.Color := clBlack;
        LMemo.Color := clWhite;
        LMemo.Frame.Typ := [];
        LMemo.Height := Max(14, ALines.Count * 13);
      end;

      elmLoteMasa:
      begin
        LMemo.Font.Size := 10;
        LMemo.Font.Style := [fsBold];
        LMemo.Font.Color := clBlack;
        LMemo.Color := $00C0F0FF; // Amarillo pastel suave
        LMemo.Frame.Typ := [ftLeft, ftRight, ftTop, ftBottom];
        LMemo.Frame.Color := $0090D0E0;
        LMemo.Frame.Width := 1;
        LMemo.Height := Max(18, ALines.Count * 18);
      end;

      elmTotalMasaBase:
      begin
        LMemo.Font.Size := 11;
        LMemo.Font.Style := [fsBold];
        LMemo.Font.Color := clNavy;
        LMemo.Color := $0098E4FF; // Amarillo destacado oro suave
        LMemo.Frame.Typ := [ftLeft, ftRight, ftTop, ftBottom];
        LMemo.Frame.Color := $0070B8D0;
        LMemo.Frame.Width := 1;
        LMemo.Height := Max(20, ALines.Count * 20);
      end;

      elmFormatoSabor:
      begin
        LMemo.Font.Size := 10;
        LMemo.Font.Style := [fsBold];
        LMemo.Font.Color := clBlack;
        LMemo.Color := $00C0F0FF; // Amarillo pastel suave
        LMemo.Frame.Typ := [ftLeft, ftRight, ftTop, ftBottom];
        LMemo.Frame.Color := $0090D0E0;
        LMemo.Frame.Width := 1;
        LMemo.Height := Max(18, ALines.Count * 18);
      end;

      elmCabeceraInclusiones:
      begin
        LMemo.Font.Size := 9;
        LMemo.Font.Style := [fsBold];
        LMemo.Font.Color := clBlack;
        LMemo.Color := $00EDF6F8;
        LMemo.Frame.Typ := [ftBottom];
        LMemo.Frame.Color := $00B0B0B0;
        LMemo.Height := Max(16, ALines.Count * 16);
      end;

      elmIngredienteInclusion:
      begin
        LMemo.Font.Size := 10;
        LMemo.Font.Style := [fsBold];
        LMemo.Font.Color := clBlack;
        LMemo.Color := $00C0F0FF; // Amarillo pastel suave
        LMemo.Frame.Typ := [ftLeft, ftRight, ftTop, ftBottom];
        LMemo.Frame.Color := $0090D0E0;
        LMemo.Frame.Width := 1;
        LMemo.Height := Max(18, ALines.Count * 18);
      end;
    end;

    LMemo.Memo.Assign(ALines);
    LCurrentTop := LCurrentTop + LMemo.Height + 2;
  end;

begin
  if not Assigned(AReport) then Exit;

  AReport.Clear;
  AReport.ReportOptions.Name := ATitulo;

  if Pos(PAGE_BREAK_MARKER, ATexto) > 0 then
    LPaginas := ATexto.Split([PAGE_BREAK_MARKER])
  else
    LPaginas := [ATexto];

  LLines := TStringList.Create;
  try
    for p := 0 to High(LPaginas) do
    begin
      LLines.Text := LPaginas[p];
      // Limpiar líneas vacías o de borde divisor al principio y final de cada fragmento
      while (LLines.Count > 0) and
            ((Trim(LLines[0]) = '') or (Pos('=====', LLines[0]) > 0)) do
        LLines.Delete(0);
      while (LLines.Count > 0) and
            ((Trim(LLines[LLines.Count - 1]) = '') or (Pos('=====', LLines[LLines.Count - 1]) > 0)) do
        LLines.Delete(LLines.Count - 1);

      LChunk := Trim(LLines.Text);
      if LChunk = '' then Continue;

      LPage := TfrxReportPage.Create(AReport);
      LPage.CreateUniqueName;
      LPage.Orientation := poPortrait;
      LPage.PaperSize := 9; // DMPAPER_A4
      LPage.PaperWidth := 210;
      LPage.PaperHeight := 297;
      LPage.LeftMargin := 10;
      LPage.RightMargin := 10;
      LPage.TopMargin := 10;
      LPage.BottomMargin := 10;

      // Encabezado de página
      LPageHeader := TfrxPageHeader.Create(LPage);
      LPageHeader.CreateUniqueName;
      LPageHeader.Height := 46;

      LTitleMemo := TfrxMemoView.Create(LPageHeader);
      LTitleMemo.CreateUniqueName;
      LTitleMemo.Left := 0;
      LTitleMemo.Top := 0;
      LTitleMemo.Width := 718;
      LTitleMemo.Height := 22;
      LTitleMemo.Font.Name := 'Segoe UI';
      LTitleMemo.Font.Size := 11;
      LTitleMemo.Font.Style := [fsBold];
      LTitleMemo.Font.Color := $002C2C2C;
      LTitleMemo.AllowExpressions := False;
      LTitleMemo.Text := ATitulo;

      LSubMemo := TfrxMemoView.Create(LPageHeader);
      LSubMemo.CreateUniqueName;
      LSubMemo.Left := 0;
      LSubMemo.Top := 22;
      LSubMemo.Width := 718;
      LSubMemo.Height := 18;
      LSubMemo.Font.Name := 'Segoe UI';
      LSubMemo.Font.Size := 9;
      LSubMemo.Font.Color := $00555555;
      LSubMemo.AllowExpressions := False;
      LSubMemo.Text := ASubtitulo;

      // Pie de página
      LPageFooter := TfrxPageFooter.Create(LPage);
      LPageFooter.CreateUniqueName;
      LPageFooter.Height := 18;

      LFooterMemo := TfrxMemoView.Create(LPageFooter);
      LFooterMemo.CreateUniqueName;
      LFooterMemo.Left := 0;
      LFooterMemo.Top := 2;
      LFooterMemo.Width := 718;
      LFooterMemo.Height := 16;
      LFooterMemo.Font.Name := 'Segoe UI';
      LFooterMemo.Font.Size := 8;
      LFooterMemo.Font.Color := $00777777;
      LFooterMemo.HAlign := haRight;
      LFooterMemo.Text := 'Página [Page#] de [TotalPages#]';

      // Banda de datos para los bloques de texto
      LDataBand := TfrxMasterData.Create(LPage);
      LDataBand.CreateUniqueName;
      LDataBand.RowCount := 1;
      LDataBand.Height := 20;
      LDataBand.Stretched := True;
      LDataBand.AllowSplit := True;

      // Desglosar líneas en bloques homogéneos con formato nativo de FastReport
      LEnInclusiones := False;
      LCurrentTop := 0;
      LBloqueLines := TStringList.Create;
      try
        LEstiloActual := elmNormal;
        for i := 0 to LLines.Count - 1 do
        begin
          LLineRaw := LLines[i];
          LEstiloLinea := ClasificarLinea(LLineRaw, LEnInclusiones);

          if (LBloqueLines.Count > 0) and (LEstiloLinea <> LEstiloActual) then
          begin
            EmitirBloque(LEstiloActual, LBloqueLines);
            LBloqueLines.Clear;
          end;

          LEstiloActual := LEstiloLinea;
          LBloqueLines.Add(LLineRaw);
        end;

        if LBloqueLines.Count > 0 then
          EmitirBloque(LEstiloActual, LBloqueLines);
      finally
        LBloqueLines.Free;
      end;

      LDataBand.Height := Max(20, LCurrentTop + 5);
    end;
  finally
    LLines.Free;
  end;
end;

procedure TfrmInformePlanificacionProduccion.btnImprimirClick(Sender: TObject);
var
  LReportName: string;
begin
  try
    LReportName := 'Informe_Planificacion_Produccion_' + FormatDateTime('yyyymmdd_hhnn', Now);
    PrepararReporteFastReport(dmgMain.frxInforme, lblTitle.Caption, lblSubtitle.Caption, mmoInforme.Lines.Text);
    TfrmPrintOptions.ShowOptions(
      Self,
      dmgMain.frxInforme,
      nil,
      LReportName,
      '',
      '',
      1,
      nil,
      nil,
      'PLANIFICACION_PRODUCCION'
    );
  except
    on E: Exception do
      MessageDlg('Error al abrir el diálogo de impresión: ' + E.Message, mtError, [mbOK], 0);
  end;
end;

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

end.
