unit U_CKProductBCPOutList;

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, RM_Common, RM_Class,
  RM_e_Xls, RM_Dataset, RM_System, RM_GridReport, cxCheckBox, Menus,
  MovePanel;

type
  TfrmCKProductBCPOutList = class(TForm)
    ToolBar1: TToolBar;
    TBRafresh: TToolButton;
    TBFind: TToolButton;
    TBExport: TToolButton;
    TBPrint: TToolButton;
    TBClose: TToolButton;
    Panel1: TPanel;
    ADOQueryCmd: TADOQuery;
    ADOQueryMain: TADOQuery;
    ADOQueryTemp: TADOQuery;
    DataSource1: TDataSource;
    cxGridPopupMenu1: TcxGridPopupMenu;
    Label3: TLabel;
    Label4: TLabel;
    C_CodeName: TEdit;
    C_Color: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    BegDate: TDateTimePicker;
    EndDate: TDateTimePicker;
    CDS_Main: TClientDataSet;
    Tv1: TcxGridDBTableView;
    cxGrid2Level1: TcxGridLevel;
    cxGrid2: TcxGrid;
    v2Column1: TcxGridDBColumn;
    v2Column3: TcxGridDBColumn;
    v2Column5: TcxGridDBColumn;
    v2Column6: TcxGridDBColumn;
    v1Column1: TcxGridDBColumn;
    v1Column2: TcxGridDBColumn;
    Label5: TLabel;
    orderNo: TEdit;
    Label6: TLabel;
    BCGangNO: TEdit;
    v1Column7: TcxGridDBColumn;
    v1Column6: TcxGridDBColumn;
    v1Column8: TcxGridDBColumn;
    v1Column9: TcxGridDBColumn;
    Label8: TLabel;
    MPRTKZ: TEdit;
    Label9: TLabel;
    MPRTMF: TEdit;
    Label7: TLabel;
    CPType: TComboBox;
    v1Column3: TcxGridDBColumn;
    CDS_PRT: TClientDataSet;
    RM1: TRMGridReport;
    RMDBMain: TRMDBDataSet;
    RMXLSExport1: TRMXLSExport;
    v1Column4: TcxGridDBColumn;
    Label10: TLabel;
    CkOrdNo: TEdit;
    v1Column5: TcxGridDBColumn;
    v1Column10: TcxGridDBColumn;
    RMDB_Sub: TRMDBDataSet;
    TBCKCX: TToolButton;
    v1Column11: TcxGridDBColumn;
    PopupMenu1: TPopupMenu;
    N1: TMenuItem;
    N2: TMenuItem;
    MovePanel2: TMovePanel;
    CDS_CX: TClientDataSet;
    v1CRTYPE: TcxGridDBColumn;
    v1Column12: TcxGridDBColumn;
    v1gangNo: TcxGridDBColumn;
    v1customerNoname: TcxGridDBColumn;
    TBOtCk: TToolButton;
    ADOPrint: TADOQuery;
    RMDB_MD: TRMDBDataSet;
    RMGridReport1: TRMGridReport;
    v1note: TcxGridDBColumn;
    customerNoname: TEdit;
    Label11: TLabel;
    TbNote: TToolButton;
    v1defNote1: TcxGridDBColumn;
    Label12: TLabel;
    CRTYPE: TComboBox;
    v1defstr1: TcxGridDBColumn;
    v1Column13: TcxGridDBColumn;
    Label13: TLabel;
    packNo: TEdit;
    ba: TLabel;
    Label15: TLabel;
    defNote1: TEdit;
    CheckBox1: TCheckBox;
    TBPrint1: TToolButton;
    ADOPrint1: TADOQuery;
    tbpackNo: TToolButton;
    RMXLSExport2: TRMXLSExport;
    v1Column14: TcxGridDBColumn;
    v1Column15: TcxGridDBColumn;
    v1Column16: TcxGridDBColumn;
    Label14: TLabel;
    PHYG: TEdit;
    Label16: TLabel;
    defstr2: TComboBox;
    v1defstr2: TcxGridDBColumn;
    ToolButton1: TToolButton;
    CheckBox2: TCheckBox;
    v1FHADDress: TcxGridDBColumn;
    v1Column19: TcxGridDBColumn;
    Label17: TLabel;
    v1Column18: TcxGridDBColumn;
    MJID: TEdit;
    Label18: TLabel;
    C_CodeNameZw: TEdit;
    Label19: TLabel;
    factoryName: TEdit;
    Label20: TLabel;
    SYRName: TEdit;
    Label21: TLabel;
    v1Column17: TcxGridDBColumn;
    v1Column20: TcxGridDBColumn;
    v1Column21: TcxGridDBColumn;
    dq: TEdit;
    Label22: TLabel;
    begTime: TDateTimePicker;
    endTime: TDateTimePicker;
    v1Column22: TcxGridDBColumn;
    defstr1: TEdit;
    Label23: TLabel;
    v1Column23: TcxGridDBColumn;
    batchNo: TEdit;
    Label24: TLabel;
    v1Column24: TcxGridDBColumn;
    v1Column25: TcxGridDBColumn;
    PHType: TComboBox;
    Label25: TLabel;
    BCKZ1: TEdit;
    Label26: TLabel;
    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 PRTCodeNameChange(Sender: TObject);
    procedure TBPrintClick(Sender: TObject);
    procedure orderNoChange(Sender: TObject);
    procedure N1Click(Sender: TObject);
    procedure N2Click(Sender: TObject);
    procedure TBCKCXClick(Sender: TObject);
    procedure orderNoKeyPress(Sender: TObject; var Key: Char);
    procedure TBOtCkClick(Sender: TObject);
    procedure TbNoteClick(Sender: TObject);
    procedure CheckBox1Click(Sender: TObject);
    procedure TBPrint1Click(Sender: TObject);
    procedure tbpackNoClick(Sender: TObject);
    procedure ToolButton1Click(Sender: TObject);
    procedure CheckBox2Click(Sender: TObject);

  private
    TblCprk :string;
    procedure InitGrid();
    function  YSData(Order_Main10:TClientDataSet):Boolean;
    procedure CreateTable();
    procedure DropTable();
    { Private declarations }
  public
    fckname:string;
    { Public declarations }
  end;

