unit U_TradePack;

interface

uses
  Windows, Messages, strutils, SysUtils, Variants, Classes, Graphics, Controls,
  Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
  cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxGridCustomTableView,
  cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView,
  cxGrid, StdCtrls, cxContainer, cxTextEdit, cxCurrencyEdit, BtnEdit, ExtCtrls,
  ComCtrls, ToolWin, DBClient, ADODB, MovePanel, Buttons, Menus,
  cxLookAndFeelPainters, cxButtons, RM_Common, RM_Class, RM_GridReport,
  RM_System, RM_Dataset, cxCheckBox, MMSystem, Math, WinSpool, Printers,
  cxGridCustomPopupMenu, cxGridPopupMenu, cxLookAndFeels, cxNavigator,
  dxDateRanges, dxBarBuiltInMenu,
  U_BaseList,  dxScrollbarAnnotations, cxMaskEdit, cxDropDownEdit,
  cxButtonEdit, dxLayoutcxEditAdapters, dxLayoutControlAdapters,
  dxLayoutContainer, dxLayoutControl, cxGroupBox, RM_BarCode, RM_RichEdit,
  cxProgressBar;

type
  TfrmTradePack = class(TfrmBaseList)
    Panel2: TPanel;
    ADOQueryMain: TADOQuery;
    ADOQueryCmd: TADOQuery;
    CDS_DDB: TClientDataSet;
    DS_DDB: TDataSource;
    SmNO: TcxTextEdit;
    ADOQueryTmp: TADOQuery;
    DataSource1: TDataSource;
    cxGrid3: TcxGrid;
    Tv3: TcxGridDBTableView;
    cxGridLevel2: TcxGridLevel;
    Tv3Column1: TcxGridDBColumn;
    DS_KDB: TDataSource;
    RMDB_1: TRMDBDataSet;
    RM2: TRMGridReport;
    Panel4: TPanel;
    ADOQueryPrint: TADOQuery;
    Label6: TLabel;
    v3C_Name: TcxGridDBColumn;
    v3C_Color: TcxGridDBColumn;
    v3Column3: TcxGridDBColumn;
    CDS_KDB: TClientDataSet;
    Panel5: TPanel;
    CDS_YDB: TClientDataSet;
    DS_YDB: TDataSource;
    v3Column5: TcxGridDBColumn;
    v3Column6: TcxGridDBColumn;
    v3Column7: TcxGridDBColumn;
    PM_KDB: TPopupMenu;
    N1: TMenuItem;
    N2: TMenuItem;
    PM_YDB: TPopupMenu;
    btnClose: TcxButton;
    N5: TMenuItem;
    chkBBQ: TCheckBox;
    PM_DDB: TPopupMenu;
    N6: TMenuItem;
    N3: TMenuItem;
    N4: TMenuItem;
    N7: TMenuItem;
    Label2: TLabel;
    CDS_DDY: TClientDataSet;
    cxGridPopupMenu2: TcxGridPopupMenu;
    cxGridPopupMenu1: TcxGridPopupMenu;
    cxGridPopupMenu3: TcxGridPopupMenu;
    v3Column4: TcxGridDBColumn;
    v3Column11: TcxGridDBColumn;
    btnOK: TcxButton;
    cxButton2: TcxButton;
    edtPacketNo: TcxTextEdit;
    cxButton3: TcxButton;
    Edit1: TcxTextEdit;
    N13: TMenuItem;
    CDS_PacketId: TClientDataSet;
    N8: TMenuItem;
    ComboBox1: TcxComboBox;
    ComboBox3: TcxComboBox;
    edtOrder: TcxButtonEdit;
    dxLayoutControl_tradepackGroup_Root: TdxLayoutGroup;
    dxLayoutControl_tradepack: TdxLayoutControl;
    dxLayoutGroup1: TdxLayoutGroup;
    dxLayoutItem1: TdxLayoutItem;
    dxLayoutItem2: TdxLayoutItem;
    dxLayoutItem3: TdxLayoutItem;
    dxLayoutItem4: TdxLayoutItem;
    dxLayoutItem5: TdxLayoutItem;
    dxLayoutItem6: TdxLayoutItem;
    dxLayoutEmptySpaceItem1: TdxLayoutEmptySpaceItem;
    dxLayoutEmptySpaceItem2: TdxLayoutEmptySpaceItem;
    cxButton_bcgs: TcxButton;
    dxLayoutItem7: TdxLayoutItem;
    cxGroupBox1: TcxGroupBox;
    cxGrid1: TcxGrid;
    TV1: TcxGridDBTableView;
    cxGridDBColumn8: TcxGridDBColumn;
    V1Column1: TcxGridDBColumn;
    cxGridDBColumn9: TcxGridDBColumn;
    V4Column3: TcxGridDBColumn;
    cxGridDBColumn10: TcxGridDBColumn;
    cxGridDBColumn11: TcxGridDBColumn;
    cxGridDBColumn12: TcxGridDBColumn;
    V4Column2: TcxGridDBColumn;
    cxGridDBColumn14: TcxGridDBColumn;
    cxGridDBColumn15: TcxGridDBColumn;
    cxGridDBColumn17: TcxGridDBColumn;
    cxGridDBColumn18: TcxGridDBColumn;
    cxGridDBColumn19: TcxGridDBColumn;
    cxGridLevel3: TcxGridLevel;
    cxGroupBox2: TcxGroupBox;
    cxGrid2: TcxGrid;
    TV2: TcxGridDBTableView;
    cxGridDBColumn2: TcxGridDBColumn;
    V2Column6: TcxGridDBColumn;
    cxGridDBColumn4: TcxGridDBColumn;
    cxGridDBColumn3: TcxGridDBColumn;
    V2Column4: TcxGridDBColumn;
    V2Column1: TcxGridDBColumn;
    V2BaooID: TcxGridDBColumn;
    V2BaooNO: TcxGridDBColumn;
    cxGridDBColumn6: TcxGridDBColumn;
    V2Column2: TcxGridDBColumn;
    V2Column3: TcxGridDBColumn;
    cxGridLevel1: TcxGridLevel;
    Tv3C_pattern: TcxGridDBColumn;
    Tv3C_ColorNo: TcxGridDBColumn;
    TV2C_pattern: TcxGridDBColumn;
    TV2C_ColorNo: TcxGridDBColumn;
    TV1C_pattern: TcxGridDBColumn;
    TV1C_colorNo: TcxGridDBColumn;
    RMRichObject1: TRMRichObject;
    RMBarCodeObject1: TRMBarCodeObject;
    CheckBox_hs: TCheckBox;
    dxLayoutItem8: TdxLayoutItem;
    dxLayoutEmptySpaceItem3: TdxLayoutEmptySpaceItem;
    procedure FormDestroy(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure edtOrderBtnClick(Sender: TObject);
    procedure btnCloseClick(Sender: TObject);
    procedure PRTColorKeyPress(Sender: TObject; var Key: Char);
    procedure N1Click(Sender: TObject);
    procedure N2Click(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure N6Click(Sender: TObject);
    procedure SmNOKeyPress(Sender: TObject; var Key: Char);
    procedure N3Click(Sender: TObject);
    procedure N4Click(Sender: TObject);
    procedure N7Click(Sender: TObject);
    procedure N5Click(Sender: TObject);
    procedure btnOKClick(Sender: TObject);
    procedure cxButton2Click(Sender: TObject);
    procedure edtPacketNoClick(Sender: TObject);
    procedure cxButton3Click(Sender: TObject);
    procedure N13Click(Sender: TObject);
    procedure N8Click(Sender: TObject);
    procedure edtOrderPropertiesButtonClick(Sender: TObject;
      AButtonIndex: Integer);
    procedure cxButton_bcgsClick(Sender: TObject);
    procedure edtOrderKeyPress(Sender: TObject; var Key: Char);
    procedure CheckBox_hsClick(Sender: TObject);
  private
    FDDBSql, FPacketId, FPacketNo: string;
    NLBName: string;

    procedure InitGridKDB(); //可打包数据
    procedure InitGridDDB(); //待打包数据
    procedure InitGridYDB(); //已打包数据
    procedure GetPacketNo();
    procedure DaBao();
    procedure HSDB();
    procedure OKDDB();
    procedure MoveCDS(CDS_Left: TclientDataSet; CDS_Right: TclientDataSet);
    procedure PrintBao(PPacketId: string);
    procedure doHsPack();
        { Private declarations }
  public
    { Public declarations }
  end;

var
  frmTradePack: TfrmTradePack;
  newh: hwnd;

implementation

uses
  U_DataLink, U_RTFun,U_globalVar, U_ZDYHelp, U_TradeClothWaitPack;
{$R *.dfm}

procedure TfrmTradePack.OKDDB();
begin
  if CDS_KDB.IsEmpty then
    Exit;
  with CDS_KDB do
  begin
    CDS_KDB.DisableControls;
    while CDS_KDB.Locate('SSel', True, []) do
    begin
      MoveCDS(CDS_KDB, CDS_DDB);
      with CDS_DDB do
      begin
        Edit;
        FieldByName('PacketId').Value := FPacketId;
        FieldByName('PacketNo').Value := FPacketNo;
      end;
      CDS_KDB.Delete;
    end;
    CDS_KDB.EnableControls;
  end;
end;

procedure TfrmTradePack.DaBao();
begin
  if CDS_DDB.IsEmpty then
    Exit;
  FDDBSql := '';
  with CDS_DDB do
  begin
    CDS_DDB.DisableControls;
    First;
    while not Eof do
    begin
      FDDBSql := FDDBSql + ' ' + 'Update Trade_Cloth_Inspect Set PacketTime=GETDATE() , PacketNo=' + QuotedStr(trim(FPacketNo)) + ',PacketId=' + QuotedStr(trim(FPacketId)) + ',PacketCode=' + QuotedStr(trim(DCode)) + ',PacketName=' + QuotedStr(trim(DName)) + 'where CIID=' + QuotedStr(trim(CDS_DDB.FieldByName('CIID').AsString));
      FDDBSql := FDDBSql + ' ' + 'Update Trade_Cloth_Stock Set PacketTime=GETDATE() , PacketNo=' + QuotedStr(trim(FPacketNo)) + ',PacketId=' + QuotedStr(trim(FPacketId)) + ',PacketCode=' + QuotedStr(trim(DCode)) + ',PacketName=' + QuotedStr(trim(DName)) + 'where CIID=' + QuotedStr(trim(CDS_DDB.FieldByName('CIID').AsString));
      Next;
    end;
    CDS_DDB.EnableControls;
  end;

  try
    ADOQueryCmd.Connection.BeginTrans;
    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add(FDDBSql);
      ExecSQL;
    end;
    ADOQueryCmd.Connection.CommitTrans;
  except
    ADOQueryCmd.Connection.RollbackTrans;
    application.MessageBox('打包失败！', '提示信息', 0);
  end;

end;

procedure TfrmTradePack.GetPacketNo();
begin
  with ADOQueryTmp do
  begin
    close;
    sql.clear;
    sql.add('select max(cast(isnull(PacketNo,''0'') as int)  )+1  as MaxPacketNo from Trade_Cloth_Stock ');
    sql.Add('where  OrderNo=' + quotedstr(trim(edtOrder.Text)));
//    ShowMessage(SQL.Text);
    open;
  end;
  FPacketNo := Trim(ADOQueryTmp.fieldbyname('MaxPacketNo').AsString);
  if FPacketNo = '' then
    FPacketNo := '1';

  edtPacketNo.Text := FPacketNo;
  if GetLSNo(ADOQueryTmp, FPacketId, 'BI', 'Trade_Cloth_Inspect', 4, 1) = False then
  begin
    Application.MessageBox('取包条码最大号失败！', '提示', 0);
    Exit;
  end;

end;

procedure TfrmTradePack.MoveCDS(CDS_Left: TclientDataSet; CDS_Right: TclientDataSet);
var
  i: Integer;
begin
  with CDS_Right do
  begin
    Append;
    for i := 0 to CDS_Left.FieldCount - 1 do
    begin
      CDS_Right.FieldByName(CDS_Left.Fields[i].FieldName).Value := CDS_Left.fieldbyname(CDS_Left.Fields[i].FieldName).Value;
    end;
    Post;
  end;
end;

procedure TfrmTradePack.PrintBao(PPacketId: string);
var
  fPrintFile: string;
  Txt, fImagePath: string;
  Moudle: THandle;
  Makebar: TMakebar;
  Mixtext: TMixtext;
begin

  with ADOQueryPrint do
  begin
    Close;
    SQL.Clear;
    SQL.Add('exec P_Trade_Insp_Prt_PackLab ' + quotedstr(PPacketId));
    Open;
  end;

  if trim(ADOQueryPrint.fieldbyName('SLabPackage').AsString)<>'' then
     NLBName := trim(ADOQueryPrint.fieldbyName('SLabPackage').AsString)
  else
    NLBName := ADOQueryPrint.fieldbyName('LabPackage').AsString;

  ExportFtErpFile(Trim(NLBName) + '.rmf', ADOQueryTmp);
  fPrintFile := ExtractFilePath(Application.ExeName) + 'Report\' + Trim(NLBName) + '.rmf';
  if not FileExists(fPrintFile) then
  begin
    Application.MessageBox(PChar('没有找' + fPrintFile), '提示', 0);
    Exit;
  end;
  if FileExists(fPrintFile) then
  begin
    RM2.LoadFromFile(fPrintFile);
    RM2.DefaultCopies := strtointdef(trim(ComboBox1.Text), 1);
    RM2.printReport;
  end;
  if FileExists(fImagePath) then
    DeleteFile(fImagePath);

end;

procedure TfrmTradePack.InitGridYDB();
begin
  if Trim(edtOrder.Text) = '' then
    Exit;
  with ADOQueryTmp do
  begin
    close;
    sql.Clear;

    sql.Add('select * from Trade_Cloth_Inspect A where isnull(PacketId,'''')<>'''' and OrderNo=' + QUOTEDSTR(Trim(edtOrder.Text)));

    open;
  end;
  SCreateCDS(ADOQueryTmp, CDS_YDB);
  SInitCDSData(ADOQueryTmp, CDS_YDB);
end;

procedure TfrmTradePack.InitGridKDB();
begin
  if Trim(edtOrder.Text) = '' then
    Exit;
  with ADOQueryTmp do
  begin
    close;
    sql.Clear;
    sql.Add('select * from Trade_Cloth_Inspect A where isnull(PacketId,'''')='''' and OrderNo=' + QUOTEDSTR(Trim(edtOrder.Text)));
//    ShowMessage(sql.Text);
    open;
  end;
  SCreateCDS(ADOQueryTmp, CDS_KDB);
  SInitCDSData(ADOQueryTmp, CDS_KDB);
end;

procedure TfrmTradePack.InitGridDDB();
begin
  //////////////////////初始化待打包界面/////////////////////
  with ADOQueryTmp do
  begin
    close;
    sql.Clear;
    sql.Add('select AA.* from Trade_Cloth_Inspect AA where 1=2');
    open;
  end;
  SCreateCDS(ADOQueryTmp, CDS_DDB);
//////////////////////初始化待打包界面/////////////////////
end;

procedure TfrmTradePack.FormDestroy(Sender: TObject);
begin
  inherited;
  frmTradePack := nil;
end;

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

  Action := cafree;
end;

procedure TfrmTradePack.FormCreate(Sender: TObject);
begin
  inherited;
  Panel2.Align:=alClient;
  cxGroupBox1.align :=alClient;
  readCxGrid('成品扫描打包Tv1', Tv1, gDllFileCaption);
  readCxGrid('成品扫描打包Tv2', Tv2, gDllFileCaption);
  readCxGrid('成品扫描打包Tv3', Tv3, gDllFileCaption);

end;

procedure TfrmTradePack.edtOrderBtnClick(Sender: TObject);
var
  FPacketId: string;
  FMainID: string;
begin
  try
    frmTradeClothWaitPack := TfrmTradeClothWaitPack.Create(self);
    with frmTradeClothWaitPack do
    begin
      if ShowModal = 1 then
      begin
        edtOrder.Text := Trim(CDS_OrderSel.fieldbyname('OrderNo').AsString);
      end;
    end;
  finally
    frmTradeClothWaitPack.Free;
  end;
  SMNO.SetFocus;
  InitGridKDB();
  InitGridYDB();
  GetPacketNo();
end;

procedure TfrmTradePack.edtOrderKeyPress(Sender: TObject; var Key: Char);
begin
  inherited;
  if key=#13 then
  begin
    InitGridKDB();
    InitGridYDB();
    GetPacketNo();
    tv3.ApplyBestFit();
  end;
end;

procedure TfrmTradePack.edtOrderPropertiesButtonClick(Sender: TObject;
  AButtonIndex: Integer);
var
  FPacketId: string;
  FMainID: string;
begin
  try
    frmTradeClothWaitPack := TfrmTradeClothWaitPack.Create(self);
    with frmTradeClothWaitPack do
    begin
      if ShowModal = 1 then
      begin
        edtOrder.Text := Trim(CDS_OrderSel.fieldbyname('OrderNo').AsString);
      end;
    end;
  finally
    frmTradeClothWaitPack.Free;
  end;
  SMNO.SetFocus;
  InitGridKDB();
  InitGridYDB();
  GetPacketNo();
  tv3.ApplyBestFit();
end;

procedure TfrmTradePack.btnCloseClick(Sender: TObject);
begin
  close;
end;

procedure TfrmTradePack.PRTColorKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
  begin
    SDofilter(ADOQueryMain, SGetFilters(Panel5, 1, 2));
    SCreateCDS(ADOQueryMain, CDS_KDB);
    SInitCDSData(ADOQueryMain, CDS_KDB);
  end;
end;

procedure TfrmTradePack.N1Click(Sender: TObject);
begin
  SelOKNo(CDS_KDB, True);
end;

procedure TfrmTradePack.N2Click(Sender: TObject);
begin
  SelOKNo(CDS_KDB, False);
end;

procedure TfrmTradePack.FormShow(Sender: TObject);
begin
  inherited;
  dxLayoutItem7.Visible:=gIsCanDesign ;
  readCxGrid('成品扫描打包Tv1', Tv1, gDllFileCaption);
  readCxGrid('成品扫描打包Tv2', Tv2, gDllFileCaption);
  readCxGrid('成品扫描打包Tv3', Tv3, gDllFileCaption);
  InitGridDDB();

  btnOk.Caption:='自动打包';

end;

procedure TfrmTradePack.N6Click(Sender: TObject);
begin

  if CDS_DDB.IsEmpty then
    Exit;
  with CDS_DDB do
  begin

    MoveCDS(CDS_DDB, CDS_KDB);
    CDS_DDB.Delete;
  end;

end;

procedure TfrmTradePack.SmNOKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
  begin
    if trim(smno.Text) = '' then
      exit;

    if trim(edtOrder.Text) = '' then
    begin
      application.MessageBox('订单号不能为空!', '提示');
      exit;
    end;
    if CDS_KDB.IsEmpty then
    begin
      application.MessageBox('订单号还未有卷信息', '提示');
      exit;
    end;
    if not CDS_KDB.Locate('ciid',Trim(SmNO.Text),[])  then
    begin
       application.MessageBox('未找到当前卷条码!', '警告');
       exit;
    end;

    if Trim(CDS_KDB.FieldByName('ciid').AsString) = Trim(SmNO.Text) then
    begin
      with CDS_KDB do
      begin
        Edit;
        FieldByName('SSel').Value := True;
        Post;
      end;
    end;

    OKDDB();
    Sleep(200);

    if StrToInt(ComboBox3.Text) = CDS_DDB.RecordCount then
    begin
      DaBao();
      with CDS_DDB do
      begin
        CDS_DDB.DisableControls;
        First;
        while not Eof do
        begin
          MoveCDS(CDS_DDB, CDS_YDB);
          Next;
        end;
        CDS_DDB.EnableControls;
        CDS_DDB.EmptyDataSet;
      end;
      if chkBBQ.Checked then
      begin
        PrintBao(FPacketId);
      end;
      GetPacketNo();
    end;

    smno.Text := '';
    smno.SetFocus;
  end;

end;

procedure TfrmTradePack.N3Click(Sender: TObject);
var
  MPacketId: string;
begin
  if CDS_YDB.Locate('SSel', True, []) = False then
  begin
    application.MessageBox('请选择打印数据！', '提示信息', MB_ICONERROR);
    exit;
  end;
  while CDS_YDB.Locate('SSel', True, []) do
  begin
    MPacketId := Trim(CDS_YDB.FieldByName('PacketId').AsString);
    PrintBao(MPacketId);
    while CDS_YDB.Locate('SSel;PacketId', VarArrayOf([True, MPacketId]), []) do
    begin
      with CDS_YDB do
      begin
        Edit;
        CDS_YDB.FieldByName('SSel').Value := False;
        Post;
      end;
    end;
  end;

end;

procedure TfrmTradePack.N4Click(Sender: TObject);
var
  NPacketId: string;
begin

  if CDS_YDB.Locate('SSel', True, []) = False then
  begin
    application.MessageBox('请选择打印数据！', '提示信息', MB_ICONERROR);
    exit;
  end;
  while CDS_YDB.Locate('SSel', True, []) do
  begin
    NPacketId := Trim(CDS_YDB.FieldByName('PacketId').AsString);
    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('Update Trade_Cloth_Inspect Set PacketLog=isnull(PacketLog,'''')+cast(PacketNo as varchar(40))+''&''+PacketId+''&''+convert(varchar,PacketTime,120)+'';'' where isnull(PacketId,'''')<>'''' and PacketId=' + QuotedStr(NPacketId));
      sql.Add('Update Trade_Cloth_Inspect Set PacketNo=null,PacketId=null  where isnull(PacketId,'''')<>'''' and PacketId=' + QuotedStr(NPacketId));
      sql.Add('Update Trade_Cloth_Stock Set PacketNo=null,PacketId=null  where isnull(PacketId,'''')<>'''' and  PacketId=' + QuotedStr(NPacketId));
      ExecSQL;
    end;

    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('insert into SY_SysLog(operor,opertime,Model,acction,opevent,result) values( ');
      sql.Add(' ' + quotedstr(trim(DName)));
      sql.Add(',getdate() ');
      sql.Add(',' + quotedstr(trim(self.Caption)));
      sql.Add(',' + quotedstr(trim('打包撤销')));
      sql.Add(',' + quotedstr(NPacketId));
      sql.Add(',' + quotedstr(trim('成功')));
      sql.Add(')');
      ExecSQL;
    end;

    while CDS_YDB.Locate('SSel;PacketId', VarArrayOf([True, NPacketId]), []) do
    begin
      with CDS_YDB do
      begin
        Edit;
        CDS_YDB.FieldByName('SSel').Value := False;
        Post;
      end;
    end;
  end;
  InitGridKDB();
  InitGridYDB();
  InitGridDDB();
  GetPacketNo();
end;

procedure TfrmTradePack.N7Click(Sender: TObject);
begin
  DaBao();
  with CDS_DDB do
  begin
    CDS_DDB.DisableControls;
    First;
    while not Eof do
    begin
      MoveCDS(CDS_DDB, CDS_YDB);
      Next;
    end;
    CDS_DDB.EnableControls;
    CDS_DDB.EmptyDataSet;
  end;
  if chkBBQ.Checked then
  begin
    PrintBao(FPacketId);
  end;

  GetPacketNo();
end;

procedure TfrmTradePack.N8Click(Sender: TObject);
begin
  SelOKNo(CDS_YDB, false);

end;

procedure TfrmTradePack.N5Click(Sender: TObject);
begin
  OKDDB();
end;

procedure TfrmTradePack.btnOKClick(Sender: TObject);
var
  i, j, K: Integer;
  MCurBatchNO, MoldBatchNO, MCurSubID, MoldSubID: string;
begin
  if not CDS_DDB.IsEmpty then
  begin
    Application.MessageBox('请清空待打包数据', '提示', 0);
    Exit;
  end;
  if CDS_KDB.IsEmpty then
    Exit;

    //混色打包
  if CheckBox_hs.Checked then
  begin
    doHsPack();
    exit;
  end;


  MCurBatchNO := '';
  MoldBatchNO := '';
  i := 0;
  j := StrToInt(ComboBox3.Text);
  K := 0;
  with CDS_KDB do
  begin
    CDS_KDB.DisableControls;
    CDS_DDB.DisableControls;
    First;
    while not Eof do
    begin
      if CDS_KDB.FieldByName('SSel').AsBoolean then
      begin
        if K = 0 then
        begin
          MoldBatchNO := Trim(CDS_KDB.FieldByName('BatchNO').AsString);
          MoldSubID := Trim(CDS_KDB.FieldByName('SubID').AsString);
        end;
        MCurBatchNO := Trim(CDS_KDB.FieldByName('BatchNO').AsString);
        MCurSubID := Trim(CDS_KDB.FieldByName('SubID').AsString);
        if j = 1 then
        begin
          MoveCDS(CDS_KDB, CDS_DDB);
          with CDS_DDB do
          begin
            Edit;
            FieldByName('PacketId').Value := FPacketId;
            FieldByName('PacketNo').Value := FPacketNo;
            Post
          end;
          DaBao();
          CDS_DDB.EmptyDataSet;
          if chkBBQ.Checked then
          begin
            PrintBao(FPacketId);
          end;
          GetPacketNo();
          Sleep(200);
          i := 0;
        end
        else
        begin
          if (MoldBatchNO <> MCurBatchNO) or (MoldSubID <> MCurSubID) then
          begin
            DaBao();
            CDS_DDB.EmptyDataSet;
            Sleep(100);
            if chkBBQ.Checked then
            begin
              PrintBao(FPacketId);
            end;

            GetPacketNo();
            MoveCDS(CDS_KDB, CDS_DDB);
            with CDS_DDB do
            begin
              Edit;
              FieldByName('PacketId').Value := FPacketId;
              FieldByName('PacketNo').Value := FPacketNo;
              Post
            end;
            i := 1;
          end
          else
          begin
            i := i + 1;

            if i <= j then
            begin
              MoveCDS(CDS_KDB, CDS_DDB);
              with CDS_DDB do
              begin
                Edit;
                FieldByName('PacketId').Value := FPacketId;
                FieldByName('PacketNo').Value := FPacketNo;
                Post
              end;
            end;

            if i = j then
            begin
              DaBao();
              CDS_DDB.EmptyDataSet;
              if chkBBQ.Checked then
              begin
                PrintBao(FPacketId);
              end;

              GetPacketNo();
              Sleep(100);
              i := 0;
            end;
          end;
        end;

        K := K + 1;
      end;

      MoldBatchNO := MCurBatchNO;
      MoldSubID := MCurSubID;
      with CDS_KDB do
      begin
        Edit;
        FieldByName('SSel').Value := false;
        Post
      end;
      Next;
    end;
    if not CDS_DDB.IsEmpty then
    begin
      DaBao();
      CDS_DDB.EmptyDataSet;
      if chkBBQ.Checked then
      begin
        PrintBao(FPacketId);
      end;

      GetPacketNo();
      Sleep(100);
      i := 0;
    end;
    CDS_DDB.EnableControls;
    CDS_KDB.EnableControls;
  end;
  InitGridKDB();
  InitGridYDB();

end;

procedure TfrmTradePack.CheckBox_hsClick(Sender: TObject);
begin
  if CheckBox_hs.Checked then
  begin
      btnOK.Caption:='混色打包';
  end
  else
  begin
     btnOK.Caption:='自动打包';
  end;

end;

procedure TfrmTradePack.cxButton2Click(Sender: TObject);
begin
  InitGridKDB();
  InitGridYDB();
  CDS_DDB.EmptyDataSet;
end;

procedure TfrmTradePack.edtPacketNoClick(Sender: TObject);
begin
  if not CDS_DDB.IsEmpty then
  begin
    Application.MessageBox('请清空待打包数据', '提示', 0);
    Exit;
  end;
end;

procedure TfrmTradePack.cxButton3Click(Sender: TObject);
begin
  edtPacketNo.Text := Edit1.Text;
  FPacketNo := Edit1.Text;
end;

procedure TfrmTradePack.cxButton_bcgsClick(Sender: TObject);
begin
  inherited;
  writeCxGrid('成品扫描打包Tv1', Tv1, gDllFileCaption);
  writeCxGrid('成品扫描打包Tv2', Tv2, gDllFileCaption);
  writeCxGrid('成品扫描打包Tv3', Tv3, gDllFileCaption);
end;

procedure TfrmTradePack.N13Click(Sender: TObject);
begin
  SelOKNo(CDS_YDB, True);
end;

//混色打包
procedure TfrmTradePack.doHsPack();
var
  rtvalues: TArray<string>;
  FOrderNO, msg: string;
  FJS, FJH: Integer;
begin
  rtvalues := SelCDSKey(CDS_KDB, ['CIID']);
  FOrderNO := edtOrder.text;
  FJS := StrToInt(ComboBox3.Text);
  FJH := StrToInt(edtPacketNo.text);

  with ADOQueryTmp do
  begin
    Close;
    Sql.Clear;
    Sql.Add('exec P_Get_HS_DaBao ');
    Sql.Add(' @CIIDs=' + quotedstr(rtvalues[0]));
    Sql.Add(',@OrderNO=' + quotedstr(Trim(FOrderNO)));
    Sql.Add(',@JS=' + inttostr(FJS));
    SQL.Add(',@JH=' + inttostr(FJH));
//      showmessage(SQL.text);
    Open;
  end;
  SCreateCDS(ADOQueryTmp, CDS_YDB);
  SInitCDSData(ADOQueryTmp, CDS_YDB);

  with ADOQueryTmp do
  begin
    Close;
    Sql.Clear;
    Sql.Add('exec P_Get_HSDaBao_TS ');
    Sql.Add(' @CIIDs=' + quotedstr(rtvalues[0]));
    Sql.Add(',@OrderNO=' + quotedstr(Trim(FOrderNO)));
    Sql.Add(',@JS=' + inttostr(FJS));
    Open;
  end;

  msg := ADOQueryTmp.FieldByName('msg').AsString;

  if Application.MessageBox(PChar(msg), '确认打包', 32 + 4) = IDYES then
  begin
    HSDB();
  end;
  GetPacketNo();
  InitGridKDB();
  InitGridYDB();


end;

///////////////////////////////
procedure TfrmTradePack.HSDB();
begin
  if CDS_YDB.IsEmpty then
    Exit;
  FDDBSql := '';
  with CDS_YDB do
  begin
    CDS_YDB.DisableControls;
    First;
    while not Eof do
    begin
      FDDBSql := FDDBSql + ' ' + 'Update Trade_Cloth_Inspect Set PacketTime=GETDATE() , PacketNo=' + QuotedStr(trim(CDS_YDB.FieldByName('PacketNo').AsString)) + ',PacketId=' + QuotedStr(trim(CDS_YDB.FieldByName('PacketId').AsString)) + ',PacketCode=' + QuotedStr(trim(DCode)) + ',PacketName=' + QuotedStr(trim(DName)) + 'where CIID=' + QuotedStr(trim(CDS_YDB.FieldByName('CIID').AsString));
      FDDBSql := FDDBSql + ' ' + 'Update Trade_Cloth_Stock Set PacketTime=GETDATE() , PacketNo=' + QuotedStr(trim(CDS_YDB.FieldByName('PacketNo').AsString)) + ',PacketId=' + QuotedStr(trim(CDS_YDB.FieldByName('PacketId').AsString)) + ',PacketCode=' + QuotedStr(trim(DCode)) + ',PacketName=' + QuotedStr(trim(DName)) + 'where CIID=' + QuotedStr(trim(CDS_YDB.FieldByName('CIID').AsString));
      Next;
    end;
    CDS_YDB.EnableControls;
  end;

  try
    ADOQueryCmd.Connection.BeginTrans;
    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add(FDDBSql);
      ExecSQL;
    end;
    ADOQueryCmd.Connection.CommitTrans;
  except
    ADOQueryCmd.Connection.RollbackTrans;
    application.MessageBox('打包失败！', '提示信息', 0);
  end;

end;

end.

