unit uMain;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, xmldom, XMLIntf, msxmldom, XMLDoc, ComCtrls, ShellApi,
  Menus, CLIPBrd, Buttons, System.Types, Vcl.ExtCtrls, System.UITypes, Vcl.ImgList;

type
  TfrmMain = class(TForm)
    LogLB: TListBox;
    InvoiceXMLDocument: TXMLDocument;
    ParseInvoicesBtn: TButton;
    MainProgressBar: TProgressBar;
    GetInvoicesBtn: TButton;
    UpdateOldGB: TGroupBox;
    UpdateOldFiles: TButton;
    UpdateSendingFiles: TButton;
    EnableUpdateOldCB: TCheckBox;
    UpdateOldInDBCB: TCheckBox;
    ListPopup: TPopupMenu;
    CopyInvNumberPBtn: TMenuItem;
    CopyUNNPBtn: TMenuItem;
    SearchEdit: TEdit;
    ButtonsImageList_24: TImageList;
    SearchOrganizationBtn: TButton;
    ButtonsImageList_16: TImageList;
    SearchBtn: TButton;
    SortBtn: TButton;
    CopyErrorsBtn: TButton;
    TopPanel: TPanel;
    BottomPanel: TPanel;
    MainMenu: TMainMenu;
    FilialSettingsMMBtn: TMenuItem;
    procedure FormCreate(Sender: TObject);
    procedure ParseInvoicesBtnClick(Sender: TObject);
    procedure GetInvoicesBtnClick(Sender: TObject);
    procedure UpdateOldFilesClick(Sender: TObject);
    procedure UpdateSendingFilesClick(Sender: TObject);
    procedure EnableUpdateOldCBClick(Sender: TObject);
    procedure CopyInvNumberPBtnClick(Sender: TObject);
    procedure ListPopupPopup(Sender: TObject);
    procedure LogLBMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure CopyUNNPBtnClick(Sender: TObject);
    procedure SearchEditKeyPress(Sender: TObject; var Key: Char);
    procedure SearchBtnClick(Sender: TObject);
    procedure SortBtnClick(Sender: TObject);
    procedure SearchOrganizationBtnClick(Sender: TObject);
    procedure CopyErrorsBtnClick(Sender: TObject);
    procedure FilialSettingsMMBtnClick(Sender: TObject);
  private
    { Private declarations }
    path: string;

    procedure FindFileInFolder(path, ext: string; update : Boolean);
    function Recycle(FileName: string): Boolean;
  public
    { Public declarations }
  end;

var
  frmMain: TfrmMain;


implementation

uses uDM, uParseThread, uInvPredprs;

{$R *.dfm}

function TfrmMain.Recycle(FileName: string): Boolean; //Удаление файлов из папки
var FileOp: TSHFileOpStruct;
begin
  FillChar(FileOp, SizeOf(FileOp), 0);
  FileOp.Wnd := Application.Handle;
  FileOp.wFunc := FO_DELETE;
  FileOp.pFrom := PChar(FileName);
  FileOp.fFlags := FOF_NOERRORUI or FOF_NOCONFIRMATION;
  FileOp.fAnyOperationsAborted:=true;
  Result := (SHFileOperation(FileOp) = 0);
end;

procedure TfrmMain.FilialSettingsMMBtnClick(Sender: TObject);
begin
  frmInvPredprs := TfrmInvPredprs.Create(Self);
  frmInvPredprs.ShowModal;
  frmInvPredprs.Free;
end;

procedure TfrmMain.FindFileInFolder(path, ext: string; update : Boolean);
Var SR : TSearchRec;
    Res : Integer;
begin
  Res := FindFirst(path+ext, faAnyFile, SR);

  while Res = 0 do
  begin
    if update then LogLB.Items.Add(Sr.Name)
    else LogLB.Items.Add(path+Sr.Name);

    Res := FindNext(SR);
  end;

  FindClose(SR);
end;

procedure TfrmMain.FormCreate(Sender: TObject);
var F: TextFile;
    conn: String;
begin
  if not FileExists('MdbConnect.ini') then
  begin
    MessageDlg('Файл MdbConnect.ini не найден.', mtError, [mbOk], 0);
    Application.Terminate;
    Exit;
  end;

  AssignFile(F, ExtractFilePath(Application.ExeName)+'MdbConnect.ini');
  Reset(F);
  Readln(F,conn);
  Readln(F,path);
  CloseFile(F);

  with DM do
  begin
    MDBConnection.ConnectionString := conn;
    MDBConnection.Open;

    SelNastr.Close;
    SelNastr.Open;

    if (SelNastrUNN.AsString = '600037767') then
      GetInvoicesBtn.Enabled := False
    else
      GetInvoicesBtn.Enabled := True;

    DelZero.ExecSQL;
  end;
end;

procedure TfrmMain.ParseInvoicesBtnClick(Sender: TObject);
begin
  LogLB.Clear;
  FindFileInFolder(path, '*.xml',False);
  MainProgressBar.Position:=0;

  if LogLB.Count=0 then
  begin
    MessageDlg('В папке нет файлов.', mtWarning, [mbOk], 0);
    Exit;
  end;

  MainProgressBar.Max:=LogLB.Count-1;

  ParseThread := TParseThread.Create(True, InvoiceXMLDocument, LogLB, MainProgressBar,
                                     UpdateOldInDBCB.Checked, SortBtn, CopyErrorsBtn,
                                     ParseInvoicesBtn, UpdateOldGB, EnableUpdateOldCB);
  ParseThread.FreeOnTerminate:=true;
  ParseThread.Priority:=tpNormal;
  ParseThread.Start;
