unit U_YSMXHZlist;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, cxGraphics, cxCustomData, cxStyles, cxTL, cxMaskEdit, DB, ADODB,
  cxInplaceContainer, cxDBTL, cxControls, cxTLData, ComCtrls, ToolWin, StdCtrls,
  cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, DBClient,
  cxGridCustomTableView, cxGridTableView, cxGridDBTableView, ExtCtrls,
  cxSplitter, cxGridLevel, cxClasses, cxGridCustomView, cxGrid,
  cxGridCustomPopupMenu, cxGridPopupMenu, RM_Dataset, RM_System, RM_Common,
  RM_Class, RM_GridReport, IdBaseComponent, IdComponent, IdTCPConnection,
  IdTCPClient, IdFTP, ShellAPI, IniFiles, cxCheckBox, cxCalendar, cxButtonEdit,
  cxTextEdit, cxDropDownEdit, RM_e_Xls, cxGridBandedTableView,
  cxGridDBBandedTableView, BtnEdit, cxPC, cxLookAndFeels, cxLookAndFeelPainters,
  cxNavigator, dxBarBuiltInMenu, Menus, dxSkinsCore, dxSkinsDefaultPainters,
  dxSkinscxPCPainter;

type
  TfrmYSMXlHZist = class(TForm)
    ToolBar1: TToolBar;
    TBRafresh: TToolButton;
    TBClose: TToolButton;
    ADOQueryTemp: TADOQuery;
    ADOQueryCmd: TADOQuery;
    Panel1: TPanel;
    ToolButton2: TToolButton;
    Label1: TLabel;
    MPRTCodeName: TEdit;
    ADOQueryMain: TADOQuery;
    ToolButton1: TToolButton;
    Label3: TLabel;
    OrderNo: TEdit;
    Label6: TLabel;
    begdate: TDateTimePicker;
    Enddate: TDateTimePicker;
    cxGridPopupMenu2: TcxGridPopupMenu;
    DS_HZ: TDataSource;
    CDS_HZ: TClientDataSet;
    Label4: TLabel;
    OrdDefNote3: TComboBox;
    ToolButton3: TToolButton;
    RM1: TRMGridReport;
    RMDBDataSet1: TRMDBDataSet;
    RMXLSExport1: TRMXLSExport;
    ADOQueryPrint: TADOQuery;
    Panetime: TPanel;
    cxTabControl1: TcxTabControl;
    Label7: TLabel;
    YFGSType: TComboBox;
    cxStyleRepository1: TcxStyleRepository;
    cxStyle1: TcxStyle;
    Label8: TLabel;
    ishs: TComboBox;
    cxStyle2: TcxStyle;
    ToolButton6: TToolButton;
    ToolButton7: TToolButton;
    ComboBox1: TComboBox;
    cxGrid1: TcxGrid;
    TV1: TcxGridDBBandedTableView;
    V1Column1: TcxGridDBBandedColumn;
    V1Column2: TcxGridDBBandedColumn;
    V1Column4: TcxGridDBBandedColumn;
    V1Column5: TcxGridDBBandedColumn;
    V1Column6: TcxGridDBBandedColumn;
    V1Column7: TcxGridDBBandedColumn;
    V1Column8: TcxGridDBBandedColumn;
    V1Column9: TcxGridDBBandedColumn;
    V1Column12: TcxGridDBBandedColumn;
    V1Column15: TcxGridDBBandedColumn;
    V1Column3: TcxGridDBBandedColumn;
    V1Column10: TcxGridDBBandedColumn;
    V1Column11: TcxGridDBBandedColumn;
    V1Column13: TcxGridDBBandedColumn;
    V1Column14: TcxGridDBBandedColumn;
    V1Column16: TcxGridDBBandedColumn;
    V1Column18: TcxGridDBBandedColumn;
    V1Column21: TcxGridDBBandedColumn;
    V1Column22: TcxGridDBBandedColumn;
    V1Column23: TcxGridDBBandedColumn;
    V1Column24: TcxGridDBBandedColumn;
    V1Column25: TcxGridDBBandedColumn;
    V1Column26: TcxGridDBBandedColumn;
    TV1Column1: TcxGridDBBandedColumn;
    TV1Column2: TcxGridDBBandedColumn;
    cxGridLevel2: TcxGridLevel;
    CDS_SUB: TClientDataSet;
    DS_SUB: TDataSource;
    Label5: TLabel;
    factoryName: TBtnEditA;
    CheckBox1: TCheckBox;
    PopupMenu1: TPopupMenu;
    N1: TMenuItem;
    N2: TMenuItem;
    Panel2: TPanel;
    cxGrid2: TcxGrid;
    Tv2: TcxGridDBTableView;
    cxGridLevel1: TcxGridLevel;
    Label2: TLabel;
    Label9: TLabel;
    Label10: TLabel;
    TV1Column3: TcxGridDBBandedColumn;
    Tv2Column2: TcxGridDBColumn;
    Tv2Column3: TcxGridDBColumn;
    Tv2Column4: TcxGridDBColumn;
    TV1Column4: TcxGridDBBandedColumn;
    TV1Column5: TcxGridDBBandedColumn;
    TV1Column6: TcxGridDBBandedColumn;
    Tv2Column1: TcxGridDBColumn;
    TV1Column7: TcxGridDBBandedColumn;
    Tv2Column5: TcxGridDBColumn;
    cxSplitter1: TcxSplitter;
    Tv2Column6: TcxGridDBColumn;
    TV1Column8: TcxGridDBBandedColumn;
    procedure FormDestroy(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure TBCloseClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure TBRafreshClick(Sender: TObject);
    procedure ToolButton2Click(Sender: TObject);
    procedure P_OrderNo_YSK(Sender: TObject);
    procedure ToolButton1Click(Sender: TObject);
    procedure OrderNoChange(Sender: TObject);
    procedure MPRTCodeNameChange(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure ToolButton3Click(Sender: TObject);
    procedure factoryNameBtnClick(Sender: TObject);
    procedure V1Column9CompareRowValuesForCellMerging(Sender: TcxGridColumn; ARow1: TcxGridDataRow; AProperties1: TcxCustomEditProperties; const AValue1: Variant; ARow2: TcxGridDataRow; AProperties2: TcxCustomEditProperties; const AValue2: Variant; var AAreEqual: Boolean);
    procedure TV1CustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
    procedure cxTabControl1Change(Sender: TObject);
    procedure ToolButton4Click(Sender: TObject);
    procedure ToolButton5Click(Sender: TObject);
    procedure V1Column8PropertiesEditValueChanged(Sender: TObject);
    procedure ToolButton6Click(Sender: TObject);
    procedure ToolButton7Click(Sender: TObject);
    procedure ToolButton8Click(Sender: TObject);
    procedure V1Column11PropertiesEditValueChanged(Sender: TObject);
    procedure V1Column2PropertiesEditValueChanged(Sender: TObject);
    procedure Tv2FocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean);
    procedure N1Click(Sender: TObject);
    procedure N2Click(Sender: TObject);
    procedure factoryNameChange(Sender: TObject);
    procedure Tv2Column1PropertiesChange(Sender: TObject);
  private
    { Private declarations }

    procedure InitGrid();
    procedure InitSubGrid();
  public
    { Public declarations }
    RKFlag, FCYID: string;
    fType: string;
    canshu2, canshu1: string;
  end;

var
  frmYSMXlHZist: TfrmYSMXlHZist;

implementation

uses
  U_DataLink, U_Fun, U_ZDYHelp, U_ProductOrderNewList, U_ZdyAttachment;

{$R *.dfm}
procedure TfrmYSMXlHZist.InitSubGrid();
begin
  if CDS_HZ.IsEmpty = true then
  begin
    Exit;
  end;
  with ADOQueryTemp do
  begin
    Close;
    SQL.Clear;
    if canshu2 <> '' then
    begin
      sql.Add(' exec  P_YSSK_List_mx2_SYRNAME  ');
      sql.Add(' @begdate=' + quotedstr(Trim(CDS_HZ.fieldbyname('dzdate').AsString)));
      sql.Add(',@Enddate=' + quotedstr(Trim(FormatDateTime('yyyy-MM-dd', Enddate.DateTime + 1))));
      sql.Add(',@factoryName=' + quotedstr(Trim(CDS_HZ.fieldbyname('FACTORYNAME').AsString)));
      case cxTabControl1.TabIndex of
        0:
          begin
            sql.Add(',@flag=''全部'' ');
          end;
        1:
          begin
            sql.Add(',@flag=''已审核'' ');
          end;
      end;
      sql.Add(',@YFGSType=' + quotedstr(Trim(YFGSType.Text)));
      sql.Add(',@ISHS=' + quotedstr(Trim(ISHS.Text)));
      sql.Add(',@SYRNAME=' + quotedstr(Trim(canshu2)));
    end
    else
    begin
      sql.Add(' exec  P_YSSK_List_mx2  ');
      sql.Add(' @begdate=' + quotedstr(Trim(CDS_HZ.fieldbyname('dzdate').AsString)));
      sql.Add(',@Enddate=' + quotedstr(Trim(FormatDateTime('yyyy-MM-dd', Enddate.DateTime + 1))));
      sql.Add(',@factoryName=' + quotedstr(Trim(CDS_HZ.fieldbyname('FACTORYNAME').AsString)));
      case cxTabControl1.TabIndex of
        0:
          begin
            sql.Add(',@flag=''全部'' ');
          end;
        1:
          begin
            sql.Add(',@flag=''已审核'' ');
          end;
      end;
      sql.Add(',@YFGSType=' + quotedstr(Trim(YFGSType.Text)));
      sql.Add(',@ISHS=' + quotedstr(Trim(ISHS.Text)));
    end;
//    ShowMessage(SQL.Text);
    Open;
  end;
  SCreateCDS20(ADOQueryTemp, CDS_Sub);
  SInitCDSData20(ADOQueryTemp, CDS_Sub);

end;

procedure TfrmYSMXlHZist.InitGrid();
begin
//  if trim(factoryName.Text) = '' then
//  begin
//    application.MessageBox('请输入客户，以便提高查询速度！', '提示信息', MB_ICONERROR);
//    exit;
//  end;
//  if trim(YFGSType.Text) = '' then
//  begin
//    application.MessageBox('请选择应收类别，以便提高查询速度！', '提示信息', MB_ICONERROR);
//    exit;
//  end;

  if CheckBox1.Checked = True then
  begin
    with ADOQueryTemp do
    begin
      Close;
      SQL.Clear;
      SQL.Add('SELECT B.* FROM YF_Money_CR_Sub B inner join YF_Money_CR a on a.yfid=B.yfid WHERE ');
      sql.Add('  B.DZDATE=''' + FormatDateTime('yyyy-MM-dd', begdate.DateTime) + ''' ');

      if CANSHU1 = '业务' then
      begin
        sql.Add('	AND (A.FILLER=' + QuotedStr(Trim(dname)));
        sql.Add('OR  EXISTS(select * from YF_Money_CR_sub y  inner join JYOrder_Main u on  y.MXOrderNo=u.ORDERNO  where y.yfid=a.yfid ');
        sql.Add('	and   (ywy=' + QuotedStr(Trim(dname)));
        sql.Add('or lidan=' + QuotedStr(Trim(dname)));
        sql.Add('	) ))');
      end;

      if canshu2 <> '' then
      begin
        sql.Add('and isnull((SELECT SELLNAME FROM SalesContract_Main WHERE ConNo=(SELECT ConNo FROM JYOrder_Main WHERE OrderNo=B.MXOrderNo) ) ,A.SYRName )=' + QuotedStr(canshu2));
      end;
      Open;
    end;
    if ADOQueryTemp.IsEmpty = False then
    begin
      screen.Cursor := crsqlwait;
      Panetime.Visible := true;
      Panetime.Left := (Width - Panetime.Width) div 2;
      Panetime.top := (Height - Panetime.Height - 200) div 2;
      application.ProcessMessages;

      try
        ADOQueryMain.DisableControls;
        with ADOQueryMain do
        begin
          Close;
          SQL.Clear;
      //SUM(isnull(MXMONEY,0)*QTYFLAG)zmoney
//          SQL.Add('SELECT C.HZZNOTE,SUM(isnull(MXMONEY,0)*QTYFLAG)zmoney,SUM((case when kxtype=''定金'' then mxmoney else 0 end) )DJmoney,FactoryName,dzdate FROM YF_Money_CR A INNER JOIN YF_Money_CR_Sub B ON A.YFID=B.YFID');
//          SQL.Add('left join hznote C on B.DZDATE=C.fla and a.FactoryName=C.flb and C.fltype=''应收对账单''');
//          SQL.Add('WHERE CRFlag=''应收收'' AND B.DZFLAG=1');
//          if CheckBox1.Checked = True then
//          begin
//            sql.Add(' AND B.DZDATE=''' + FormatDateTime('yyyy-MM-dd', begdate.DateTime) + ''' ');
//          end;
//          SQL.Add('GROUP BY C.HZZNOTE,FactoryName,dzdate');
//          SQL.Add('ORDER BY DZDATE');
          SQL.Add('SELECT ZMONEY=SUM(ZMONEY),DJMONEY=SUM(DJMONEY),FactoryName,dzdate,HZZNOTE=(CASE WHEN SUM(HZZNOTE)>0 THEN ''已开票'' else ''未开票'' end )    ');
          sql.Add(',ZHSMONEY=(select sum(ZHSMONEY) from V_VIEW_HZ  b where b.FactoryName=aa.FactoryName and b.DZDATE=aa.DZDATE) ');
          SQL.Add(',SYMONEY=(sum(YSMONEY)-ISNULL((select sum(ZHSMONEY) from V_VIEW_HZ  b where b.FactoryName=aa.FactoryName and b.DZDATE=aa.DZDATE),0) )   FROM (');
          SQL.Add('SELECT zmoney=isnull(MXMONEY,0)*QTYFLAG,DJmoney=(case when kxtype=''定金'' then mxmoney else 0 end) ,');
          SQL.Add('FactoryName,dzdate ,');
          SQL.Add('YSMONEY=(CASE WHEN CRTYPE=''应收款登记'' then MXMONEY ELSE 0 END ),');
          SQL.Add('HZZNOTE=(case when isnull((select count(x.DZDNO) from FD_Invoicesub x where x.DZDNO = b.yfsid ),0)>0 then 1 else 0 end) FROM YF_Money_CR A INNER JOIN YF_Money_CR_Sub B ON A.YFID=B.YFID');
          SQL.Add('WHERE CRFlag=''应收收'' AND B.DZFLAG=1 AND SHSTATUS=''1'' ');

          if CANSHU1 = '业务' then
          begin
            sql.Add('	AND (A.FILLER=' + QuotedStr(Trim(dname)));
            sql.Add('OR  EXISTS(select * from YF_Money_CR_sub y  inner join JYOrder_Main u on  y.MXOrderNo=u.ORDERNO  where y.yfid=a.yfid ');
            sql.Add('	and   (ywy=' + QuotedStr(Trim(dname)));
            sql.Add('or lidan=' + QuotedStr(Trim(dname)));
            sql.Add('	) ))');
          end;

          if CheckBox1.Checked = True then
          begin
            sql.Add(' AND B.DZDATE=''' + FormatDateTime('yyyy-MM-dd', begdate.DateTime) + ''' ');
          end;
          if canshu2 <> '' then
          begin
            sql.Add('and isnull((SELECT SELLNAME FROM SalesContract_Main WHERE ConNo=(SELECT ConNo FROM JYOrder_Main WHERE OrderNo=B.MXOrderNo) ) ,A.SYRName )=' + QuotedStr(canshu2));
          end;
          SQL.Add(') AA ');
          SQL.Add('GROUP BY FactoryName,dzdate');
          SQL.Add('ORDER BY DZDATE');
          Open;
        end;
        SCreateCDS20(ADOQueryMain, CDS_HZ);
        SInitCDSData20(ADOQueryMain, CDS_HZ);
      finally
        ADOQueryMain.EnableControls;
//    ToolButton2.Click;
        Panetime.Visible := false;
        screen.Cursor := crdefault;
      end;
    end
    else
    begin
      application.MessageBox('该对账日期不存在数据，请重新选择！', '提示信息', MB_ICONERROR);
      exit;
    end;

  end
  else
  begin
    screen.Cursor := crsqlwait;
    Panetime.Visible := true;
    Panetime.Left := (Width - Panetime.Width) div 2;
    Panetime.top := (Height - Panetime.Height - 200) div 2;
    application.ProcessMessages;

    try
      ADOQueryMain.DisableControls;
      with ADOQueryMain do
      begin
        Close;
        SQL.Clear;

//        SQL.Add('SELECT C.HZZNOTE,SUM(isnull(MXMONEY,0)*QTYFLAG)zmoney,SUM((case when kxtype=''定金'' then mxmoney else 0 end) )DJmoney,FactoryName,dzdate FROM YF_Money_CR A INNER JOIN YF_Money_CR_Sub B ON A.YFID=B.YFID');
//        SQL.Add('left join hznote C on B.DZDATE=C.fla and a.FactoryName=C.flb and C.fltype=''应收对账单''');
//        SQL.Add('WHERE CRFlag=''应收收'' AND B.DZFLAG=1');
//        if CheckBox1.Checked = True then
//        begin
//          sql.Add(' AND B.DZDATE=''' + FormatDateTime('yyyy-MM-dd', begdate.DateTime) + ''' ');
//        end;
//        SQL.Add('GROUP BY C.HZZNOTE,FactoryName,dzdate');
//        SQL.Add('ORDER BY DZDATE');

        SQL.Add('SELECT ZMONEY=SUM(ZMONEY),DJMONEY=SUM(DJMONEY),FactoryName,dzdate,HZZNOTE=(CASE WHEN SUM(HZZNOTE)>0 THEN ''已开票'' else ''未开票'' end )    ');
        sql.Add(',ZHSMONEY=(select sum(ZHSMONEY) from V_VIEW_HZ  b where b.FactoryName=aa.FactoryName and b.DZDATE=aa.DZDATE) ');
        SQL.Add(',SYMONEY=(sum(YSMONEY)-ISNULL((select sum(ZHSMONEY) from V_VIEW_HZ  b where b.FactoryName=aa.FactoryName and b.DZDATE=aa.DZDATE),0) )   FROM (');
        SQL.Add('SELECT zmoney=isnull(MXMONEY,0)*QTYFLAG,DJmoney=(case when kxtype=''定金'' then mxmoney else 0 end) ,');
        SQL.Add('FactoryName,dzdate ,');
        SQL.Add('YSMONEY=(CASE WHEN CRTYPE=''应收款登记'' then MXMONEY ELSE 0 END ),');
        SQL.Add('HZZNOTE=(case when isnull((select count(x.DZDNO) from FD_Invoicesub x where x.DZDNO = b.yfsid ),0)>0 then 1 else 0 end) FROM YF_Money_CR A INNER JOIN YF_Money_CR_Sub B ON A.YFID=B.YFID');
        SQL.Add('WHERE CRFlag=''应收收'' AND B.DZFLAG=1 AND SHSTATUS=''1''');

        if CANSHU1 = '业务' then
        begin
          sql.Add('	AND (A.FILLER=' + QuotedStr(Trim(dname)));
          sql.Add('OR  EXISTS(select * from YF_Money_CR_sub y  inner join JYOrder_Main u on  y.MXOrderNo=u.ORDERNO  where y.yfid=a.yfid ');
          sql.Add('	and   (ywy=' + QuotedStr(Trim(dname)));
          sql.Add('or lidan=' + QuotedStr(Trim(dname)));
          sql.Add('	) ))');
        end;
        if canshu2 <> '' then
        begin
          sql.Add('and isnull((SELECT SELLNAME FROM SalesContract_Main WHERE ConNo=(SELECT ConNo FROM JYOrder_Main WHERE OrderNo=B.MXOrderNo) ) ,A.SYRName )=' + QuotedStr(canshu2));
        end;
        if CheckBox1.Checked = True then
        begin
          sql.Add(' AND B.DZDATE=''' + FormatDateTime('yyyy-MM-dd', begdate.DateTime) + ''' ');
        end;
        SQL.Add(') AA ');
        SQL.Add('GROUP BY FactoryName,dzdate');
        SQL.Add('ORDER BY DZDATE');
//        ShowMessage(SQL.Text);
        Open;
      end;
      SCreateCDS20(ADOQueryMain, CDS_HZ);
      SInitCDSData20(ADOQueryMain, CDS_HZ);
    finally
      ADOQueryMain.EnableControls;
//    ToolButton2.Click;
      Panetime.Visible := false;
      screen.Cursor := crdefault;
    end;
  end;

end;

procedure TfrmYSMXlHZist.FormDestroy(Sender: TObject);
begin
  frmYSMXlHZist := nil;
end;

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

procedure TfrmYSMXlHZist.TBCloseClick(Sender: TObject);
begin
  WriteCxBandedGrid(self.Caption + '2', Tv1, '应收汇总对账单9');
  WriteCxGrid(self.Caption + '2', Tv2, '应收汇总对账单8');
  Close;
end;

procedure TfrmYSMXlHZist.FormShow(Sender: TObject);
begin
  readCxBandedGrid(self.Caption + '2', Tv1, '应收汇总对账单9');
  readCxGrid(self.Caption + '2', Tv2, '应收汇总对账单8');

end;

procedure TfrmYSMXlHZist.TBRafreshClick(Sender: TObject);
begin
  factoryName.SetFocus;
  InitGrid();
//  InitSUBGrid();
end;

procedure TfrmYSMXlHZist.ToolButton2Click(Sender: TObject);
begin
  if ADOQueryMain.Active then
  begin
    SDofilter(ADOQueryMain, SGetFilters(Panel1, 1, 2));
    SCreateCDS20(ADOQueryMain, CDS_HZ);
    SInitCDSData20(ADOQueryMain, CDS_HZ);
  end;
end;

procedure TfrmYSMXlHZist.P_OrderNo_YSK(Sender: TObject);
begin
  ToolButton2.Click;
end;

procedure TfrmYSMXlHZist.ToolButton1Click(Sender: TObject);
begin
  if ADOQueryMain.IsEmpty then
    Exit;
  TcxGridToExcel(self.Caption + '-' + trim(factoryName.Text), cxgrid2);
end;

procedure TfrmYSMXlHZist.OrderNoChange(Sender: TObject);
begin
  if Length(Trim(OrderNo.Text)) < 3 then
    Exit;
  ToolButton2.Click;
end;

procedure TfrmYSMXlHZist.MPRTCodeNameChange(Sender: TObject);
begin
  ToolButton2.Click;
end;

procedure TfrmYSMXlHZist.FormCreate(Sender: TObject);
var
  fsj: string;
begin
  cxGrid2.Align := AlClient;
  Enddate.DateTime := SGetServerDate(ADOQueryTemp);
  begdate.DateTime := Enddate.DateTime;
  canshu2 := DParameters2;
  fsj := 'select distinct(YFGSType) name from YF_Money_CR where CRType=''应收款登记'' ';
  SInitComBoxBySql(ADOQueryCmd, YFGSType, False, fsj);
end;

procedure TfrmYSMXlHZist.ToolButton3Click(Sender: TObject);
var
  fPrintFile: string;
  Txt, fImagePath: string;
  Moudle: THandle;
  Makebar: TMakebar;
  Mixtext: TMixtext;
  wsql, wsql2: string;
  FMAINID: string;
begin

//  if CDS_HZ.IsEmpty then
//    exit;
//  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.Date);
//    RmVariables['enddate'] := FormatDateTime('yyyy-mm-dd', enddate.Date);
//    RmVariables['ishs'] := Trim(ishs.Text);
//    RMVariables['zdr'] := trim(DName);
//    RmVariables['begDate'] := FormatDateTime('yymmdd', begDate.Date) + '-' + FormatDateTime('yymmdd', enddate.Date);
//
//    RMGridReport1.LoadFromFile(filepath);
//   // RMGridReport1.PrintReport;
//    RMGridReport1.ShowReport;
//
//  finally
//
//  end;
  if CDS_SUB.IsEmpty then
    Exit;
  //if Trim(CDS_Main.fieldbyname('CRType').AsString)<>'检验出库' then Exit;
  if CDS_SUB.Locate('SSel', True, []) = False then
  begin
    Application.MessageBox('没有选择数据!', '提示', 0);
    Exit;
  end;
  ExportFtErpFile('应收款对账单.rmf', ADOQueryTemp);
  fPrintFile := ExtractFilePath(Application.ExeName) + 'report\应收款对账单.rmf';

  with CDS_SUB do
  begin

    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('delete TBSubID where DName=''' + Trim(DCode) + '''');
      ExecSQL;
    end;
    with ADOQueryCmd do
    begin
      Close;
      sql.Clear;
      sql.Add('SELECT * FROM TBSubID where 1=2 ');
      open;
    end;
    CDS_SUB.DisableControls;
    try
      ADOQueryCmd.Connection.BeginTrans;
      with CDS_SUB do
      begin
        First;
        while not Eof do
        begin
          if Fieldbyname('Ssel').AsBoolean then
          begin

            ADOQueryCmd.append;
            ADOQueryCmd.fieldbyname('SubId').Value := Trim(CDS_SUB.fieldbyname('YFSID').AsString);
            ADOQueryCmd.fieldbyname('Dname').Value := Trim(DCode);
            ADOQueryCmd.post;
          end;
          Next;
        end;
      end;
      ADOQueryCmd.Connection.CommitTrans;
    except
      ADOQueryCmd.Connection.RollbackTrans;
    end;
    CDS_SUB.EnableControls;
    with ADOQueryPrint do
    begin
      Close;
      sql.Clear;

      sql.Add(' exec  P_PRINT_YSSK_List_mx  ');
      sql.Add(' @begdate=' + quotedstr(Trim(CDS_HZ.fieldbyname('dzdate').AsString)));
      sql.Add(',@Enddate=' + quotedstr(Trim(FormatDateTime('yyyy-MM-dd', Enddate.DateTime + 1))));
      sql.Add(',@factoryName=' + quotedstr(Trim(CDS_HZ.fieldbyname('FACTORYNAME').AsString)));
      case cxTabControl1.TabIndex of
        0:
          begin
            sql.Add(',@flag=''全部'' ');
          end;
        1:
          begin
            sql.Add(',@flag=''已审核'' ');
          end;
      end;
      sql.Add(',@YFGSType=' + quotedstr(Trim(YFGSType.Text)));
      sql.Add(',@ISHS=' + quotedstr(Trim(ISHS.Text)));
      sql.add(',@spid=' + quotedstr(Trim(DCode)));
//      ShowMessage(SQL.Text);
      Open;
    end;
//    SCreateCDS20(ADOQueryPrint, CDS_HZ);
//    SInitCDSData20(ADOQueryPrint, CDS_HZ);

    RMXLSExport1 := TRMXLSExport.Create(RMXLSExport1);
    if FileExists(fPrintFile) then
    begin
      RmVariables['GSTT'] := Trim(ComboBox1.Text);
//      RmVariables['djmoney'] := Trim(CDS_HZ.fieldbyname('djmoney').AsString);
      RmVariables['YSK2'] := Tv1.DataController.Summary.FooterSummaryValues[4];
//      ShowMessage(floatToStr(Tv1.DataController.Summary.FooterSummaryValues[4]));
      RmVariables['SK'] := floatToStr(Tv1.DataController.Summary.FooterSummaryValues[5]);
      RmVariables['YK'] := trim(CDS_HZ.fieldbyname('ZMoney').asstring);
      RM1.LoadFromFile(fPrintFile);

      RM1.ShowReport;
    end
    else
    begin
      CDS_SUB.EnableControls;
      Application.MessageBox(PChar('没有找' + ExtractFilePath(Application.ExeName) + 'Report\应收款对账单.rmf'), '提示', 0);
      Exit;
    end;
//    Edit;
//    FieldByName('SSel').Value := False;
//    Post;
//    end;
  end;
  CDS_SUB.EnableControls;

end;

procedure TfrmYSMXlHZist.factoryNameBtnClick(Sender: TObject);
begin
  try
    frmZdyAttachment := TfrmZdyAttachment.Create(Application);
    with frmZdyAttachment do
    begin
      if ShowModal = 1 then
      begin
        FactoryName.Text := Trim(CDS_HZ.fieldbyname('CoName').AsString);
        InitGrid();
      end;
    end;
  finally
    frmZdyAttachment.Free;
  end;
  ToolButton2.Click;
end;

procedure TfrmYSMXlHZist.V1Column9CompareRowValuesForCellMerging(Sender: TcxGridColumn; ARow1: TcxGridDataRow; AProperties1: TcxCustomEditProperties; const AValue1: Variant; ARow2: TcxGridDataRow; AProperties2: TcxCustomEditProperties; const AValue2: Variant; var AAreEqual: Boolean);
begin
  if ARow1.Values[V1Column10.Index] = ARow2.Values[V1Column10.Index] then
    AAreEqual := True
  else
    AAreEqual := False;
end;

procedure TfrmYSMXlHZist.TV1CustomDrawCell(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
begin
  if (AViewInfo.GridRecord.Values[TcxGridDBTableView(Sender).GetColumnByFieldName('keyNO').Index]) mod 2 = 0 then
  begin
    ACanvas.Brush.Color := $EEF5FF;
  end
  else
  begin
    ACanvas.Brush.Color := $FFF8F0;
  end;

  if AViewInfo.GridRecord.Values[TV1Column2.Index] = '1' then
  begin
    ACanvas.Font.Color := clRed;
  end;

end;

procedure TfrmYSMXlHZist.cxTabControl1Change(Sender: TObject);
begin
  InitGrid();
end;

procedure TfrmYSMXlHZist.ToolButton4Click(Sender: TObject);
begin
  if CDS_HZ.IsEmpty then
    exit;

  if cxTabControl1.TabIndex <> 0 then
    Exit;

//  if CDS_HZ.Locate('ssel', true, []) = false then
//  begin
//    Application.MessageBox('没有选择数据!', '提示', 0);
//    Exit;
//  end;
  try
    ADOQueryCmd.Connection.BeginTrans;
    with CDS_HZ do
    begin

      with ADOQueryCmd do
      begin
        close;
        sql.Clear;
        sql.Add('update YF_Money_CR SET status=''1'' ');
        sql.Add('where YFID =' + quotedstr(trim(CDS_HZ.fieldbyname('YFID').AsString)));
        execsql;
      end;

    end;
    ADOQueryCmd.Connection.CommitTrans;
    InitGrid();
  except
    ADOQueryCmd.Connection.RollbackTrans;
    application.MessageBox('操作失败！', '提示信息', 0);
  end;
end;

procedure TfrmYSMXlHZist.ToolButton5Click(Sender: TObject);
begin
  if CDS_HZ.IsEmpty then
    exit;
  if cxTabControl1.TabIndex <> 1 then
    Exit;
//  if CDS_HZ.Locate('ssel', true, []) = false then
//  begin
//    Application.MessageBox('没有选择数据!', '提示', 0);
//    Exit;
//  end;
  try
    ADOQueryCmd.Connection.BeginTrans;
    with CDS_HZ do
    begin

      with ADOQueryCmd do
      begin
        close;
        sql.Clear;
        sql.Add('update YF_Money_CR SET status=''0'' ');
        sql.Add('where YFID =' + quotedstr(trim(CDS_HZ.fieldbyname('YFID').AsString)));
        execsql;
      end;

    end;
    ADOQueryCmd.Connection.CommitTrans;
    application.MessageBox('操作成功！', '提示信息', 0);
    InitGrid();
  except
    ADOQueryCmd.Connection.RollbackTrans;
    application.MessageBox('操作失败！', '提示信息', 0);
  end;
end;

procedure TfrmYSMXlHZist.V1Column8PropertiesEditValueChanged(Sender: TObject);
var
  mvalue, FFieldName: string;
begin
  if CDS_HZ.FieldByName('crtype').AsString = '应收款登记' then
  begin
    mvalue := TcxTextEdit(Sender).EditingText;
    FFieldName := Trim(Tv1.Controller.FocusedColumn.DataBinding.FilterFieldName);
    with CDS_HZ do
    begin
      Edit;
      FieldByName(FFieldName).Value := mvalue;
      Post;
    end;
    with ADOQueryCmd do
    begin
      Close;
      SQL.Clear;
      sql.Add('update YF_Money_CR_Sub set  ' + FFieldName + '=' + (Trim(mvalue)));
      sql.Add('where YFSID=' + quotedstr(Trim(CDS_HZ.fieldbyname('YFSID').AsString)));

      sql.Add('update YF_Money_CR_Sub set  ');
      sql.Add('MXMONEY=ISNULL(SHANGJIFEI,0)+ISNULL(XIAOGANGFEI,0)+ISNULL(PRICE,0)*QTY-ISNULL(YSK,0)-ISNULL(KKMONEY,0)');
      sql.Add('where YFSID=' + quotedstr(Trim(CDS_HZ.fieldbyname('YFSID').AsString)));

      sql.Add('update YF_Money_CR set  ');
      sql.Add('MONEY=(SELECT SUM(MXMONEY) FROM YF_Money_CR_Sub A WHERE A.YFID=YF_Money_CR.YFID GROUP BY YFID) ');
      sql.Add(',BBMONEY=HUILV*(SELECT SUM(MXMONEY) FROM YF_Money_CR_Sub A WHERE A.YFID=YF_Money_CR.YFID GROUP BY YFID) ');
      sql.Add('where YFID=' + quotedstr(Trim(CDS_HZ.fieldbyname('YFID').AsString)));
      ExecSQL;
    end;
    tv1.Controller.EditingController.ShowEdit();
    InitGrid();
  end;
end;

procedure TfrmYSMXlHZist.ToolButton6Click(Sender: TObject);
begin
  if CDS_HZ.IsEmpty then
    exit;

  if CDS_HZ.Locate('ssel', true, []) = false then
  begin
    Application.MessageBox('没有选择数据!', '提示', 0);
    Exit;
  end;
  try
    ADOQueryCmd.Connection.BeginTrans;
    with CDS_HZ 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 YF_Money_CR_SUB SET DZFLAG=''1'' ');
            sql.Add('where YFSID =' + quotedstr(trim(CDS_HZ.fieldbyname('YFSID').AsString)));
            execsql;
          end;
        end;
        next;
      end;
      First;
      EnableControls;
    end;
    ADOQueryCmd.Connection.CommitTrans;
    InitGrid();
  except
    ADOQueryCmd.Connection.RollbackTrans;
    application.MessageBox('操作失败！', '提示信息', 0);
  end;
end;

procedure TfrmYSMXlHZist.ToolButton7Click(Sender: TObject);
begin
  if CDS_SUB.IsEmpty then
    exit;

  if CDS_SUB.Locate('ssel', true, []) = false then
  begin
    Application.MessageBox('没有选择数据!', '提示', 0);
    Exit;
  end;
  try
    ADOQueryCmd.Connection.BeginTrans;
    with CDS_SUB 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 YF_Money_CR_SUB SET DZFLAG=NULL,DZDATE=NULL ');
            sql.Add('where YFSID =' + quotedstr(trim(CDS_SUB.fieldbyname('YFSID').AsString)));
            execsql;
          end;
        end;
        next;
      end;
      First;
      EnableControls;
    end;
    ADOQueryCmd.Connection.CommitTrans;
    InitGrid();
  except
    ADOQueryCmd.Connection.RollbackTrans;
    application.MessageBox('操作失败！', '提示信息', 0);
  end;
end;

procedure TfrmYSMXlHZist.ToolButton8Click(Sender: TObject);
var
  F1, F2, F3, F4: string;
  S1: Double;
begin
  if CDS_HZ.IsEmpty then
    exit;

  if CDS_HZ.Locate('ssel', true, []) = false then
  begin
    Application.MessageBox('没有选择数据!', '提示', 0);
    Exit;
  end;
  S1 := 0;
  try
    ADOQueryCmd.Connection.BeginTrans;
    with CDS_HZ do
    begin
      DisableControls;
      First;
      while not eof do
      begin
        if (Fieldbyname('ssel').AsBoolean) and (CDS_HZ.Fieldbyname('CRType').ASSTRING = '应收款登记') then
        begin
          F1 := factoryName.Text;
          S1 := CDS_HZ.Fieldbyname('YMxMoney').ASFLOAT + S1;
          F3 := F3 + '/' + TRIM(CDS_HZ.Fieldbyname('YFSID').ASSTRING);
        end;
        next;
      end;
      First;
      EnableControls;
    end;
    ADOQueryCmd.Connection.CommitTrans;

  except
    ADOQueryCmd.Connection.RollbackTrans;

  end;
  if S1 <> 0 then
  begin
    with ADOQueryTemp do
    begin
      close;
      sql.Clear;
      sql.Add(' exec  P_Do_SCFK  ');
      sql.Add(' @DNAME=' + quotedstr(Trim(DName)));
      sql.Add(',@MONEY=' + quotedstr(Trim(FloatToStr(S1))));
      sql.Add(' ,@DGCM=' + quotedstr(Trim(factoryName.Text)));
      sql.Add(',@FROMYFSID=' + quotedstr(Trim(F3)));
//      ShowMessage(SQL.Text);
      execsql;
    end;
    InitGrid();
  end;

end;

procedure TfrmYSMXlHZist.V1Column11PropertiesEditValueChanged(Sender: TObject);
var
  mvalue, FFieldName: string;
begin
  if CDS_HZ.FieldByName('crtype').AsString = '收款登记' then
  begin
    mvalue := TcxTextEdit(Sender).EditingText;
    FFieldName := Trim(Tv1.Controller.FocusedColumn.DataBinding.FilterFieldName);
    with CDS_HZ do
    begin
      Edit;
      FieldByName(FFieldName).Value := mvalue;
      Post;
    end;
    with ADOQueryCmd do
    begin
      Close;
      SQL.Clear;
      sql.Add('update YF_Money_CR_Sub set  ' + FFieldName + '=' + (Trim(mvalue)));
      sql.Add('where YFSID=' + quotedstr(Trim(CDS_HZ.fieldbyname('YFSID').AsString)));

      sql.Add('update YF_Money_CR set  ');
      sql.Add('MONEY=(SELECT SUM(MXMONEY) FROM YF_Money_CR_Sub A WHERE A.YFID=YF_Money_CR.YFID GROUP BY YFID) ');
      sql.Add(',BBMONEY=HUILV*(SELECT SUM(MXMONEY) FROM YF_Money_CR_Sub A WHERE A.YFID=YF_Money_CR.YFID GROUP BY YFID) ');
      sql.Add('where YFID=' + quotedstr(Trim(CDS_HZ.fieldbyname('YFID').AsString)));
      ExecSQL;
    end;
    tv1.Controller.EditingController.ShowEdit();
    InitGrid();
  end;
end;

procedure TfrmYSMXlHZist.V1Column2PropertiesEditValueChanged(Sender: TObject);
var
  mvalue, FFieldName: string;
begin
  if CDS_HZ.FieldByName('crtype').AsString = '收款登记' then
  begin
    mvalue := TcxTextEdit(Sender).EditingText;
    FFieldName := Trim(Tv1.Controller.FocusedColumn.DataBinding.FilterFieldName);
    with CDS_HZ do
    begin
      Edit;
      FieldByName(FFieldName).Value := mvalue;
      Post;
    end;
    with ADOQueryCmd do
    begin
      Close;
      SQL.Clear;
      sql.Add('update YF_Money_CR set  ' + FFieldName + '=' + QuotedStr(Trim(mvalue)));
      sql.Add('where YFID=' + quotedstr(Trim(CDS_HZ.fieldbyname('YFSID').AsString)));

      ExecSQL;
    end;
    tv1.Controller.EditingController.ShowEdit();
    InitGrid();
  end;
end;

procedure TfrmYSMXlHZist.Tv2FocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean);
begin
  InitSubGrid();
  if (CDS_HZ.IsEmpty <> True) and (CDS_SUB.IsEmpty <> True) then
  begin
    label2.Caption := '应收款：' + floatToStr(Tv1.DataController.Summary.FooterSummaryValues[4]);
    label9.Caption := '收款：' + floatToStr(Tv1.DataController.Summary.FooterSummaryValues[5]);
    label10.Caption := '余款：' + trim(CDS_HZ.fieldbyname('ZMoney').asstring);
    SelOKNo(CDS_SUB, True);
//    with CDS_SUB do
//    begin
//      First;
//      while not Eof do
//      begin
//        Edit;
//        FieldByName('ssel').Value := true;
//
//        Post;
//        Next;
//      end;
//    end;
  end;

end;

procedure TfrmYSMXlHZist.N1Click(Sender: TObject);
begin
  SelOKNo(CDS_SUB, True);
end;

procedure TfrmYSMXlHZist.N2Click(Sender: TObject);
begin
  SelOKNo(CDS_SUB, False);
end;

procedure TfrmYSMXlHZist.factoryNameChange(Sender: TObject);
begin
  ToolButton2.Click;
end;

procedure TfrmYSMXlHZist.Tv2Column1PropertiesChange(Sender: TObject);
var
  mvalue, FFieldName: string;
begin

//  mvalue := TcxTextEdit(Sender).EditingText;
//  FFieldName := Trim(Tv2.Controller.FocusedColumn.DataBinding.FilterFieldName);
//  with CDS_HZ do
//  begin
//    Edit;
//    FieldByName(FFieldName).Value := mvalue;
//    Post;
//  end;
//  with ADOQueryTemp do
//  begin
//    Close;
//    SQL.Clear;
//    sql.Add('SELECT * FROM HZNOTE WHERE FLA=' + quotedstr(Trim(CDS_HZ.fieldbyname('DZDATE').AsString)));
//    SQL.Add(' AND FLB=' + quotedstr(Trim(CDS_HZ.fieldbyname('FactoryName').AsString)));
//    SQL.Add('AND FlTYPE=''应收对账单''');
//
//    Open;
//
//  end;
//  if ADOQueryTemp.IsEmpty = True then
//  begin
//    with ADOQueryCmd do
//    begin
//      Close;
//      SQL.Clear;
//      sql.Add('insert into HZNOTE(fla,flb,hzznote,fltype) values (' + quotedstr(Trim(CDS_HZ.fieldbyname('DZDATE').AsString)));
//      sql.Add(',' + quotedstr(Trim(CDS_HZ.fieldbyname('FactoryName').AsString)));
//      sql.Add(',' + quotedstr(Trim(mvalue)));
//      sql.Add(',''应收对账单'')');
//      ExecSQL;
//    end;
//  end
//  else
//  begin
//    with ADOQueryCmd do
//    begin
//      Close;
//      SQL.Clear;
//      sql.Add('update  HZNOTE set hzznote=' + quotedstr(Trim(mvalue)));
//      sql.Add(' WHERE FLA=' + quotedstr(Trim(CDS_HZ.fieldbyname('DZDATE').AsString)));
//      SQL.Add(' AND FLB=' + quotedstr(Trim(CDS_HZ.fieldbyname('FactoryName').AsString)));
//      SQL.Add('AND FlTYPE=''应收对账单''');
//      ExecSQL;
//    end;
//  end;
//
//  tv2.Controller.EditingController.ShowEdit();
end;

end.

