unit U_YMTRKList;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage,
  cxEdit, DB, cxDBData, cxGridCustomTableView, cxGridTableView,
  cxGridBandedTableView, cxGridDBBandedTableView, cxGridLevel, cxClasses,
  cxControls, cxGridCustomView, cxGridDBTableView, cxGrid, StdCtrls, ComCtrls,
  ExtCtrls, ToolWin, cxGridCustomPopupMenu, cxGridPopupMenu, ADODB, DBClient,
  cxDropDownEdit, cxCheckBox, RM_Common, RM_Class, RM_e_Xls, RM_Dataset,
  RM_System, RM_GridReport, Menus, cxCalendar, cxButtonEdit, cxTextEdit,
  cxContainer, cxImage, cxDBEdit, cxLookAndFeels, cxLookAndFeelPainters,
  dxSkinsCore, 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,
  dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint,
  dxSkinXmas2008Blue, dxSkinscxPCPainter, cxNavigator, cxCurrencyEdit,
  cxMaskEdit, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP;

type
  TfrmYMTRKList = class(TForm)
    ToolBar1: TToolBar;
    TBRafresh: TToolButton;
    TBFind: TToolButton;
    TBExport: TToolButton;
    TBClose: TToolButton;
    Panel1: TPanel;
    ADOQueryCmd: TADOQuery;
    ADOQueryMain: TADOQuery;
    ADOQueryTemp: TADOQuery;
    DataSource1: TDataSource;
    cxGridPopupMenu1: TcxGridPopupMenu;
    Label1: TLabel;
    Label2: TLabel;
    BegDate: TDateTimePicker;
    EndDate: TDateTimePicker;
    CDS_Main: TClientDataSet;
    RM1: TRMGridReport;
    RMDBMain: TRMDBDataSet;
    RMXLSExport1: TRMXLSExport;
    RMDBHZ: TRMDBDataSet;
    CDS_HZ: TClientDataSet;
    CDS_PRT: TClientDataSet;
    TBDel: TToolButton;
    PopupMenu1: TPopupMenu;
    N1: TMenuItem;
    N2: TMenuItem;
    TBAdd: TToolButton;
    TBEdit: TToolButton;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    Label8: TLabel;
    SPName: TEdit;
    FactoryName: TEdit;
    SPID: TEdit;
    SPSpec: TEdit;
    Label6: TLabel;
    SPCF: TEdit;
    Label7: TLabel;
    OrderNo: TEdit;
    cxGrid2: TcxGrid;
    Tv1: TcxGridDBTableView;
    v1Column6: TcxGridDBColumn;
    v1Column2: TcxGridDBColumn;
    v1Column4: TcxGridDBColumn;
    v1Column13: TcxGridDBColumn;
    v1Column15: TcxGridDBColumn;
    v1Column17: TcxGridDBColumn;
    v1Column14: TcxGridDBColumn;
    v2Column1: TcxGridDBColumn;
    v1Column8: TcxGridDBColumn;
    v1Column7: TcxGridDBColumn;
    v1Column1: TcxGridDBColumn;
    v1Column10: TcxGridDBColumn;
    v1Column11: TcxGridDBColumn;
    v1Column9: TcxGridDBColumn;
    v2Column6: TcxGridDBColumn;
    v1Column3: TcxGridDBColumn;
    v1Column16: TcxGridDBColumn;
    v1Column12: TcxGridDBColumn;
    cxGrid2Level1: TcxGridLevel;
    Label9: TLabel;
    ToFactoryName: TEdit;
    Label12: TLabel;
    CRType: TComboBox;
    v1Column18: TcxGridDBColumn;
    v1Column19: TcxGridDBColumn;
    Label11: TLabel;
    RCGangNo: TEdit;
    Label13: TLabel;
    SPColor: TEdit;
    Label15: TLabel;
    SPHX: TEdit;
    ADOQueryImage: TADOQuery;
    v1Column21: TcxGridDBColumn;
    cxGrid1: TcxGrid;
    TvMX: TcxGridDBTableView;
    TvMXMXQty: TcxGridDBColumn;
    cxGridLevel2: TcxGridLevel;
    CDS_MX: TClientDataSet;
    DS_MX: TDataSource;
    cxGridPopupMenu2: TcxGridPopupMenu;
    ToolButton1: TToolButton;
    ToolButton2: TToolButton;
    TvMXMXID: TcxGridDBColumn;
    Panel2: TPanel;
    ToolBar2: TToolBar;
    TbAddRow: TToolButton;
    TbDeleteRow: TToolButton;
    Panel3: TPanel;
    AddNum: TEdit;
    Label17: TLabel;
    Button1: TButton;
    TvMXSsel: TcxGridDBColumn;
    TbEditKW: TToolButton;
    Tv1SSel: TcxGridDBColumn;
    Panel4: TPanel;
    Label25: TLabel;
    btnChk: TButton;
    btn1: TButton;
    KuWei: TcxButtonEdit;
    Tv1Column1: TcxGridDBColumn;
    Tv1Column2: TcxGridDBColumn;
    Tv1Column3: TcxGridDBColumn;
    TvMXColumn1: TcxGridDBColumn;
    Tv1Column4: TcxGridDBColumn;
    pm1: TPopupMenu;
    MenuItem1: TMenuItem;
    Panel5: TPanel;
    Label10: TLabel;
    Sure: TButton;
    Quit: TButton;
    Label14: TLabel;
    MQty: TEdit;
    KgQty: TEdit;
    http: TIdHTTP;
    procedure FormDestroy(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure TBRafreshClick(Sender: TObject);
    procedure ConNoMChange(Sender: TObject);
    procedure TBCloseClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure TBExportClick(Sender: TObject);
    procedure TBFindClick(Sender: TObject);
    procedure N1Click(Sender: TObject);
    procedure N2Click(Sender: TObject);
    procedure TBDelClick(Sender: TObject);
    procedure TBAddClick(Sender: TObject);
    procedure TBEditClick(Sender: TObject);
    procedure SPIDChange(Sender: TObject);
    procedure SPSpecChange(Sender: TObject);
    procedure FactoryNameChange(Sender: TObject);
    procedure TvMXCustomDrawIndicatorCell(Sender: TcxGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxCustomGridIndicatorItemViewInfo; var ADone: Boolean);
    procedure Tv1FocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean);
    procedure ToolButton1Click(Sender: TObject);
    procedure ToolButton2Click(Sender: TObject);
    procedure TbAddRowClick(Sender: TObject);
    procedure TbDeleteRowClick(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure TbEditKWClick(Sender: TObject);
    procedure KuWeiPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
    procedure btnChkClick(Sender: TObject);
    procedure btn1Click(Sender: TObject);
    procedure MenuItem1Click(Sender: TObject);
    procedure SureClick(Sender: TObject);
    procedure QuitClick(Sender: TObject);
  private
    canshu1, canshu2: string;
    procedure InitGrid();
    procedure InitImage(fsubID: string);
    procedure InitMXGrid(SPID: string);
    function BatchStockIn(MXIDs: string; UserID: string): Boolean;

    { Private declarations }
  public
    { Public declarations }
  end;

var
  frmYMTRKList: TfrmYMTRKList;

implementation

uses
  U_DataLink, U_RTFun, U_YMTRKInPut, U_ZdyAttachGYS, U_LabelPrintFun, U_ZDYHelp,
  U_KuWeiList, superobject;

{$R *.dfm}
function TfrmYMTRKList.BatchStockIn(MXIDs: string; UserID: string): Boolean;
var
  IdHttp: TIdHTTP;
  Url, ResponseStr: string;
  ResponseStream: TStringStream;
  vJson1: ISuperObject;
begin
  Result := False;

//   参数验证
  if Trim(MXIDs) = '' then
  begin
    ShowMessage('MXID不能为空');
    Exit;
  end;

  if Trim(UserID) = '' then
  begin
    ShowMessage('用户ID不能为空');
    Exit;
  end;

  IdHttp := TIdHTTP.Create(nil);
  ResponseStream := TStringStream.Create('');
  try
    try
      // GET请求 - 不需要设置ContentType
      // 参数直接放在URL中
      // 接口URL（参数编码在URL中）
      Url := 'http://www.rightsoft.top/YunXiang/api/YMTCK/batchStockIn?' + 'MXID=' + Trim(MXIDs) + '&userid=' + Trim(UserID);
//      ShowMessage(Url);
      // 发送GET请求
      IdHttp.Get(Url, ResponseStream);

      // 获取响应内容
      ResponseStr := ResponseStream.DataString;

      // 解析JSON响应
      vJson1 := SO(ResponseStr);
//      ShowMessage(ResponseStr);
      if (vJson1.O['code'] <> nil) then
      begin
        if (vJson1.O['code'].AsInteger = 10000) then
        begin
          Result := True;
          ShowMessage('批量入库成功！');
        end
        else
        begin
          // 获取错误信息
          if vJson1.O['message'] <> nil then
            ShowMessage('批量入库失败: ' + vJson1.O['message'].AsString)
          else
            ShowMessage('批量入库失败，未知错误');
        end;
      end
      else
      begin
        ShowMessage('接口返回格式错误');
      end;

    except
      on e: Exception do
      begin
        ShowMessage('网络请求异常: ' + e.Message);
      end;
    end;

  finally
    IdHttp.Free;
    ResponseStream.Free;
  end;
end;

procedure TfrmYMTRKList.InitMXGrid(SPID: string);
begin
  with ADOQueryTemp do
  begin
    Close;
    sql.Clear;
    sql.Add('select * from YMT_CK_MX where 1 = 1 and SPID=' + quotedstr(Trim(SPID)));
    sql.Add(' order by MXID');
    Open;
  end;
  SCreateCDS20(ADOQueryTemp, CDS_MX);
  SInitCDSData20(ADOQueryTemp, CDS_MX);
end;

procedure TfrmYMTRKList.InitImage(fsubID: string);
begin
  ADOQueryImage.close;
 // IF fwbid='' then exit;
  with ADOQueryImage do
  begin
    close;
    sql.Clear;
    sql.Add('select * from TP_File A');
    sql.Add('inner join JYOrder_Sub B on B.HXFile=A.WBID');
    sql.Add('where B.SubID=' + quotedstr(trim(fsubID)));
    open;
  end;
end;

procedure TfrmYMTRKList.FormDestroy(Sender: TObject);
begin
  frmYMTRKList := nil;
end;

procedure TfrmYMTRKList.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;
end;

procedure TfrmYMTRKList.FormCreate(Sender: TObject);
begin
  //cxGrid1.Align:=alClient;
  canshu1 := Trim(DParameters1);
  canshu2 := Trim(DParameters2);
  EndDate.DateTime := SGetServerDate10(ADOQueryTemp);
  BegDate.DateTime := EndDate.DateTime;
end;

procedure TfrmYMTRKList.InitGrid();
begin
  try
    ADOQueryMain.DisableControls;
    with ADOQueryMain do
    begin
      Filtered := False;
      Close;
      sql.Clear;
      sql.Add(' select A.* ');
      sql.Add(' from YMT_CK_CR A');
      sql.add(' where A.CRTime>=''' + Trim(FormatDateTime('yyyy-MM-dd', BegDate.DateTime)) + '''');
      sql.Add(' and A.CRTime<=''' + Trim(FormatDateTime('yyyy-MM-dd', enddate.DateTime + 1)) + '''');
      sql.Add(' and isnull(CKName,'''')=''待检布''');
      SQL.Add(' and CRFlag=''入库''  ');
      Open;
      //ShowMessage(SQL.Text);
    end;
    SCreateCDS20(ADOQueryMain, CDS_Main);
    SInitCDSData20(ADOQueryMain, CDS_Main);

    InitMXGrid(Trim(CDS_Main.fieldbyname('SPID').AsString));
  finally
    ADOQueryMain.EnableControls;
  end;
end;

procedure TfrmYMTRKList.TBRafreshClick(Sender: TObject);
begin
  BegDate.SetFocus;
  InitGrid();
end;

procedure TfrmYMTRKList.ConNoMChange(Sender: TObject);
begin
  if ADOQueryMain.Active then
  begin
    SDofilter(ADOQueryMain, SGetFilters(Panel1, 1, 2));
  end;
end;

procedure TfrmYMTRKList.TBCloseClick(Sender: TObject);
begin
  WriteCxGrid('待检布入库列表', Tv1, '待检布仓库');
  WriteCxGrid('待检布入库列表2', TvMX, '待检布仓库');
  Close;
end;

procedure TfrmYMTRKList.FormShow(Sender: TObject);
begin
  if Trim(canshu2) = '查看' then
  begin
    TBAdd.Visible := False;
    TBDel.Visible := False;
    TBEdit.Visible := False;
  end
  else
  begin
    TBAdd.Visible := True;
    TBDel.Visible := True;
    TBEdit.Visible := True;
  end;
//  ReadCxGrid('待检布入库列表', Tv1, '待检布仓库');
//  ReadCxGrid('待检布入库列表2', TvMX, '待检布仓库');
  InitGrid();
end;

procedure TfrmYMTRKList.TBExportClick(Sender: TObject);
begin
  if ADOQueryMain.IsEmpty then
    exit;
  TcxGridToExcel('待检布入库列表', cxGrid2);
end;

procedure TfrmYMTRKList.TBFindClick(Sender: TObject);
begin
  if ADOQueryMain.Active then
  begin
    SDofilter(ADOQueryMain, SGetFilters(Panel1, 1, 2));
    SCreateCDS20(ADOQueryMain, CDS_Main);
    SInitCDSData20(ADOQueryMain, CDS_Main);
  end;
end;

procedure TfrmYMTRKList.N1Click(Sender: TObject);
begin
  SelOKNo(CDS_Main, True);
end;

procedure TfrmYMTRKList.N2Click(Sender: TObject);
begin
  SelOKNo(CDS_Main, False);
end;

procedure TfrmYMTRKList.TBDelClick(Sender: TObject);
begin
  if CDS_Main.IsEmpty then
    Exit;
  if Trim(CDS_Main.fieldbyname('SPID').AsString) <> '' then
  begin
    if Trim(CDS_Main.fieldbyname('CRType').AsString) = '平移入库' then
    begin
      Application.MessageBox('平移入库的数据为自动生成，不能删除!', '提示', 0);
      Exit;
    end;
    with ADOQueryTemp do
    begin
      Close;
      sql.Clear;
      sql.Add('select * from YMT_CK_CR where FZSPID=''' + Trim(CDS_Main.fieldbyname('SPID').AsString) + '''');
      sql.Add(' and CRQtyFlag=-1');
      Open;
    end;
    if ADOQueryTemp.IsEmpty = False then
    begin
      Application.MessageBox('已有出库记录，不能删除!', '提示', 0);
      Exit;
    end;

    if Application.MessageBox('确定要删除数据吗？', '提示', 32 + 4) <> IDYES then
      Exit;
    try
      ADOQueryCmd.Connection.BeginTrans;

      with ADOQueryCmd do
      begin
        Close;
        sql.Clear;
        sql.Add(' delete YMT_CK_CR where SPID=''' + Trim(CDS_Main.fieldbyname('SPID').AsString) + '''');
        ExecSQL;
      end;
      ADOQueryCmd.Connection.CommitTrans;
      CDS_Main.Delete;
    except
      ADOQueryCmd.Connection.RollbackTrans;
      Application.MessageBox('删除异常!', '提示', 0);
    end;
  end
  else
  begin
    CDS_Main.Delete;
  end;
end;

procedure TfrmYMTRKList.TBAddClick(Sender: TObject);
begin
  try
    frmYMTRKInPut := TfrmYMTRKInPut.Create(Application);
    with frmYMTRKInPut do
    begin
      PState := 0;
      FBCId := '';
      if ShowModal = 1 then
      begin
        Self.InitGrid();
      end;
    end;
  finally
    frmYMTRKInPut.Free;
  end;
end;

//procedure TfrmYMTRKList.TBEditClick(Sender: TObject);
//var
//  OldSPID: string; // 用于保存当前行的SPID
//begin
//  if CDS_Main.IsEmpty then
//    Exit;
//
//  if Trim(CDS_Main.fieldbyname('CRType').AsString) = '平移入库' then
//  begin
//    Application.MessageBox('平移入库的数据为自动生成，不能修改!', '提示', 0);
//    Exit;
//  end;
//  try
//    OldSPID := Trim(CDS_Main.fieldbyname('SPID').AsString);
//    frmYMTRKInPut := TfrmYMTRKInPut.Create(Application);
//    with frmYMTRKInPut do
//    begin
//      PState := 1;
//      FBCId := OldSPID;
//      TBDel.Visible := False;
//      TBAdd.Visible := False;
//      if ShowModal = 1 then
//      begin
//
//      end;
//    end;
//    InitGrid();
//    // 重新定位到原来的行
//    if not CDS_Main.Locate('SPID', OldSPID, []) then
//    begin
//      // 如果找不到原记录（如被删除），则定位到第一条记录
//      if not CDS_Main.IsEmpty then
//        CDS_Main.First;
//    end;
//  finally
//    frmYMTRKInPut.Free;
//  end;
//end;

procedure TfrmYMTRKList.TBEditClick(Sender: TObject);
var
  OldSPID: string; // 用于保存当前行的SPID
  SelectedSPIDs: TStringList; // 用于保存所有选中的SPID
begin
  if CDS_Main.IsEmpty then
    Exit;
    
  // 创建字符串列表保存所有选中的SPID
  SelectedSPIDs := TStringList.Create;
  try
    // 检查是否有选中的行
    if CDS_Main.Locate('SSel', True, []) = True then
    begin
      // 遍历数据集，收集所有选中的SPID
      CDS_Main.DisableControls;
      try
        CDS_Main.First;
        while not CDS_Main.Eof do
        begin
          if CDS_Main.FieldByName('SSel').AsBoolean then
          begin
            // 检查是否为平移入库
            if Trim(CDS_Main.FieldByName('CRType').AsString) = '平移入库' then
            begin
              Application.MessageBox('平移入库的数据为自动生成，不能修改!', '提示', 0);
              Exit; // 直接Exit，不需要手动释放SelectedSPIDs，finally块会处理
            end;
            SelectedSPIDs.Add(Trim(CDS_Main.FieldByName('SPID').AsString));
          end;
          CDS_Main.Next;
        end;
      finally
        CDS_Main.EnableControls;
      end;
    end
    else
    begin
      // 没有勾选任何行，只处理当前行
      // 检查当前行是否为平移入库
      if Trim(CDS_Main.FieldByName('CRType').AsString) = '平移入库' then
      begin
        Application.MessageBox('平移入库的数据为自动生成，不能修改!', '提示', 0);
        Exit;
      end;
      SelectedSPIDs.Add(Trim(CDS_Main.FieldByName('SPID').AsString));
    end;

    // 保存当前行的SPID用于后续定位
    OldSPID := Trim(CDS_Main.FieldByName('SPID').AsString);

    try
      frmYMTRKInPut := TfrmYMTRKInPut.Create(Application);
      with frmYMTRKInPut do
      begin
        PState := 1;
        FBCId := OldSPID; // 保持原有单个SPID的兼容性
        // 传递所有选中的SPID

        FSelectedSPIDs.Assign(SelectedSPIDs);

        TBDel.Visible := False;
        TBAdd.Visible := False;
        if ShowModal = 1 then
        begin
          // 处理返回结果
        end;
      end;
      InitGrid();
      // 重新定位到原来的行
      if not CDS_Main.Locate('SPID', OldSPID, []) then
      begin
        // 如果找不到原记录（如被删除），则定位到第一条记录
        if not CDS_Main.IsEmpty then
          CDS_Main.First;
      end;
    finally
      frmYMTRKInPut.Free;
    end;
  finally
    SelectedSPIDs.Free;
  end;
end;

procedure TfrmYMTRKList.SPIDChange(Sender: TObject);
begin
  if Length(Trim(SPID.Text)) < 4 then
  begin
    if Trim(SPID.Text) <> '' then
      Exit;
  end;
  TBFind.Click;
end;

procedure TfrmYMTRKList.SPSpecChange(Sender: TObject);
begin
  TBFind.Click;
end;

procedure TfrmYMTRKList.FactoryNameChange(Sender: TObject);
begin
  TBFind.Click;
end;

procedure TfrmYMTRKList.TvMXCustomDrawIndicatorCell(Sender: TcxGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxCustomGridIndicatorItemViewInfo; var ADone: Boolean);
var
  FValue: string;
  FBounds: TRect;
begin
  FBounds := AViewInfo.Bounds;
  if (AViewInfo is TcxGridIndicatorRowItemViewInfo) then
  begin
    ACanvas.FillRect(FBounds);
    ACanvas.DrawComplexFrame(FBounds, clBtnHighlight, clBtnShadow, [bBottom, bLeft, bRight], 1);
    FValue := IntToStr(TcxGridIndicatorRowItemViewInfo(AViewInfo).GridRecord.Index + 1);
    InflateRect(FBounds, -1, -1);    //Platform   specific.   May   not   work   on   Linux.
    ACanvas.Font.Color := clBlack;
    ACanvas.Brush.Style := bsClear;
    ACanvas.DrawText(FValue, FBounds, cxAlignCenter or cxAlignTop);
    ADone := True;
  end;
end;

procedure TfrmYMTRKList.Tv1FocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean);
begin
  InitMXGrid(Trim(CDS_Main.fieldbyname('SPID').AsString));
end;

procedure TfrmYMTRKList.ToolButton1Click(Sender: TObject);
var
  FPrintJson, JsonResult, MFiltration: string;
  RTValues: TStringArray;
begin
  if CDS_Main.IsEmpty then
    Exit;
  if CDS_MX.Locate('SSel', True, []) then
  begin
    RTValues := SelCDSKey(CDS_MX, ['MXID']);
    MFiltration := RTValues[0];
  end
  else
  begin
    MFiltration := Trim(CDS_Main.fieldbyname('SPID').AsString);
  end;
  FPrintJson := '{ "LMType": "LMType","QrCodeField": "MXID","PreviewPrint": true,"DConString": "' + DConString + '","DCode": "' + DCode + '","DName": "' + DName + '", "PrtArgs": [ { "IsSql": true, "Filtration": " ' + MFiltration + '" }] }';

  FormPrint(Application, PChar(FPrintJson));
end;

procedure TfrmYMTRKList.ToolButton2Click(Sender: TObject);
var
  MPrintJson, JsonResult, MFiltration: string;
begin
  if CDS_Main.IsEmpty then
    Exit;
  MFiltration := Trim(CDS_Main.fieldbyname('SPID').AsString);
  MPrintJson := '{ "LBName": "标签打印","QrCodeField": "MXID","DConString": "' + DConString + '","DCode": "' + DCode + '","DName": "' + DName + '","IsPreview": true,"printerIndex": 0,"ExportFileType": "", "PrtArgs": [ {"SqlStr": "EXEC P_YMT_CK_MX_Prt1 ''' + MFiltration + ''' " }] }';
  FunPrint(Application, PChar(MPrintJson));

end;

procedure TfrmYMTRKList.TbAddRowClick(Sender: TObject);
var
  MaxNo, MMXID, SPID: string;
begin
  if GetLSNo(ADOQueryTemp, MaxNo, 'MCM', 'YMT_CK_MX', 3, 1) = False then
  begin
    Application.MessageBox('取最大号失败!', '提示', 0);
    Exit;
  end;
  MMXID := Trim(MaxNo);
  SPID := Trim(CDS_Main.fieldbyname('SPID').AsString);
  with ADOQueryCmd do
  begin
    Close;
    SQL.Clear;
    sql.Add('insert into  YMT_CK_MX (MXID,SPID,MXQty)');
    sql.Add('values(' + quotedstr(MMXID));
    sql.Add(',' + quotedstr(Trim(SPID)));
    sql.Add(',0');
    sql.Add(')');
    ExecSQL;
  end;
  InitMXGrid(SPID);
end;

procedure TfrmYMTRKList.TbDeleteRowClick(Sender: TObject);
var
  Bookmark: TBookmark;
begin
  if CDS_MX.IsEmpty then
  begin
    Application.MessageBox('当前没有可删除的记录！', '提示', MB_ICONWARNING);
    Exit;
  end;

  if Application.MessageBox('确定要删除当前行吗？', '确认删除', MB_ICONQUESTION + MB_YESNO) <> IDYES then
    Exit;
    
  // 记录当前行，删除后尝试回到附近位置
  Bookmark := CDS_MX.GetBookmark;
  with ADOQueryCmd do
  begin
    Close;
    SQL.Clear;
    sql.Add('delete YMT_CK_MX   where MXID=' + quotedstr(Trim(CDS_MX.FieldByName('MXID').AsString)));
    ExecSQL;
  end;
  try
    CDS_MX.Delete;
  finally
    if CDS_MX.BookmarkValid(Bookmark) then
      CDS_MX.GotoBookmark(Bookmark);
    CDS_MX.FreeBookmark(Bookmark);
  end;

end;

procedure TfrmYMTRKList.Button1Click(Sender: TObject);
var
  Num, i: Integer;
  MaxNo, MMXID, SPID: string;
begin
  Num := StrToInt(Trim(AddNum.Text));
  SPID := Trim(CDS_Main.fieldbyname('SPID').AsString);

  try
    ADOQueryCmd.Connection.BeginTrans;
    for i := 1 to Num do
    begin
      if GetLSNo(ADOQueryTemp, MaxNo, 'MCM', 'YMT_CK_MX', 3, 1) = False then
      begin
        Application.MessageBox('取最大号失败!', '提示', 0);
        Exit;
      end;
      MMXID := Trim(MaxNo);
      with ADOQueryCmd do
      begin
        Close;
        SQL.Clear;
        sql.Add('insert into  YMT_CK_MX (MXID,SPID,MXQty)');
        sql.Add('values(' + quotedstr(MMXID));
        sql.Add(',' + quotedstr(Trim(SPID)));
        sql.Add(',0');
        sql.Add(')');
        ExecSQL;
      end;
    end;
    ADOQueryCmd.Connection.CommitTrans;
    InitMXGrid(SPID);
  except
    ADOQueryCmd.Connection.RollbackTrans;
    Application.MessageBox('添加失败!', '提示', 0);
  end;
end;

procedure TfrmYMTRKList.TbEditKWClick(Sender: TObject);
begin
  if CDS_Main.IsEmpty then
    exit;
  Panel4.Visible := True;
end;

procedure TfrmYMTRKList.KuWeiPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
begin
  try
    frmKuWeiList := TfrmKuWeiList.Create(Application);
    with frmKuWeiList do
    begin
      if ShowModal = 1 then
      begin
        with Self.CDS_Main do
        begin
          Edit;
          KuWei.Text := Trim(frmKuWeiList.Order_Main.fieldbyname('KWName').AsString);
        end;
      end;
    end;
  finally
    frmKuWeiList.Free;
  end;
end;

procedure TfrmYMTRKList.btnChkClick(Sender: TObject);
begin
  if CDS_Main.IsEmpty then
    exit;
  if CDS_Main.Locate('SSel', True, []) = False then
  begin
    application.MessageBox('请选择数据！', '提示信息');
    exit;
  end;

  try
    while CDS_Main.Locate('SSel', True, []) do
    begin
      with ADOQueryCmd do
      begin
        close;
        sql.Clear;
        sql.Add('update YMT_CK_CR SET KuWei=' + quotedstr(trim(KuWei.Text)));
        sql.Add('where SPID=' + quotedstr(trim(CDS_Main.fieldbyname('SPID').AsString)));
        execsql;
      end;
      with CDS_Main do
      begin
        Edit;
        FieldByName('SSel').Value := False;
        FieldByName('KuWei').Value := trim(KuWei.Text);
        Post;
      end;
    end;

    Panel4.Visible := False;
    application.MessageBox('批量修改成功！', '提示信息');
  except
    application.MessageBox('批量修改失败！', '提示信息', 0);
  end;
end;

procedure TfrmYMTRKList.btn1Click(Sender: TObject);
begin
  Panel4.Visible := False;
end;

procedure TfrmYMTRKList.MenuItem1Click(Sender: TObject);
begin
  if CDS_MX.IsEmpty then
    exit;
  Panel5.Visible := True;

end;

//执行拆批
procedure TfrmYMTRKList.SureClick(Sender: TObject);
var
  MaxNo, MMXID, SPID, MXIDs: string;
  fMQty, fKGQty: Double;
begin
  // 开始事务
  ADOQueryCmd.Connection.BeginTrans;

  try
    // 验证输入数值
    try
      fMQty := StrToFloat(Trim(MQty.Text));
      fKGQty := StrToFloat(Trim(KGQty.Text));
    except
      Application.MessageBox('请输入有效的数值！', '提示', 0);
      ADOQueryCmd.Connection.RollbackTrans; // 回滚事务
      Exit;
    end;

    if GetLSNo(ADOQueryTemp, MaxNo, 'MCM', 'YMT_CK_MX', 3, 1) = False then
    begin
      Application.MessageBox('取最大号失败!', '提示', 0);
      ADOQueryCmd.Connection.RollbackTrans; // 回滚事务
      Exit;
    end;

    MMXID := Trim(MaxNo);
    SPID := Trim(CDS_Main.fieldbyname('SPID').AsString);
    
    // 增加拆出了新批
    with ADOQueryCmd do
    begin
      Close;
      SQL.Clear;
      sql.Add('insert into YMT_CK_MX (MXID,SPID,MQty,KGQty,Filler)');
      sql.Add('values(' + quotedstr(MMXID));
      sql.Add(',' + quotedstr(Trim(SPID)));
      sql.Add(',' + FloatToStr(fMQty));  // 使用数值，不加引号
      sql.Add(',' + FloatToStr(fKGQty)); // 使用数值，不加引号
      sql.Add(',' + quotedstr(Trim(DName)));
      sql.Add(')');
      ExecSQL;
    end;

    // 更新当前数量和重量
    with ADOQueryCmd do
    begin
      close;
      sql.Clear;
      sql.Add('update YMT_CK_MX SET MQty = ' + FloatToStr(CDS_MX.FieldByName('MQty').AsFloat - fMQty));
      sql.Add(', KGQty = ' + FloatToStr(CDS_MX.FieldByName('KGQty').AsFloat - fKGQty));
      sql.Add('where MXID=' + quotedstr(trim(CDS_MX.fieldbyname('MXID').AsString)));
      execsql;
    end;
    MXIDs := MMXID + ',' + trim(CDS_MX.fieldbyname('MXID').AsString);

    // 提交事务 - 所有操作成功完成
    ADOQueryCmd.Connection.CommitTrans;

    // 调用接口，将拆批数据入库
    if MXIDs <> '' then
    begin
      if not BatchStockIn(MXIDs, Trim(DCode)) then
      begin
        Application.MessageBox('批量入库接口调用失败!', '提示', 0);
        Exit;
      end;
    end;

    InitMXGrid(SPID);
    Panel5.Visible := False;
    application.MessageBox('拆批成功！', '提示信息');

  except
    on E: Exception do
    begin
      // 回滚事务 - 发生任何异常都回滚
      ADOQueryCmd.Connection.RollbackTrans;
      Application.MessageBox(PChar('拆批失败！错误：' + E.Message), '提示信息', 0);
    end;
  end;
end;

procedure TfrmYMTRKList.QuitClick(Sender: TObject);
begin
  Panel5.Visible := False;
end;

end.

