unit BatchSimpleChange;

interface
uses
  Types,
  Graphics,
  StdCtrls,
  SysUtils,
  Classes,
  Dialogs,
  ExtCtrls,
  Controls,
  ScadaBase,
  Forms,
  FIBQuery, 
  pFIBQuery, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet
  ;

const
  dt_format = 'yyyy.mm.dd hh:nn:ss';
  dataformat = 'yyyymmdd';
  debug_mode = false;

type



  TBatchSimpleChange = class( TCustomScadaObject )
  public




{    procedure createKomponent(            i:integer;
                                          nm  :string;
                                          mx  :real;
                                          rz  :string;
                                          TagA, TagB,
                                          TagRecA, TagRecB : string
                                           );

 }
    url        : string;
    user, pass : string;
    Connected  : boolean;


    WES        : TpFIBDatabase;
    Trans      : TpFIBTransaction;
    qry        : TpFIBQuery;

    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure Connect;
    procedure Disconnect;

    function GetCurBatch (opc:string):integer;
    function SetCurBatch (opc:string; v:integer):integer;

    function GetDumpMain (opc, tb:string):integer;


    function AutoInc (opc:string ):integer;


    procedure ExceptionClose;
    function  IsConnected : boolean;

    procedure Init; override;
    procedure Process; override;

  end;




function createBatchSimpleChange(var parent: TPanel; DBLink, DBuser, DBpass : string): TBatchSimpleChange;
//function GetCurBatch(opc:string): integer;


implementation
uses
  RpVisualGlobal,
  TagStorage,
  Variants,
  HyperStr;



procedure Log(s: string);
var
  F: TextFile;
begin
  try
    AssignFile(F, CurDir + 'error.log');
    if not FileExists(CurDir + 'error.log') then
      rewrite(F)
    else begin
      append(F);
    end;

    Writeln(F, DateTimeToStr(now) + ': ' + s);
  finally
    try
      CloseFile(F);
    except
    end;
  end;
end;


procedure LogDB(s: string);
var
  F: TextFile;
  s2:string;
