unit U_FileAutoUpdate;

interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComCtrls, ToolWin, ShlObj, cxShellCommon, cxControls,
  cxContainer, cxShellTreeView, cxShellListView, StdCtrls, BtnEdit,
  OleCtnrs, DB, ADODB,ZLib;


function ExportFtErpFile(mFileName:string;ADORead:TADOQuery):boolean;
function ExportFtErpFile10(mFileName:string;ADORead:TADOQuery):boolean;
procedure GetFileInfo(mFile:string;var mfileSize:integer;var CreationTime:tdatetime;var WriteTime:tdatetime);
function CovFileDate(Fd:_FileTime):TDateTime;
procedure UpdateFileTime(FileName:string; CreationTime, LastAccessTime, LastWriteTime:TDateTime);
implementation
uses
  U_CompressionFun;

///////////////////////////////////////////////////////
  //函数功能：从服务器下载文件；
///////////////////////////////////////////////////////
function ExportFtErpFile10(mFileName:string;ADORead:TADOQuery):boolean;
var
  Stream : TMemoryStream;
  ff:TADOBlobstream;
  mfileSize:integer;
  mCreationTime:TdateTime;
  mWriteTime:TdateTime;
  IsFileHas:boolean;
  mChildPath:string;
  mFilePath:string;
begin
  try
    result:=false;
    mChildPath:='';
    ///////////////////////////////////////////////
    //获取文件下载的子路径
    with ADORead do
    begin
      close;
      sql.Clear ;
      sql.Add('select FilePath ');
      sql.Add('from RT_FileUpdate');
      sql.Add('where FileName='+quotedStr(mFileName));
      Open;
      if RecordCount>0 then
      begin
       // if not fieldByName('valid').AsBoolean then exit;
        if trim(fieldByName('FilePath').AsString)<>'' then
          mChildPath:=trim(fieldByName('FilePath').AsString)+'\';
      end;
    end;
    //如果产品存在
    mFilePath:= ExtractFilePath(Paramstr(0))+mChildPath;
    IsFileHas:= FileExists(mFilePath+mFileName);
    if IsFileHas then
    begin
      //////////////////////////
      //获取文件信息
      GetFileInfo(mFilePath+mFileName,mfileSize,mCreationTime,mWriteTime);
    end;
    //////////////////////////////////////////
    //存在文件
    if IsFileHas then
    begin
      with ADORead do
      begin
        close;
        sql.Clear ;
        sql.Add('select count(FileName) as cnt ');
        sql.Add('from RT_FileUpdate');
        sql.Add('where FileName='+quotedStr(mFileName));
       // sql.Add('and fileEditDate>'''+formatDateTime('yyyy-MM-dd hh:mm',mWriteTime)+'''');
        sql.Add(' and DATEDIFF(minute,'+ quotedStr(formatDateTime('yyyy-MM-dd hh:mm',mWriteTime))+',fileEditDate)>0');
        Open;


        //是否存在新的文件
        if fieldByName('cnt').AsInteger>0 then
        begin
          close;
          sql.Clear ;
          sql.Add('select * ');
          sql.Add('from RT_FileUpdate');
          sql.Add('where FileName='+quotedStr(mFileName));

          Open;

          ff := TADOBlobstream.Create(fieldByName('Files') as TblobField, bmRead);
        end
        else
        begin
          exit;
        end;

       if trim(fieldByName('FilePath').AsString)<>'' then
          mChildPath:=trim(fieldByName('FilePath').AsString)+'\';
      end;
    end
    //////////////////////////////////////
    //不存在
    else
    begin
      with ADORead do
      begin
        close;
        sql.Clear ;
        sql.Add('select * ');
        sql.Add('from RT_FileUpdate');
        sql.Add('where FileName='+quotedStr(mFileName));
        Open;

        if recordCount>0 then
        begin
          ff := TADOBlobstream.Create(fieldByName('Files') as TblobField, bmRead);
        end
        else
        begin
          exit;
        end;

       if trim(fieldByName('FilePath').AsString)<>'' then
          mChildPath:=trim(fieldByName('FilePath').AsString)+'\';
      end;

    end;
    
    if  ff<>nil then
    begin
      try
        mfileName:=trim(ADORead.fieldByName('FileName').asString);
        if not DirectoryExists(ExtractFileDir(mFilePath+mfileName)) then
        ForceDirectories(ExtractFileDir(mFilePath+mfileName));
        Stream:= TMemoryStream.Create ;
        //OleContainer1.SaveToStream(Stream);
        //ADOQuery1FileContent.SaveToFile('tmp'); //数据存入临时文件
        //OleContainer1.LoadFromFile('tmp'); //从临时文件中读取OLE对象
        ff.SaveToStream(Stream);
        CompressionStream(Stream);     //数据压缩
        //OleContainer1.SaveToFile(ExtractFilePath(Paramstr(0))+mfielName)
        Stream.SaveToFile(mFilePath+mfileName); //+'\tmpFile\'

        //OleContainer1.SaveToFile('tmp');
      finally
        Stream.Free ;
        ff.free;
      end;
    end;
    UpdateFileTime(mFilePath+mfileName,ADORead.fieldByName('FileCreateDate').AsDateTime,ADORead.fieldByName('FileEditDate').AsDateTime,ADORead.fieldByName('FileEditDate').AsDateTime);
    Result:=true;
  except
    application.MessageBox(pchar('读取文件'+mfileName+'失败!'),'提示信息',0);
  end;