var
  frmCKProductBCPOutList: TfrmCKProductBCPOutList;

implementation
uses
  U_DataLink,U_Fun, U_Printckmd, U_CKProductCK, U_NoteList;

{$R *.dfm}
procedure TfrmCKProductBCPOutList.DropTable();
var
  strSQL:string;
begin
 // TblCprk := '[##CP_INOut123' + trim(DCode) + IntToStr(Handle)+formatdatetime('hhnnsszzz',time) + ']';
	//创建临时表
  strSQL := 'IF OBJECT_ID(''tempdb..' + TblCprk + ''') IS NOT NULL DROP TABLE ' + TblCprk;
	with ADOQueryCmd do
	begin
		Close;
		SQL.Clear;
		SQL.Add(strSQL);
		ExecSQL;
	end;
end;
procedure TfrmCKProductBCPOutList.CreateTable();
var
  strSQL:string;
begin
  TblCprk := '[##CP_PPack' + trim(DCode) + IntToStr(Handle)+formatdatetime('hhnnsszzz',time) + ']';
	//创建临时表
  strSQL := 'IF OBJECT_ID(''tempdb..' + TblCprk + ''') IS NOT NULL DROP TABLE ' + TblCprk + #13
			    + 'CREATE TABLE ' + TblCprk + ' ('
			    + 'MainID VARCHAR(20),'
          + 'subID  VARCHAR(20),'
          + 'BCID   Varchar(20))'#13;
	with ADOQueryCmd do
	begin
		Close;
		SQL.Clear;
		SQL.Add(strSQL);
		ExecSQL;
	end;
end;

procedure TfrmCKProductBCPOutList.FormDestroy(Sender: TObject);
begin
  frmCKProductBCPOutList:=nil;
end;

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

  Action:=caFree;
end;

procedure TfrmCKProductBCPOutList.FormCreate(Sender: TObject);
begin
  cxGrid2.Align:=alClient;

  BegDate.DateTime:=SGetServerDateTime(ADOQueryTemp);
  EndDate.DateTime:=SGetServerDateTime(ADOQueryTemp);
  
end;

procedure TfrmCKProductBCPOutList.InitGrid();
var
  mBegdate,mEnddate:string;