end;

procedure TfrmMain.GetInvoicesBtnClick(Sender: TObject);
begin
  WinExec('receive2Dir.bat', SW_SHOW);
end;

procedure TfrmMain.UpdateOldFilesClick(Sender: TObject);
begin
  Recycle(ExtractFilePath(paramstr(0))+'recv\*.xml');
  GetInvoicesBtn.Click;
end;

procedure TfrmMain.UpdateSendingFilesClick(Sender: TObject);
var key : Integer;
begin
  LogLB.Clear;
  FindFileInFolder(ExtractFilePath(paramstr(0))+'recv3\', '*.xml',true);

  if LogLB.Count<>0 then MainProgressBar.Max:=LogLB.Count-1
  else
  begin
    MessageDlg('В папке нет файлов.', mtWarning, [mbOk], 0);
    Exit;
  end;
  
  for key:=0 to LogLB.Count-1 do
  begin
    MainProgressBar.Position:=key;

    if FileExists(ExtractFilePath(paramstr(0))+'recv\' + LogLB.Items[key]) then
    begin
      if CopyFile(PChar(ExtractFilePath(paramstr(0))+'recv\' + LogLB.Items[key]),PChar(ExtractFilePath(paramstr(0))+'recv3\' + LogLB.Items[key]),false) then
      begin
        DeleteFile(ExtractFilePath(paramstr(0))+'recv\' + LogLB.Items[key]);
        LogLB.Items[key]:=LogLB.Items[key]+' - Заменён'
      end
      else LogLB.Items[key]:=LogLB.Items[key]+' - Ошибка замены';
    end
    else LogLB.Items[key]:=LogLB.Items[key]+' - Не найден';
  end;
end;

procedure TfrmMain.CopyErrorsBtnClick(Sender: TObject);
begin
  Clipboard.AsText := LogLB.Items.Text;
end;

procedure TfrmMain.EnableUpdateOldCBClick(Sender: TObject);
begin
  UpdateOldFiles.Enabled := EnableUpdateOldCB.Checked;
  UpdateSendingFiles.Enabled := EnableUpdateOldCB.Checked;
  UpdateOldInDBCB.Enabled := EnableUpdateOldCB.Checked;
end;

procedure TfrmMain.CopyInvNumberPBtnClick(Sender: TObject);
begin
  Clipboard.AsText := Copy(LogLB.Items[LogLB.ItemIndex],1,25);
end;

procedure TfrmMain.ListPopupPopup(Sender: TObject);
begin
  if LogLB.Items.Count > 0 then
  begin
    CopyInvNumberPBtn.Enabled := True;

    if Pos('Не найдено организации с УНП', LogLB.Items[LogLB.ItemIndex])>0 then
      CopyUNNPBtn.Enabled := True
    else
      CopyUNNPBtn.Enabled := False;
  end
  else
  begin
    CopyInvNumberPBtn.Enabled := False;
    CopyUNNPBtn.Enabled := False;
  end;
end;

procedure TfrmMain.LogLBMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  LogLB.ItemIndex:=LogLB.ItemAtPos(Point(X,Y), false);
end;

procedure TfrmMain.CopyUNNPBtnClick(Sender: TObject);
begin
  Clipboard.AsText := Copy(LogLB.Items[LogLB.ItemIndex],
                           Pos('Не найдено организации с УНП',
                               LogLB.Items[LogLB.ItemIndex])+31,9);
end;

procedure TfrmMain.SearchEditKeyPress(Sender: TObject; var Key: Char);
begin
  if not CharInSet(Key, ['0'..'9', #8]) then Key:=#0;
end;

procedure TfrmMain.SearchOrganizationBtnClick(Sender: TObject);
begin
  ShellExecute(handle, 'open', 'https://kartoteka.by/', nil, nil, SW_SHOW);
end;

procedure TfrmMain.SearchBtnClick(Sender: TObject);
var i: Integer;
begin
  if LogLB.Items.Count = 0 then
  begin
    MessageDlg('Список ЭСЧФ пуст.', mtInformation, [mbOk], 0);
    Exit;
  end;

  for i:= 0 to LogLB.Items.Count-1 do
  begin
    if Pos(SearchEdit.Text, LogLB.Items[i])>0 then
    begin
      LogLB.ItemIndex := i;
      Break;
    end;  
  end;  
end;

procedure TfrmMain.SortBtnClick(Sender: TObject);
var original, unp, error : TStringList;
    i : integer;
begin
  original := TStringList.Create;
  unp := TStringList.Create;
  error := TStringList.Create;

  for i:= 0 to LogLB.Count-1 do
  begin
    if Pos('Не найдено организации с УНП', LogLB.Items[i])>0 then
      unp.Add(LogLB.Items[i])
    else
      if Pos('Не найдена исходная ЭСЧФ', LogLB.Items[i])>0 then
        original.Add(LogLB.Items[i])
      else
        error.Add(LogLB.Items[i]);
  end;

  LogLB.Clear;

  for i:=0 to unp.Count-1 do
    LogLB.Items.Add(unp[i]);

  for i:=0 to original.Count-1 do
    LogLB.Items.Add(original[i]);

  for i:=0 to error.Count-1 do
    LogLB.Items.Add(error[i]);

  unp.Free;
  original.Free;
  error.Free;
end;

end.