end;

///////////////////////////////////////////////////////
  //函数功能：从服务器下载文件；
///////////////////////////////////////////////////////
function ExportFtErpFile(mFileName:string;ADORead:TADOQuery):boolean;
var
  Stream : TMemoryStream;
  ff:TADOBlobstream;
  mfileSize:integer;
  mCreationTime:TdateTime;
  mWriteTime:TdateTime;
  IsFileHas:boolean;
  mChildPath:string;
  mFilePath:string;
begin
  try
    result:=false;
    mChildPath:='';
    ///////////////////////////////////////////////
    //获取文件下载的子路径
    with ADORead do
    begin
      close;
      sql.Clear ;
      sql.Add('select FilePath ');
      sql.Add('from RT_FileUpdate');
      sql.Add('where FileName='+quotedStr(mFileName));
      Open;
      if RecordCount>0 then
      begin
       // if not fieldByName('valid').AsBoolean then exit;
        if trim(fieldByName('FilePath').AsString)<>'' then
          mChildPath:=trim(fieldByName('FilePath').AsString)+'\';
      end;
    end;
    //如果产品存在
    mFilePath:= ExtractFilePath(Paramstr(0))+mChildPath;
    IsFileHas:= FileExists(mFilePath+mFileName);
    if IsFileHas then
    begin
      //////////////////////////
      //获取文件信息
      GetFileInfo(mFilePath+mFileName,mfileSize,mCreationTime,mWriteTime);
    end;
    //////////////////////////////////////////
    //存在文件
    if IsFileHas then
    begin
      with ADORead do
      begin
        close;
        sql.Clear ;
        sql.Add('select count(FileName) as cnt ');
        sql.Add('from RT_FileUpdate');
        sql.Add('where FileName='+quotedStr(mFileName));
       // sql.Add('and fileEditDate>'''+formatDateTime('yyyy-MM-dd hh:mm',mWriteTime)+'''');
        sql.Add(' and DATEDIFF(minute,'+ quotedStr(formatDateTime('yyyy-MM-dd hh:mm',mWriteTime))+',fileEditDate)>0');
        Open;


        //是否存在新的文件
        if fieldByName('cnt').AsInteger>0 then
        begin
          close;
          sql.Clear ;
          sql.Add('select * ');
          sql.Add('from RT_FileUpdate');
          sql.Add('where FileName='+quotedStr(mFileName));

          Open;

          ff := TADOBlobstream.Create(fieldByName('Files') as TblobField, bmRead);
        end
        else
        begin
          exit;
        end;

       if trim(fieldByName('FilePath').AsString)<>'' then
          mChildPath:=trim(fieldByName('FilePath').AsString)+'\';
      end;
    end
    //////////////////////////////////////
    //不存在
    else
    begin
      with ADORead do
      begin
        close;
        sql.Clear ;
        sql.Add('select * ');
        sql.Add('from RT_FileUpdate');
        sql.Add('where FileName='+quotedStr(mFileName));
        Open;

        if recordCount>0 then
        begin
          ff := TADOBlobstream.Create(fieldByName('Files') as TblobField, bmRead);
        end
        else
        begin
          exit;
        end;

       if trim(fieldByName('FilePath').AsString)<>'' then
          mChildPath:=trim(fieldByName('FilePath').AsString)+'\';
      end;

    end;
    
    if  ff<>nil then
    begin
      try
        mfileName:=trim(ADORead.fieldByName('FileName').asString);
        if not DirectoryExists(ExtractFileDir(mFilePath+mfileName)) then
        ForceDirectories(ExtractFileDir(mFilePath+mfileName));
        Stream:= TMemoryStream.Create ;
        //OleContainer1.SaveToStream(Stream);
        //ADOQuery1FileContent.SaveToFile('tmp'); //数据存入临时文件
        //OleContainer1.LoadFromFile('tmp'); //从临时文件中读取OLE对象
        ff.SaveToStream(Stream);
        //OleContainer1.SaveToFile(ExtractFilePath(Paramstr(0))+mfielName)
        Stream.SaveToFile(mFilePath+mfileName); //+'\tmpFile\'

        //OleContainer1.SaveToFile('tmp');
      finally
        Stream.Free ;
           ff.free;
      end;
    end;
    UpdateFileTime(mFilePath+mfileName,ADORead.fieldByName('FileCreateDate').AsDateTime,ADORead.fieldByName('FileEditDate').AsDateTime,ADORead.fieldByName('FileEditDate').AsDateTime);
    Result:=true;
  except
    application.MessageBox(pchar('读取文件'+mfileName+'失败!'),'提示信息',0);
  end;