begin
  mbegdate:=FormatDateTime('yyyy-MM-dd',begdate.Date)+' '+FormatDateTime('HH:nn',begTime.Time);
  menddate:=FormatDateTime('yyyy-MM-dd',enddate.Date)+' '+FormatDateTime('HH:nn',endTime.Time);
  try
    ADOQueryMain.DisableControls;
    with ADOQueryMain do
    begin
      Close;
      sql.Clear;
      Filtered:=False;
      SQL.Add('select A.*,B.OrderNo,B.MPRTMF,B.MPRTKZ,B.customerNoname,C.PRTPrice,cast(A.bckz as varchar) as bckz1 ');
      sql.Add(',B.SYRName,B.FHADDress,B.lxfs');
      sql.Add(',PHYG=(select Top 1 Filler from CK_BanCP_PH X where X.phID=A.phID )');
      sql.Add(',PHType=(select Top 1 PHType from CK_BanCP_PH X where X.phID=A.phID )');
      sql.Add(',factoryName=(select factoryName from WFB_MJJY X  where X.MJID=A.MJID )');
      sql.Add(',C_CodeNameZw=(select MAX(defnote3) from KH_Zdy_Attachment X where X.ZdyName=A.C_CodeName) ');
      sql.Add(',Dq=(select TOP 1 defstr7 from KH_Zdy_Attachment X where X.ZdyName=B.customerNoName and X.Type=''KHName'') ');
      sql.Add(',zgQty=(select (case when piQty>0 then cast(Qty1/piQty as decimal(18,2)) else 0 end) from CK_SXPB_CR X where X.SPID=A.APID)');
      sql.add(' from CK_BanCP_CR A ');
      Sql.add(' LEFT join JYOrder_Main B on B.MainId=A.MainId');
      Sql.add(' LEFT join JYOrder_Sub C on C.MainID=A.mainID and C.SubId=A.SubId');
      sql.add(' where A.CRTime>='''+FormatDateTime('yyyy-MM-dd',begdate.Date)+''' ');
      sql.add(' and A.CRTime<'''+FormatDateTime('yyyy-MM-dd',enddate.Date+1)+''' ');
      SQL.Add(' and CRflag  =''出库'' ');
      IF trim(SyrName.Text)<>'' then
      sql.Add(' and A.SYRName like '+quotedstr('%'+trim(SyrName.Text)+'%'));
      IF trim(customerNoName.Text)<>'' then
      sql.Add(' and B.customerNoName like '+quotedstr('%'+trim(customerNoName.Text)+'%'));
      IF trim(fCKName)<>'' then
      sql.Add(' and A.CKName='''+trim(fckName)+''' ');
      Open;
    end;
    SCreateCDS20(ADOQueryMain,CDS_Main);
    SInitCDSData20(ADOQueryMain,CDS_Main);
  finally
    ADOQueryMain.EnableControls;
  end;
  tbfind.Click;
end;

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

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

procedure TfrmCKProductBCPOutList.TBCloseClick(Sender: TObject);
begin
  WriteCxGrid('仓库出库列表',Tv1,'成品仓库');
  Close;
end;

procedure TfrmCKProductBCPOutList.FormShow(Sender: TObject);
begin
  ReadCxGrid('仓库出库列表',Tv1,'成品仓库');
  with ADOQueryTemp do
  begin
    Close;
    sql.Clear;
    sql.Add('select Cast('''' as varchar(20)) MainId,Cast('''' as varchar(80)) KHName,Cast(0 as decimal(18,4)) PRTPrice ');
    Open;
  end;
  SCreateCDS20(ADOQueryTemp,CDS_CX);
  SInitCDSData20(ADOQueryTemp,CDS_CX);
  CDS_CX.Delete;
  //InitGrid();
  if Trim(DParameters2)='管理' then
  begin
    TBCKCX.Visible:=True;
    TBOtCk.Visible:=true;
  //  TbNote.Visible:=true;
    TBPrint.Visible:=true;
 //   tbpackNo.Visible:=true;
  end;
end;

procedure TfrmCKProductBCPOutList.TBExportClick(Sender: TObject);
begin
  if ADOQueryMain.IsEmpty then exit;
  SelExportData(Tv1,ADOQueryMain,'');
end;

procedure TfrmCKProductBCPOutList.TBFindClick(Sender: TObject);
var
  strwhere:string;
begin
  if ADOQueryMain.Active then
  begin
    strwhere:=SGetFilters(Panel1,1,2);
    IF CheckBox2.Checked then
    begin
      IF trim(strwhere)='' then
      strwhere:=strwhere+' customerNoname<>''广东门市部'' '
      else
      strwhere:=strwhere+' and customerNoname<>''广东门市部'' ';
    end;
    SDofilter(ADOQueryMain,strwhere);
    SCreateCDS20(ADOQueryMain,CDS_Main);
    SInitCDSData20(ADOQueryMain,CDS_Main);
  end;
end;

procedure TfrmCKProductBCPOutList.PRTCodeNameChange(Sender: TObject);
begin
  TBFind.Click;
end;

procedure TfrmCKProductBCPOutList.TBPrintClick(Sender: TObject);
var
  filepath,fOrderNo:string;
  i:integer;
  Txt,fImagePath:string;
   Moudle: THandle;
   Makebar:TMakebar;
   Mixtext:TMixtext;
begin
  if CDS_Main.IsEmpty then Exit;
{ if CDS_Main.Locate('ssel',true,[])=false then
  begin
    Application.MessageBox('没有选择数据!','提示',0);
    Exit;
  end;     }
  CreateTable();
{
  i:=0;
  with CDS_Main do
  begin
    DisableControls;
    first;
    while not eof do
    begin
      IF Fieldbyname('ssel').AsBoolean then
      begin
        IF trim(Fieldbyname('customerNoname').AsString)<>'广东门市部'then
        begin
          IF i=0 then fOrderNo:=trim(fieldbyname('OrderNo').AsString);
          IF (i>0) and (trim(fieldbyname('OrderNo').AsString)<> fOrderNo) then
          begin
           application.MessageBox('选择了不同的订单，不能打印！','提示信息',0);
           EnableControls;
           exit;
          end;
        end;
        with adoqueryCmd do
        begin
          Close;
	   	    SQL.Clear;
	   	    SQL.Add(' insert into '+TblCprk+'(BCID) values( ');
          SQL.Add(' '+quotedstr(trim(CDS_Main.fieldbyname('BCID').AsString)));
          sql.add(')');
	   	    execsql;
        end;
        i:=i+1;
      end;
      next;
    end;
    First;
    EnableControls;
  end;
  }

  with AdoPrint do
  begin
    close;
    sql.Clear;
    sql.Add('exec P_Do_PrintMd10 ');
    sql.Add('@mainID='+quotedstr(trim(CDS_Main.fieldbyname('MainID').AsString)));
    sql.Add(',@TblCprk='+quotedstr(trim(TblCprk)));
    sql.Add(',@flag='+quotedstr(trim('出库列表')));
    open;
  end;

  try
    filepath:=ExtractFilePath(Application.ExeName) + 'report\出库码单.rmf';
    if not FileExists(Pchar(filepath))  then
    begin
      application.MessageBox(pchar('文件['+filepath+']不存在！'),'提示信息',MB_IConError);
      exit;
    end;
        try
          Moudle:=LoadLibrary('MakeQRBarcode.dll');
          @Makebar:=GetProcAddress(Moudle,'Make');
          @Mixtext:=GetProcAddress(Moudle,'MixText');
          Txt:=Trim(AdoPrint.fieldbyname('orderNo').AsString);
          fImagePath:=ExtractFilePath(Application.ExeName)+'image\temp.bmp';
          if not DirectoryExists(pchar(ExtractFilePath(Application.ExeName)+'image')) then
          CreateDirectory(pchar(ExtractFilePath(Application.ExeName)+'image'),nil);
          if FileExists(fImagePath) then DeleteFile(fImagePath);
          Makebar(pchar(Txt),Length(Txt),3,3,0,PChar(fImagePath),3);
        except
          application.MessageBox('条形码生成失败！','提示信息',MB_ICONERROR);
          exit;
        end;
    RMVariables['QRBARCODE']:=fImagePath;
    RMVariables['dtxz'] :=FormatDateTime('yyyy-mm-dd',date());
    RMVariables['zdr'] :=trim(DName);
    RMVariables['Filler'] :=trim(CDS_Main.fieldbyname('Filler').AsString);
    RMGridReport1.LoadFromFile(filepath);
    RMGridReport1.ShowReport;
    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('update JYOrder_Main Set LbInt=isnull(Lbint,0)+1 ');
      sql.Add('where MainId='''+Trim(CDS_Main.fieldbyname('MainId').AsString)+'''');
      ExecSQL;
    end;
  finally
     DropTable();
  end;

end;

procedure TfrmCKProductBCPOutList.orderNoChange(Sender: TObject);
begin
  if Length(orderNo.Text)<4 then Exit;



end;

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

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

procedure TfrmCKProductBCPOutList.TBCKCXClick(Sender: TObject);
var
  FFMainId,FPrice:String;
    YFID,CRID:string;
begin
  if CDS_Main.IsEmpty then Exit;
  if CDS_Main.Locate('SSel',True,[])=False then
  begin
    Application.MessageBox('没有选择数据','提示',0);
    Exit;
  end;
  if Application.MessageBox('确定要撤销数据吗？','提示',32+4)<>IDYES then Exit;
  MovePanel2.Visible:=True;
  MovePanel2.Refresh;
  try
    ADOQueryCmd.Connection.BeginTrans;
    CDS_Main.DisableControls;
    with CDS_Main do
    begin
      while CDS_Main.Locate('SSel',True,[])=True do
      begin

        with ADOQueryTemp do
        begin
          Close;
          sql.Clear;
          sql.Add('select * from WFB_MJJY1 ');
          sql.Add(' where BCID='''+Trim(CDS_Main.fieldbyname('BCID').AsString)+'''');
          sql.Add(' and MJStr2=''已入库'' ');
          Open;
          if not IsEmpty then
          begin
            CDS_Main.EnableControls;
            MovePanel2.Visible:=False;
            Application.MessageBox('广东已经入库，不能撤销出库!','提示',0);
            ADOQueryCmd.Connection.RollbackTrans;
            exit;
          end;
        end;

      {  with ADOQueryTemp do
        begin
          Close;
          sql.Clear;
          sql.Add('select * from YF_Money_CR ');
          sql.Add(' where MainID='''+Trim(CDS_Main.fieldbyname('MainID').AsString)+'''');
          sql.Add(' and subID='''+Trim(CDS_Main.fieldbyname('subID').AsString)+'''');
          sql.Add(' and YFName=''销售金额'' ');
          sql.Add(' and status>=''1'' ');
          Open;
          if not IsEmpty then
          begin
            CDS_Main.EnableControls;
            MovePanel2.Visible:=False;
            Application.MessageBox('应收款没有撤销审核，不能撤销出库!','提示',0);
            ADOQueryCmd.Connection.RollbackTrans;
            exit;
          end;
        end; }

        with ADOQueryTemp do
        begin
          Close;
          sql.Clear;
          sql.Add('select * from YF_Money_CR ');
          sql.Add(' where MainID='''+Trim(CDS_Main.fieldbyname('MainID').AsString)+'''');
          sql.Add(' and subID='''+Trim(CDS_Main.fieldbyname('subID').AsString)+'''');
          sql.Add(' and YFName=''销售金额'' ');
          Open;
          if not IsEmpty then
          begin
           YFID:=Fieldbyname('YFID').AsString;
           CRID:=Fieldbyname('CRID').AsString;
          end;
        end;
        {  with ADOQueryTemp do
          begin
            Close;
            sql.Clear;
            sql.Add('select * from Contract_main ');
            sql.Add(' where conTk2='+Quotedstr(trim(CDS_Main.fieldbyname('CKOrdNo').AsString)));
            Open;
            if  not ADOQueryTemp.IsEmpty then
            begin
              CDS_Main.EnableControls;
              MovePanel2.Visible:=False;
              application.MessageBox('成品后加工中没有删除数据，不能撤销!','提示信息',0);
              ADOQueryCmd.Connection.RollbackTrans;
              exit;
            end;
          end; }
          with ADOQueryCmd do
          begin
            Close;
            sql.Clear;

            sql.Add('UPDATE CK_BanCp_KC SET KCKgQty =A.KCKgQty + B.KgQty,KCQty =A.KCQty + B.Qty,KCRollNum =1,kcstatus=''1'' ');
            sql.Add('FROM  CK_BanCp_KC A ');
            sql.Add('INNER JOIN CK_BanCP_CR B on B.CRID=A.CRID and B.CRType=''配货出库'' ');
            sql.Add('WHERE B.BCID ='+Quotedstr(trim(CDS_Main.fieldbyname('BCID').AsString)));

            sql.Add('UPDATE CK_BanCp_KC SET KCKgQty =A.KCKgQty + B.KgQty,KCQty =A.KCQty + B.Qty,KCRollNum =1 ');
            sql.Add('FROM  CK_BanCp_KC A ');
            sql.Add('INNER JOIN CK_BanCP_CR B on B.CRID=A.CRID and B.CRType<>''配货出库'' ');
            sql.Add('WHERE B.BCID ='+Quotedstr(trim(CDS_Main.fieldbyname('BCID').AsString)));

            sql.Add('update JYOrder_sub SET substatus=''2'' ');
            sql.Add('where mainID='+quotedstr(trim(CDS_Main.fieldbyname('mainID').AsString)));
            sql.Add('and subID='+quotedstr(trim(CDS_Main.fieldbyname('subID').AsString)));
            sql.Add('and isnull(substatus,''0'')>''0'' ');

            sql.Add('delete  from BP_kc ');
            sql.Add('FROM   BP_kc A ');
            sql.Add('inner join  BP_InOut B on B.KCID=A.KCID and B.CRNO=A.CRNO and B.CRFlag=''入库'' ');
            SQL.Add('where  B.frommainID='''+Trim(CDS_Main.fieldbyname('ckordNo').AsString)+''' ');
            SQL.Add('AND  B.fromSUBID='''+Trim(CDS_Main.fieldbyname('bcid').AsString)+''' ');

            sql.Add('delete  from BP_InOut ');
            SQL.Add('where  frommainID='''+Trim(CDS_Main.fieldbyname('ckordNo').AsString)+''' ');
            SQL.Add('AND  fromSUBID='''+Trim(CDS_Main.fieldbyname('bcid').AsString)+''' ');
            SQL.Add('AND  CRFlag=''入库''  ');

            sql.Add('delete  from BP_kc ');
            sql.Add('FROM   BP_kc A ');
            sql.Add('inner join  BP_InOut B on B.KCID=A.KCID and B.CRNO=A.CRNO and B.CRFlag=''入库'' ');
            SQL.Add('where  B.frommainID='''+Trim(CDS_Main.fieldbyname('ckordNo').AsString)+''' ');
            SQL.Add('AND  B.fromSUBID='''+Trim(CDS_Main.fieldbyname('bcid').AsString)+''' ');
            sql.Add('delete WFB_MJJY1 where BCID='''+Trim(CDS_Main.fieldbyname('BCID').AsString)+'''');
            sql.Add('delete CK_BanCP_CR where BCID='''+Trim(CDS_Main.fieldbyname('BCID').AsString)+'''');
      //      sql.Add('delete CK_BanCP_PH where PHID='''+Trim(CDS_Main.fieldbyname('PHID').AsString)+'''');
             sql.Add('update  CK_BanCP_PH SET P_status=''0'' where PHID='''+Trim(CDS_Main.fieldbyname('PHID').AsString)+'''');

            sql.Add('update YF_Money_CR Set Qty=(select isnull(Sum(Qty),0) from CK_BanCP_CR A  ');
            sql.Add(' where A.mainID=YF_Money_CR.mainID and  A.subiD=YF_Money_CR.subiD and A.CRType=''配货出库''  )');
            sql.Add(',PS=(select isnull(count(*),0) from CK_BanCP_CR A  ');
            sql.Add(' where A.mainID=YF_Money_CR.mainID and  A.subiD=YF_Money_CR.subiD and A.CRType=''配货出库''  )');
            sql.Add(' where YFID='''+Trim(YFID)+'''');

            sql.Add('delete from YF_Money_CR ');
            sql.Add('where YFID='''+Trim(YFID)+''' and Qty=0 ');

            sql.Add('Update YF_Money_CR Set Money=Price*Qty,BBMoney=Price*Qty*HuiLv');
            sql.Add(' where YFID='''+Trim(YFID)+'''');

            sql.Add('Update YF_Money_KC Set KCMoney=(select isnull(Sum(Money*QtyFlag),0) from YF_Money_CR A where A.CRID=YF_Money_KC.CRID)');
            sql.Add(',KCBBMoney=(select isnull(Sum(BBMoney*QtyFlag),0) from YF_Money_CR A where A.CRID=YF_Money_KC.CRID)');
            sql.Add(' where  CRID='''+Trim(CRID)+'''');

     {       sql.Add('UPdate CK_BanCP_KC Set KCKgQty=(select KgQty from CK_BanCP_CR A where  A.CRID=CK_BanCP_KC.CRID and A.CRFlag=''入库'') ');
            sql.Add(',KCQty=(select Qty from CK_BanCP_CR A where  A.CRID=CK_BanCP_KC.CRID and A.CRFlag=''入库'') ');
            SQL.Add(' where CRID='+CDS_Main.fieldbyname('CRID').AsString);  }
            ExecSQL;
          end;


          CDS_Main.Delete;
      end;
    end;
    CDS_Main.EnableControls;


    ADOQueryCmd.Connection.CommitTrans;
    MovePanel2.Visible:=False;
    Exit;
  except
    MovePanel2.Visible:=False;
    CDS_Main.EnableControls;
    ADOQueryCmd.Connection.RollbackTrans;
    Application.MessageBox('撤销异常！','提示',0);
  end;

end;
function TfrmCKProductBCPOutList.YSData(Order_Main10:TClientDataSet):Boolean;
var
  CRID,YFID,Price,PriceUnit,OrderUnit:String;
begin
  Result:=False;
  with ADOQueryTemp do
  begin
    Close;
    SQL.Clear;
    sql.Add('select Top 1 * from JYOrder_Sub Where Mainid='''+Trim(Order_Main10.fieldbyname('MainId').AsString)+'''');
    //sql.Add(' and PRTPrice>0');
    Open;
  end;
  {Price:=ADOQueryTemp.fieldbyname('PRTPrice').AsString;
  if Trim(Price)='' then
  begin
    Price:='0';
  end; }
  PriceUnit:=Trim(ADOQueryTemp.fieldbyname('PriceUnit').AsString);
  OrderUnit:=Trim(ADOQueryTemp.fieldbyname('OrderUnit').AsString);
  with ADOQueryTemp do
  begin
    Close;
    SQL.Clear;
    sql.Add('select * from YF_Money_KC where FactoryName='''+Trim(Order_Main10.fieldbyname('KHName').AsString)+'''');
    Open;
  end;
  if ADOQueryTemp.IsEmpty=False then
  begin
    CRID:=ADOQueryTemp.fieldbyname('CRID').AsString;
  end else
  begin
    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('Update YF_Money_CRID set CRID=CRID+1');
      sql.Add('select * from YF_Money_CRID ');
      Open;
    end;
    CRID:=ADOQueryCmd.fieldbyname('CRID').AsString;
    with ADOQueryCmd do
    begin
      Close;
      SQL.Clear;
      sql.Add('select * from YF_Money_KC where 1<>1');
      Open;
    end;
    with ADOQueryCmd do
    begin
      Append;
      FieldByName('CRID').Value:=StrToInt(CRID);
      FieldByName('FactoryName').Value:=Trim(Order_Main10.fieldbyname('KHName').AsString);
      FieldByName('ZdyStr1').Value:='应收收';
      Post;
    end;
  end;
  with ADOQueryTemp do
  begin
    Close;
    sql.Clear;
    sql.Add('select * from YF_Money_CR where FactoryName='''+Trim(Order_Main10.fieldbyname('KHName').AsString)+'''');
    sql.Add(' and YFTypeId='''+Trim(Order_Main10.fieldbyname('Mainid').AsString)+'''');
    sql.Add(' and Price='''+Trim(Order_Main10.fieldbyname('PRTPrice').AsString)+'''');
    Open;
  end;
  if ADOQueryTemp.IsEmpty then
  begin
    if GetLSNo(ADOQueryCmd,YFID,'CS','YF_Money_CR',3,1)=False then
    begin
      Application.MessageBox('取坯布应付最大号失败!','提示',0);
      Exit;
    end;
    {with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('select * from YF_Money_CR where 1<>1');
      Open;
    end;
    with ADOQueryCmd do
    begin
      Append;
      FieldByName('YFID').Value:=Trim(YFID);
      FieldByName('YFTypeId').Value:=Trim(Order_Main10.fieldbyname('MainId').AsString);
      FieldByName('CRID').Value:=StrToInt(CRID);
      FieldByName('Filler').Value:=Trim(DName);
      FieldByName('CRType').Value:='应收款登记';
      FieldByName('CRFlag').Value:='应收收';
      FieldByName('QtyFlag').Value:=1;
      FieldByName('FactoryName').Value:=Trim(Order_Main10.fieldbyname('KHName').AsString);
      FieldByName('CRTime').Value:=SGetServerDateTime(ADOQueryTemp);
      FieldByName('YFType').Value:='自动生成';
      FieldByName('Price').Value:=Price;
      //FieldByName('HuiLv').Value:=1;
      FieldByName('BZType').Value:=Trim(PriceUnit);
      FieldByName('QtyUnit').Value:=Trim(OrderUnit);
      FieldByName('YFName').Value:='销售金额';
      FieldByName('MainId').Value:=Trim(Order_Main10.fieldbyname('Mainid').AsString);
      Post;
    end; }
  end else
  begin
    YFID:=Trim(ADOQueryTemp.fieldbyname('YFID').AsString);
  end;
  with ADOQueryCmd do
  begin
    Close;
    sql.Clear;
    sql.Add('update YF_Money_CR Set Qty=(select isnull(Sum(Qty),0) from CK_BanCP_CR A  ');
    sql.Add(' inner join JYOrder_Sub B on A.SubId=B.SubId where');
    SQL.Add(' A.MainId=YF_Money_CR.YFTypeId and A.CRType=''正常出库'' and CPType=''正品''  ');
    SQL.Add(' and B.PRTPrice=YF_Money_CR.Price)');
    sql.Add(',PS=(select isnull(count(*),0) from CK_BanCP_CR A  ');
    sql.Add(' inner join JYOrder_Sub B on A.SubId=B.SubId where');
    SQL.Add(' A.MainId=YF_Money_CR.YFTypeId and A.CRType=''正常出库'' and CPType=''正品''  ');
    SQL.Add(' and B.PRTPrice=YF_Money_CR.Price )');
    sql.Add(' where YFTypeId='''+Trim(Order_Main10.fieldbyname('Mainid').AsString)+'''');
    sql.Add(' and Price='+Order_Main10.fieldbyname('PRTPrice').AsString);
    ExecSQL;
  end;
  with ADOQueryCmd do
  begin
    Close;
    sql.Clear;
    sql.Add('Update YF_Money_CR Set Money=cast(Price*Qty as decimal(18,0)),BBMoney=cast(Price*Qty*HuiLv as decimal(18,0)) ');
    sql.Add('where YFID='''+Trim(YFID)+'''');
    ExecSQL;
  end;
  with ADOQueryCmd do
  begin
    Close;
    sql.Clear;
    sql.Add('Update YF_Money_KC Set KCMoney=(select isnull(Sum(Money*QtyFlag),0) from YF_Money_CR A where A.CRID=YF_Money_KC.CRID)');
    sql.Add(',KCBBMoney=(select isnull(Sum(BBMoney*QtyFlag),0) from YF_Money_CR A where A.CRID=YF_Money_KC.CRID)');
    sql.Add(' where CRID='+CRID);
    ExecSQL;
  end;
  with ADOQueryTemp do
  begin
    Close;
    sql.Clear;
    sql.Add('select * from YF_Money_CR where YFId='''+Trim(YFID)+'''');
    Open;
  end;
  if ADOQueryTemp.FieldByName('Qty').Value=0 then
  begin
    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('delete from YF_Money_CR where YFID='''+Trim(YFID)+'''');
      ExecSQL;
    end;
  end;
  with ADOQueryTemp do
  begin
    Close;
    sql.Clear;
    sql.Add('select * from YF_Money_CR where CRId='+CRID);
    Open;
  end;
  if ADOQueryTemp.IsEmpty then
  begin
    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('delete from YF_Money_KC where CRId='+CRID);
      ExecSQL;
    end;
  end;


  Result:=True;
end;

procedure TfrmCKProductBCPOutList.orderNoKeyPress(Sender: TObject;
  var Key: Char);
begin
  if Key=#13 then
  begin
    if Length(Trim(orderNo.Text))<4 then Exit;
    try
    ADOQueryMain.DisableControls;
    with ADOQueryMain do
    begin
      Close;
      sql.Clear;
      Filtered:=False;
      SQL.Add('select A.*,B.OrderNo,B.MPRTMF,B.MPRTKZ,B.customerNoname,C.PRTPrice,cast(A.bckz as varchar) as bckz1 ');
      sql.Add(',B.SYRName,B.FHADDress,B.lxfs');
      sql.Add(',PHYG=(select Top 1 Filler from CK_BanCP_PH X where X.phID=A.phID )');
      sql.Add(',PHType=(select Top 1 PHType from CK_BanCP_PH X where X.phID=A.phID )');
      sql.Add(',factoryName=(select factoryName from WFB_MJJY X  where X.MJID=A.MJID )');
      sql.Add(',C_CodeNameZw=(select MAX(defnote3) from KH_Zdy_Attachment X where X.ZdyName=A.C_CodeName) ');
      sql.Add(',Dq=(select TOP 1 defstr7 from KH_Zdy_Attachment X where X.ZdyName=B.customerNoName and X.Type=''KHName'') ');
      sql.Add(',zgQty=(select (case when piQty>0 then cast(Qty1/piQty as decimal(18,2)) else 0 end) from CK_SXPB_CR X where X.SPID=A.APID)');
      sql.add('from CK_BanCP_CR A ');
      Sql.add(' LEFT join JYOrder_Main B on A.MainId=B.MainId');
      Sql.add(' LEFT join JYOrder_Sub C on A.SubId=C.SubId');
      sql.add('where B.OrderNo='+quotedstr(trim(OrderNo.Text)));
      SQL.Add(' and CRflag  =''出库'' ');
      sql.Add(' and A.CKName='''+trim(fckName)+''' ');
      Open;
    end;
    SCreateCDS20(ADOQueryMain,CDS_Main);
    SInitCDSData20(ADOQueryMain,CDS_Main);

{    with ADOQueryTemp do
    begin
      Close;
      sql.Clear;
      Filtered:=False;
      SQL.Add('select  count(distinct ckOrdNO) as cnt ');
      sql.add('from CK_BanCP_CR A ');
      Sql.add(' LEFT join JYOrder_Main B on A.MainId=B.MainId');
      Sql.add(' LEFT join JYOrder_Sub C on A.SubId=C.SubId');
      sql.add('where B.OrderNo='+quotedstr(trim(OrderNo.Text)));
      SQL.Add(' and CRflag  =''出库'' ');
      Open;
      Label17.Caption:='出库单数：0';
      if not IsEmpty then
      begin
        Label17.Caption:='出库单数：'+Fieldbyname('cnt').AsString;
      end;
    end;  }
  finally
    ADOQueryMain.EnableControls;
  end;

  end;
end;

procedure TfrmCKProductBCPOutList.TBOtCkClick(Sender: TObject);
begin
  frmCKProductCK:=TfrmCKProductCK.create(self);
  with frmCKProductCK do
  begin
   { if Trim(DParameters2)<>'管理' then
    begin
      CRType.Items.Clear;
      CRType.Items.Add('加工出库');
      CRType.Items.Add('样品出库');
      CRType.Items.Add('回修出库');
      CRType.Items.Add('盘点出库');
      CRType.Items.Add('坯布退货');
      CRType.Items.Add('损耗出库');
      CRType.ItemIndex:=0;
    end; }
    fckName:=self.fckname;
    if showmodal=1 then
    begin
      self.TBRafresh.Click;
    end;
    free;
  end;
end;

procedure TfrmCKProductBCPOutList.TbNoteClick(Sender: TObject);
var
  Fnote:string;
begin
  IF CDS_Main.IsEmpty then exit;
  frmwlnote:=Tfrmwlnote.create(self);
  with frmwlnote do
  begin
    if showmodal=1 then
    begin
      Fnote:=trim(Memo1.Text);
      with CDS_Main do
      begin
        DisableControls;
        first;
        while not eof do
        begin
          IF Fieldbyname('ssel').AsBoolean then
          begin
            with ADOQueryCmd do
            begin
              close;
              sql.Clear;
              sql.Add('update CK_Bancp_CR SET defNote1='+quotedstr(trim(Memo1.Text)));
              sql.Add('where BCID='+quotedstr(trim(CDS_Main.fieldbyname('BCID').AsString)));
              sql.Add('update BP_InOut SET defNote1='+quotedstr(trim(Memo1.Text)));
              sql.Add('where FromSubID='+quotedstr(trim(CDS_Main.fieldbyname('BCID').AsString)));
              execsql;
            end;
          end;
          next;
        end;
        First;
        EnableControls;
      end;
      TBRafresh.Click;
    end;
    close;
  end;
end;

procedure TfrmCKProductBCPOutList.CheckBox1Click(Sender: TObject);
begin
  IF  CDS_Main.IsEmpty then exit;
  with CDS_Main do
  begin
    DisableControls;
    first;
    while not eof do
    begin
      edit;
      fieldbyname('ssel').Value:=checkbox1.Checked;
      post;
      next;
    end;
    First;
    EnableControls;
  end;

end;

procedure TfrmCKProductBCPOutList.TBPrint1Click(Sender: TObject);
var
  filepath:string;
begin
  if CDS_Main.IsEmpty then exit;
 if CDS_Main.Locate('ssel',true,[])=false then
  begin
    Application.MessageBox('没有选择数据!','提示',0);
    Exit;
  end;
  CreateTable();


  with CDS_Main do
  begin
    DisableControls;
    first;
    while not eof do
    begin
      IF Fieldbyname('ssel').AsBoolean then
      begin
        with adoqueryCmd do
        begin
          Close;
	   	    SQL.Clear;
	   	    SQL.Add(' insert into '+TblCprk+'(BCID) values( ');
          SQL.Add(' '+quotedstr(trim(CDS_Main.fieldbyname('BCID').AsString)));
          sql.add(')');
	   	    execsql;
        end;
      end;
      next;
    end;
    First;
    EnableControls;
  end;

  with AdoPrint do
  begin
    close;
    sql.Clear;
    sql.Add('exec P_Get_CpCkpackList ');
    sql.Add('@mainID='+quotedstr(trim('')));
    sql.Add(',@TblCprk='+quotedstr(trim(TblCprk)));
    sql.Add(',@flag='+quotedstr(trim('1')));
    open;
  end;

   with AdoPrint1 do
  begin
    close;
    sql.Clear;
    sql.Add('exec P_Get_CpCkpackList ');
    sql.Add('@mainID='+quotedstr(trim('')));
    sql.Add(',@TblCprk='+quotedstr(trim(TblCprk)));
    sql.Add(',@flag='+quotedstr(trim('10')));
    open;
  end;

  try
    filepath:=ExtractFilePath(Application.ExeName) + 'report\成品出库单.rmf';
    if not FileExists(Pchar(filepath))  then
    begin
      application.MessageBox(pchar('文件['+filepath+']不存在！'),'提示信息',MB_IConError);
      exit;
    end;
    RMVariables['begdate'] :=FormatDateTime('yyyy-MM-dd',BegDate.DateTime)+' - '+FormatDateTime('yyyy-MM-dd',enddate.DateTime);
    RMVariables['dtxz'] :=FormatDateTime('yyyy-mm-dd',date());
    RMVariables['zdr'] :=trim(DName);
    RMVariables['Filler'] :=trim(CDS_Main.fieldbyname('Filler').AsString);
    RMGridReport1.LoadFromFile(filepath);
    RMGridReport1.ShowReport;
  finally

  end;

  DropTable();

end;

procedure TfrmCKProductBCPOutList.tbpackNoClick(Sender: TObject);
begin
  IF CDS_Main.IsEmpty then exit;
  frmwlnote:=Tfrmwlnote.create(self);
  with frmwlnote do
  begin
    frmwlnote.Caption:='添加包号';
    frmwlnote.Label1.Caption:='包号';
    if showmodal=1 then
    begin
     // Fnote:=trim(Memo1.Text);

      with CDS_Main do
      begin
        DisableControls;
        first;
        while not eof do
        begin
          IF Fieldbyname('ssel').AsBoolean then
          begin
            with ADOQueryCmd do
            begin
              close;
              sql.Clear;
              sql.Add('update CK_Bancp_CR SET packNo='+quotedstr(trim(Memo1.Text)));
              sql.Add('where BCID='+quotedstr(trim(CDS_Main.fieldbyname('BCID').AsString)));
              execsql;
            end;
          end;
          next;
        end;
        First;
        EnableControls;
      end;
      TBRafresh.Click;
    end;
    close;
  end;

end;

procedure TfrmCKProductBCPOutList.ToolButton1Click(Sender: TObject);
begin
  IF CDS_Main.IsEmpty then exit;
  frmwlnote:=Tfrmwlnote.create(self);
  with frmwlnote do
  begin
    frmwlnote.Caption:='修改货运类型';
    frmwlnote.Label1.Caption:='货运类型';
    if showmodal=1 then
    begin
      with CDS_Main do
      begin
        DisableControls;
        first;
        while not eof do
        begin
          IF Fieldbyname('ssel').AsBoolean then
          begin
            with ADOQueryCmd do
            begin
              close;
              sql.Clear;
              sql.Add('update CK_Bancp_CR SET defstr2='+quotedstr(trim(Memo1.Text)));
              sql.Add('where BCID='+quotedstr(trim(CDS_Main.fieldbyname('BCID').AsString)));
              sql.Add('update BP_InOut SET defstr2='+quotedstr(trim(Memo1.Text)));
              sql.Add('where FromSubID='+quotedstr(trim(CDS_Main.fieldbyname('BCID').AsString)));
              execsql;
            end;
          end;
          next;
        end;
        First;
        EnableControls;
      end;
      TBRafresh.Click;
    end;
    close;
  end;

end;
procedure TfrmCKProductBCPOutList.CheckBox2Click(Sender: TObject);
begin
TBFind.Click;
end;

end.
