unit U_LabelPrint;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage,
  Printers, cxEdit, DB, cxDBData, ToolWin, ComCtrls, cxGridCustomTableView,
  cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxControls,
  cxGridCustomView, cxGrid, DBClient, ADODB, ImgList, StdCtrls, ExtCtrls,
  cxTextEdit, cxGridCustomPopupMenu, cxGridPopupMenu, cxLookAndFeels,
  cxLookAndFeelPainters, cxNavigator, dxBarBuiltInMenu, RM_Common, RM_Class,
  RM_GridReport, RM_Dataset, RM_E_llPDF, RM_BarCode, RM_e_Graphic, RM_e_Jpeg,
  RM_e_Xls, cxContainer, cxMaskEdit, cxDropDownEdit, cxMRUEdit, dxSkinsCore,
  dxSkinsDefaultPainters, cxProgressBar, cxButtons, dxSkinBlack, dxSkinBlue,
  dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
  dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
  dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
  dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
  dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
  dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
  dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
  dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
  dxSkinOffice2013White, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic,
  dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust,
  dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVS2010,
  dxSkinWhiteprint, dxSkinXmas2008Blue, RM_System, Buttons;

type
  TfrmLabelPrint = class(TForm)
    ADOQueryTemp: TADOQuery;
    ADOConnection1: TADOConnection;
    Panel1: TPanel;
    ImageList1: TImageList;
    RMDB_1: TRMDBDataSet;
    RM1: TRMGridReport;
    RMDB_2: TRMDBDataSet;
    CDS_Label: TClientDataSet;
    ADO_Prt: TADOQuery;
    btnShow: TSpeedButton;
    RMDB_3: TRMDBDataSet;
    RMXLSExport1: TRMXLSExport;
    RMJPEGExport1: TRMJPEGExport;
    RMBarCodeObject1: TRMBarCodeObject;
    CheckBox1: TCheckBox;
    Label1: TLabel;
    cbbLab: TcxMRUEdit;
    CheckBox2: TCheckBox;
    ADOQueryCmd: TADOQuery;
    ADO_While: TADOQuery;
    ComboBox1: TcxComboBox;
    btnPrint: TSpeedButton;
    RMDB_4: TRMDBDataSet;
    RMDB_5: TRMDBDataSet;
    CDS_1: TClientDataSet;
    CDS_2: TClientDataSet;
    CDS_3: TClientDataSet;
    CDS_4: TClientDataSet;
    CDS_5: TClientDataSet;
    ComboBox_Print: TComboBox;
    procedure FormCreate(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormShow(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure TV1DblClick(Sender: TObject);
    procedure btnPrintClick(Sender: TObject);
    procedure btnShowClick(Sender: TObject);
    procedure cbbLabPropertiesButtonClick(Sender: TObject);
  private
    IsDebug, FPreviewPrint, IsSql1, IsSql2, IsSql3, IsSql4, IsSql5: Boolean;
    FLMType, FQrCodeField: string;
    FFiltration1, FFiltration2, FFiltration3, FFiltration4, FFiltration5: string;
    FSuccessfulFun: string;
    FparamBlclid: string;
    procedure InitGrid();
    procedure PrintLabel(MIsShow: Boolean);
    procedure GetPrtData(Ado: TADOQuery; Cds: TClientDataSet; IsSql: Boolean; LMSql, FFiltration: string);
    procedure InitArgs();
    { Private declarations }
  public
    FPrintJson: PChar;
    FJsonOut: PChar;
    DConString, DCode, DName: string;
    constructor Create(AOwner: TComponent; JsonArgs: PChar);
    { Public declarations }
  end;

var
  frmLabelPrint: TfrmLabelPrint;

implementation

uses
  U_RTFun, U_LabelMapSet, superobject, U_QrCodeFun, U_Fun ;

{$R *.dfm}
constructor TfrmLabelPrint.Create(AOwner: TComponent; JsonArgs: PChar);
begin
  inherited Create(AOwner);
  FPrintJson := JsonArgs;
//  fFormID := mFormID;
//  fBLCLID := recid;
//  if CopyNumber > 0 then
//    fCopyNumber := CopyNumber
//  else
//    fCopyNumber := 1;
//  fIsPreview := IsPreview;
//  fprinterIndex := printerIndex;
//  fexportFileType := exportFileType;
end;

procedure TfrmLabelPrint.InitArgs;
var
  JSONObject, item: ISuperObject; // SuperObject 接口类型
  jsonArray: TSuperArray;
  i: Integer;
begin
  // 解析 JSON 字符串
  JSONObject := SO(FPrintJson);
  if JSONObject = nil then
  begin
    Application.MessageBox('PrintJson格式异常!', '提示', 0);
    Exit;
  end;

  // 提取基础字段
  IsDebug := JSONObject.B['IsDebug'];
  FSuccessfulFun := JSONObject.S['SuccessfulFun'];
  FLMType := JSONObject.S['LMType'];
  FPreviewPrint := JSONObject.B['PreviewPrint'];
  FQrCodeField := JSONObject.S['QrCodeField'];
  DConString := JSONObject.S['DConString'];
  DCode := JSONObject.S['DCode'];
  DName := JSONObject.S['DName'];



  // 获取数组
  jsonArray := JSONObject.A['PrtArgs'];
  if jsonArray = nil then // 处理数组不存在的情况
  begin
    Application.MessageBox('PrtArgs数组缺失!', '提示', 0);
    Exit;
  end;

  // 初始化变量避免未定义行为
  FFiltration1 := '';
  FFiltration2 := '';
  FFiltration3 := '';
  FFiltration4 := '';
  FFiltration5 := '';

  // 遍历JSON数组（最多处理5个元素）
  for i := 0 to jsonArray.Length - 1 do
  begin
    item := jsonArray.O[i];
    case i of
      0:
        begin
          IsSql1 := item.B['IsSql'];
          FFiltration1 := item.S['Filtration'];
        end;
      1:
        begin
          IsSql2 := item.B['IsSql'];
          FFiltration2 := item.S['Filtration'];
        end;
      2:
        begin
          IsSql3 := item.B['IsSql'];
          FFiltration3 := item.S['Filtration'];
        end;
      3:
        begin
          IsSql4 := item.B['IsSql'];
          FFiltration4 := item.S['Filtration'];
        end;
      4:
        begin
          IsSql5 := item.B['IsSql'];
          FFiltration5 := item.S['Filtration'];
        end;
    end;
  end;

  // 空值回退逻辑
  if Trim(FFiltration2) = '' then
  begin
    IsSql2 := IsSql1;
    FFiltration2 := FFiltration1;
  end;

  if Trim(FFiltration3) = '' then
  begin
    IsSql3 := IsSql1;
    FFiltration3 := FFiltration1;
  end;

  if Trim(FFiltration4) = '' then
  begin
    IsSql4 := IsSql1;
    FFiltration4 := FFiltration1;
  end;

  if Trim(FFiltration5) = '' then
  begin
    IsSql5 := IsSql1;
    FFiltration5 := FFiltration1;
  end;
end;

procedure TfrmLabelPrint.GetPrtData(Ado: TADOQuery; Cds: TClientDataSet; IsSql: Boolean; LMSql, FFiltration: string);
begin
  with Ado do
  begin
    Close;
    sql.Clear;
    if IsSql then
    begin
      sql.add('exec ' + trim(CDS_Label.fieldbyname(LMSql).AsString));
      sql.add(FFiltration);
    end
    else
    begin
      sql.add('exec ' + trim(CDS_Label.fieldbyname(LMSql).AsString) + '  ' + quotedstr(Trim(FFiltration)));
    end;
    if IsDebug then
      ShowMessage(sql.Text);
    Open;
  end;

  IintCDS(Ado, Cds);
  SetQrCodePath(Cds, FQrCodeField);
end;

procedure TfrmLabelPrint.PrintLabel(MIsShow: Boolean);
var
  fPrintFile, fPrintFile10, FMainID, LBName: string;
begin
  if CDS_Label.IsEmpty then
  begin
    Application.MessageBox(PChar('类型' + FLMType + '没有设置标签!'), '提示', 0);
    Exit;
  end;
  RMJPEGExport1.ShowDialog := CheckBox2.Checked;
  RMXLSExport1.ShowDialog := CheckBox2.Checked;
  RM1.ShowPrintDialog := CheckBox1.Checked;

  LBName := cbbLab.text;
  ExportFtErpFile(LBName + '.rmf', ADOQueryTemp);

  if CDS_Label.Locate('LMName', LBName, []) then
  begin
    if trim(CDS_Label.fieldbyname('LMSql1').AsString) <> '' then
      GetPrtData(ADO_Prt, CDS_1, IsSql1, 'LMSql1', FFiltration1);

    if trim(CDS_Label.fieldbyname('LMSql2').AsString) <> '' then
      GetPrtData(ADO_Prt, CDS_2, IsSql2, 'LMSql2', FFiltration2);

    if trim(CDS_Label.fieldbyname('LMSql3').AsString) <> '' then
      GetPrtData(ADO_Prt, CDS_3, IsSql3, 'LMSql3', FFiltration3);

    if trim(CDS_Label.fieldbyname('LMSql4').AsString) <> '' then
      GetPrtData(ADO_Prt, CDS_4, IsSql4, 'LMSql4', FFiltration4);

    if trim(CDS_Label.fieldbyname('LMSql5').AsString) <> '' then
      GetPrtData(ADO_Prt, CDS_5, IsSql5, 'LMSql5', FFiltration5);
  end;

  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\' + LBName + '.rmf';
  if FileExists(fPrintFile) then
  begin
    RM1.LoadFromFile(fPrintFile);
    RM1.DefaultCopies := StrToIntDef(ComboBox1.Text, 1);
    RMVariables['LBPrtCode'] := dcode;
    RMVariables['LBPrtName'] := dname;
    if MIsShow then
      RM1.ShowReport
    else
      RM1.PrintReportL(ComboBox_Print.Text);
    ;
  end
  else
  begin
    Application.MessageBox(PChar('没有找' + fPrintFile), '提示', 0);
  end;
end;

procedure TfrmLabelPrint.FormCreate(Sender: TObject);
begin

  FPreviewPrint := True;

  ComboBox_Print.Items.Assign(Printer.Printers);
//  ComboBox2.ItemIndex := 0; //指向第一台打印机
  ComboBox_Print.Items.Add('默认打印机');
  ComboBox_Print.ItemIndex := Self.ComboBox_Print.Items.IndexOf(trim('默认打印机'));

  InitArgs();
  with ADOConnection1 do
  begin
    Connected := false;
    ConnectionString := DConString;
    Connected := true;
  end;
  EnsureQrCodeDirectory();
  ClearQrCodeDirectory();
end;

procedure TfrmLabelPrint.btnPrintClick(Sender: TObject);
begin
  PrintLabel(False);
  FJsonOut := '{"success":true}';
  ModalResult := 1;
end;

procedure TfrmLabelPrint.btnShowClick(Sender: TObject);
begin

  PrintLabel(true);
  FJsonOut := '{"success":true,"ShowFlag":true}';
end;

procedure TfrmLabelPrint.cbbLabPropertiesButtonClick(Sender: TObject);
begin

  try
    frmLabelMapSet := TfrmLabelMapSet.Create(Application);
    with frmLabelMapSet do
    begin
      IsSql1 := self.IsSql1;
      IsSql2 := self.IsSql2;
      IsSql3 := self.IsSql3;
      IsSql4 := self.IsSql4;
      IsSql5 := self.IsSql5;
      FFiltration1 := self.FFiltration1;
      FFiltration2 := self.FFiltration2;
      FFiltration3 := self.FFiltration3;
      FFiltration4 := self.FFiltration4;
      FFiltration5 := self.FFiltration5;
      FLMType := self.FLMType;
      if ShowModal = 1 then
      begin
        Self.InitGrid();
      end;
    end;
  finally
    frmLabelMapSet.Free;
  end;
end;

procedure TfrmLabelPrint.FormClose(Sender: TObject; var Action: TCloseAction);
begin

  Action := cahide;
end;

procedure TfrmLabelPrint.InitGrid();
begin

  with ADOQueryTemp do
  begin
    close;
    sql.Clear;
    sql.Add('select  LMName  name from BS_Label_Map where LMType=' + QuotedStr(TRIM(FLMType)));
    sql.Add(' order by  SerialNo    ');
    Open;
    if isEmpty then
    begin
      exit;
    end;
    cbbLab.Properties.LookupItems.Clear;
    while not Eof do
    begin

      cbbLab.Properties.LookupItems.Add(Trim(fieldByName('Name').AsString));
      Next;
    end;

    cbbLab.ItemIndex := 0;
  end;

  with ADOQueryTemp do
  begin
    Filtered := False;
    Close;
    sql.Clear;
    Sql.Add('select * from BS_Label_Map where LMType=' + QuotedStr(TRIM(FLMType)));
    Open;
  end;
  SCreateCDS20(ADOQueryTemp, CDS_Label);
  SInitCDSData20(ADOQueryTemp, CDS_Label);
  if CDS_Label.IsEmpty then
  begin
    Application.MessageBox(PChar('类型' + FLMType + '没有设置标签!'), '提示', 0);
    Exit;
  end;
end;

procedure TfrmLabelPrint.FormShow(Sender: TObject);
begin

 
//  if FPreviewPrint then
//    RM1.PreviewButtons := [rmpbZoom, rmpbLoad, rmpbSave, rmpbPrint, rmpbFind, rmpbPageSetup, rmpbExit, rmpbSaveToXLS, rmpbExport, rmpbNavigator]
//  else
//    RM1.PreviewButtons := [rmpbZoom, rmpbLoad, rmpbSave, rmpbFind, rmpbPageSetup, rmpbExit, rmpbSaveToXLS, rmpbExport, rmpbNavigator];
//  ComboBox_Print.Properties.Items.Assign(printer.Printers);
  InitGrid();
end;

procedure TfrmLabelPrint.TV1DblClick(Sender: TObject);
begin
  ModalResult := 1;
end;

procedure TfrmLabelPrint.FormDestroy(Sender: TObject);
begin
  frmLabelPrint := nil;
end;

end.