end;
////////////////////////////////////////////////////////
  //
///////////////////////////////////////////////////////
procedure GetFileInfo(mFile:string;var mfileSize:integer;var CreationTime:tdatetime;var WriteTime:tdatetime);
var
  vSearchRec:   TSearchRec;
begin
   FindFirst(mFile,faAnyFile,vSearchRec);
   mfileSize:=vSearchRec.Size;
   CreationTime:=CovFileDate(vSearchRec.FindData.ftCreationTime);//创建时间
   //vSearchRec.FindData.ftLastAccessTime//访问时间
   WriteTime:=CovFileDate(vSearchRec.FindData.ftLastWriteTime);//修改时间
   FindClose(vSearchRec);
end;
///////////////////////////////////////////////
  //
/////////////////////////////////////////////
function CovFileDate(Fd:_FileTime):TDateTime;
var 
  Tct:_SystemTime;
  Temp:_FileTime;
begin 
  FileTimeToLocalFileTime(Fd,Temp);
  FileTimeToSystemTime(Temp,Tct);
  CovFileDate:=SystemTimeToDateTime(Tct);
end;


procedure UpdateFileTime(FileName:string; CreationTime, LastAccessTime, LastWriteTime:TDateTime);
var
  FileHnd : Integer;
  SysTime : TSystemTime;
  tTzi: TTimezoneInformation;
  FCreationTime, FLastAccessTime, FLastWriteTime: TFileTime;
begin
  GetTimezoneInformation(tTzi) ;
  CreationTime := CreationTime+Ttzi.Bias/1440;
  DateTimeToSystemTime(CreationTime,SysTime);
  SystemTimeToFileTime(SysTime,FCreationTime);
  //LastAccessTime := LastAccessTime + Ttzi.Bias/1440;
  //DateTimeToSystemTime(LastAccessTime,SysTime);
  //SystemTimeToFileTime(SysTime,FLastAccessTime);
  LastWriteTime := LastWriteTime + Ttzi.Bias/1440;
  DateTimeToSystemTime(LastWriteTime,SysTime);
  SystemTimeToFileTime(SysTime,FLastWriteTime);
  try
    FileHnd := FileOpen(FileName, fmOpenWrite or fmShareDenyNone);
    SetFileTime(FileHnd, @FCreationTime, nil, @FLastWriteTime);
  finally
    FileClose(FileHnd);
  end;
end;

end.