begin
  try
    DateTimeToString(s2, 'yyyy_mm_dd', now);


    if NOT DirectoryExists(CurDir + '\lg') then
       CreateDir(CurDir + '\lg');

    AssignFile(F, CurDir + '\lg\'+ s2 + '_dtik.log');
    if not FileExists(CurDir + '\lg\'+ s2 +'_dtik.log') then
      rewrite(F)
    else begin
      append(F);
    end;

    Writeln(F, DateTimeToStr(now) + ': ' + s);
  finally
    try
      CloseFile(F);
    except
    end;
  end;
end;




function createBatchSimpleChange(var parent: TPanel; DBLink, DBuser, DBpass : string): TBatchSimpleChange;
var  BatchChanger: TBatchSimpleChange;

begin

  BatchChanger := TBatchSimpleChange.Create(parent);
  BatchChanger.parent := parent;
  BatchChanger.url  := DBLink;
  BatchChanger.user := DBUser;
  BatchChanger.pass := DBPass;

  result := BatchChanger;


//--------------------------
end;


function  TBatchSimpleChange.IsConnected : boolean;
begin
 result := Connected AND WES.Connected;
end;


constructor TBatchSimpleChange.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);

  Connected := false;

  WES        := TpFIBDatabase.Create(AOwner);
  Trans      := TpFIBTransaction.Create(AOwner);
  qry        := TpFIBQuery.Create(AOwner);


end;






destructor TBatchSimpleChange.Destroy;
begin
  WES.Destroy;
  Trans.Destroy;
  qry.Destroy;

  inherited Destroy;

end;


procedure TBatchSimpleChange.Process;
begin
  inherited;
  if not rvgLogIn then Exit;
  //
end;


procedure TBatchSimpleChange.ExceptionClose;
begin
 if Qry.Transaction.Active then
   begin
     Qry.Transaction.Rollback;
     qry.Close;
     qry.FreeHandle;
   end;
end;


procedure TBatchSimpleChange.Init;
begin
  inherited;
end;

function TBatchSimpleChange.AutoInc (opc:string ):integer;
var v, nv :integer;
begin
  if NOT IsConnected then
    begin
      result := -1;
      exit;
    end;


 v := GetCurBatch (opc);

 result := 0;

 if v >= 0 then
   begin
     // В теории максимально может быть: +2147483647
     if v >= 2100000000 then nv := 1
       else nv := v + 1;

     GetDumpMain(opc, 'MAIN');
     GetDumpMain(opc, 'MAINHR');

     result := SetCurBatch (opc, nv);

   end;


end;

function TBatchSimpleChange.GetDumpMain (opc, tb:string):integer;
var sql:string;
    SavedToDB:boolean;
    c : integer;
    s, s2 : string;
begin
  if NOT IsConnected then
    begin
      result := -1;
      exit;
    end;

  SavedToDB:=false;
  sql:='SELECT IDM FROM MODULES WHERE NAME LIKE '''+opc+''' ';
  sql := 'SELECT IDM, SWBEG, SWEND, WNBEG, WNEND, DTBEG, PERTYPE FROM '+tb+' WHERE IDM IN (' + sql + ') ORDER BY IDM';

 try
   qry.SQL.text:=sql;
   qry.Transaction.StartTransaction;
   qry.ExecQuery;

   c:=0;
   LogDB ('--------------------------------------------------------------------------------');

   if qry.Eof then begin
     c := 0;
   end else begin
      c := 1;
      while not qry.Eof do
         begin
           s2 := '';
           DateTimeToString(s2, 'yyyy-mm-dd hh:nn:ss', qry.Fields[5].AsDateTime);

           s := tb +  ' IDM=' + IntToStr(qry.Fields[0].AsInteger);
           s := s + ' SWBEG=' + IntToStr(qry.Fields[1].AsInt64);
           s := s + ' SWEND=' + IntToStr(qry.Fields[2].AsInt64);
           s := s + ' WNBEG=' + IntToStr(qry.Fields[3].AsInt64);
           s := s + ' WNEND=' + IntToStr(qry.Fields[4].AsInt64);
           s := s + ' DTBEG=' + s2;
           s := s + ' PERTYPE=' + IntToStr(qry.Fields[6].AsInteger);
           LogDB (s);

           c := c + 1;
           qry.Next;
         end;
      c := c - 1;
   end;

   LogDB ('--------------------------------------------------------------------------------');
   SavedToDB := true;
   Qry.Transaction.Commit;
   qry.Close;
   qry.FreeHandle;
   result := c;

 except
   SavedToDB := false;
   log (DateTimeToStr(now) + 'Провал запроса: '+sql);
   ExceptionClose;
   result := -1;

 end;

end;





function TBatchSimpleChange.GetCurBatch (opc:string):integer;
var sql:string;
    SavedToDB:boolean;
    c, m : integer;
begin
  if NOT IsConnected then
    begin
      GetCurBatch := -1;
      exit;
    end;

  SavedToDB:=false;
  sql:='SELECT IDBATCH FROM MODULES WHERE NAME LIKE '''+opc+''' ';

 try
   qry.SQL.text:=sql;
   qry.Transaction.StartTransaction;
   qry.ExecQuery;

   c:=0;
   m:=-1;
   if qry.Eof then begin
     c := 0;
   end else begin
     c := 1;

      while not qry.Eof do
         begin
           if c=1 then  m := qry.Fields[0].AsInteger
                  else
                    begin
                      if m < qry.Fields[0].AsInteger then
                            m := qry.Fields[0].AsInteger;
                    end;



//           ProdList[cProd-1].name := qry.Fields[1].AsString;
//           ProdList[cProd-1].desc := qry.Fields[2].AsString;
//           ProdList[cProd-1].code := qry.Fields[3].AsInteger;
//           ProdList[cProd-1].isInit := true;

           c := c + 1;
           qry.Next;
         end;

       c := c - 1;
   end;


  // ShowMessage('Нашли ' + inttostr(c) + ' модулей. Максимальная партия ' + inttostr(m) );
   SavedToDB := true;

   //if debug_mode then log ('Затронуло '+inttostr(qry.rowsaffected)+' ячеек');

   //if qry.rowsaffected = 1 then SavedToDB := true;

   //if NOT SavedToDB then log ('Корректно не сработал запрос:' + sql);

   Qry.Transaction.Commit;
   qry.Close;
   qry.FreeHandle;

 except
   SavedToDB := false;
   log (DateTimeToStr(now) + 'Провал запроса: '+sql);
   ExceptionClose;

 end;



 if SavedToDB then
  begin
    if m < 0 then GetCurBatch := 0
             else GetCurBatch := m;
  end
              else GetCurBatch := -1;

end;







function TBatchSimpleChange.SetCurBatch (opc:string; v:integer):integer;
var sql:string;
    SavedToDB:boolean;
begin

  if NOT IsConnected then
    begin
      result := -1;
      exit;
    end;


  SavedToDB:=false;
  sql:='UPDATE MODULES SET IDBATCH='+inttostr(v)+' WHERE NAME LIKE '''+opc+''' ';
  result := 0;
 try
   qry.SQL.text:=sql;
   qry.Transaction.StartTransaction;
   qry.ExecQuery;
//   if debug_mode then log ('Затронуло '+inttostr(qry.rowsaffected)+' ячеек');
//   if qry.rowsaffected = 1 then SavedToDB := true;
   result := qry.rowsaffected;

   //if NOT SavedToDB then log ('Корректно не сработал запрос:' + sql);

   Qry.Transaction.Commit;
   qry.Close;
   qry.FreeHandle;

 except
   SavedToDB := false;
   result := -1;
   log (DateTimeToStr(now) + 'Провал запроса: '+sql);
   ExceptionClose;

 end;


end;



procedure TBatchSimpleChange.Connect;
var  w:boolean;
begin

  if not rvgLogIn then Exit;
  if Connected then exit;


  w := true;


  WES.DatabaseName := url;
  WES.DBParams.Clear;

  WES.DBParams.Add('lc_ctype=WIN1251');
  WES.DBParams.Add('user_name=' + user);
  WES.DBParams.Add('password=' + pass);

  WES.SQLDialect := 3;

  WES.DefaultTransaction := Trans;
  qry.Database := WES;
  qry.ParamCheck := true;
  qry.Transaction := Trans;


  if NOT w then
    begin
      Connected := false;
      exit;
    end;

  try
    WES.Connected := true;
    if WES.Connected then
       begin

       end
    else
       begin
         w := false;
       end;

  except
    WES.Connected := false;
    ShowMessage('Соединиться с весовой БД не удалось' + url);
  end;

  Connected := w;
end;

procedure TBatchSimpleChange.Disconnect;
begin
  Connected := false;
  if WES.Connected then WES.Connected := false;
end;


end.
