unit uStatistic;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, DB, ADODB, ComCtrls, ComObj, DBGridEhGrouping,
  ToolCtrlsEh, DBGridEhToolCtrls, DynVarsEh, GridsEh, DBAxisGridsEh, DBGridEh,
  PrnDbgeh, Mask, DBCtrlsEh, DBLookupEh, CheckLst, System.UITypes, EhLibVCL,
  MemTableDataEh, DataDriverEh, MemTableEh, Vcl.ExtCtrls, System.IniFiles;

type
  TfrmStatistic = class(TForm)
    StatisticMemo: TMemo;
    statQ: TADOQuery;
    FirstPicker: TDateTimePicker;
    SecondPicker: TDateTimePicker;
    ListQ: TADOQuery;
    StatusProgressBar: TProgressBar;
    StatusMemo: TMemo;
    StatisticPageControl: TPageControl;
    StatusSheet: TTabSheet;
    PrintSheet: TTabSheet;
    InvPrintDBGridEh: TPrintDBGridEh;
    InvDBGridEh: TDBGridEh;
    PrintGridDataSource: TDataSource;
    PrintSelect: TADOQuery;
    PrintComboBox: TDBLookupComboboxEh;
    SelectPredpr: TADOQuery;
    ComboBoxDataSource: TDataSource;
    PrintSelectnumber: TLargeintField;
    PrintSelectdocNumber: TStringField;
    PrintSelectdocDate: TDateTimeField;
    PrintSelecttotalCost: TBCDField;
    PrintSelecttotalExcise: TBCDField;
    PrintSelecttotalVat: TBCDField;
    PrintSelecttotalCostVat: TBCDField;
    PrintSelectinvStatus: TWordField;
    PrintSelectStatus: TStringField;
    StatusCheckLB: TCheckListBox;
    FindForm: TBitBtn;
    PrintPredprLabel: TLabel;
    UpdateStatusBtn: TButton;
    GetStatisticBtn: TButton;
    UpdatePrintButton: TButton;
    PrintButton: TButton;
    FilterButton: TButton;
    PrintMemTableEh: TMemTableEh;
    PrintDataSetDriverEh: TDataSetDriverEh;
    PrintSelectnamePredpr: TStringField;
    PrintMemTableEhnumber: TLargeintField;
    PrintMemTableEhdocNumber: TStringField;
    PrintMemTableEhdocDate: TDateTimeField;
    PrintMemTableEhtotalCost: TBCDField;
    PrintMemTableEhtotalExcise: TBCDField;
    PrintMemTableEhtotalVat: TBCDField;
    PrintMemTableEhtotalCostVat: TBCDField;
    PrintMemTableEhinvStatus: TWordField;
    PrintMemTableEhnamePredpr: TStringField;
    PrintMemTableEhStatus: TStringField;
    AllRB: TRadioButton;
    NotFinalRB: TRadioButton;
    Bevel1: TBevel;
    FiltersPanel: TPanel;
    ShowFiltersBtn: TButton;
    StatusTopPanel: TPanel;
    StatusLeftPanel: TPanel;
    PrintTopPanel: TPanel;
    PrintBottomPanel: TPanel;
    procedure UpdateStatusBtnClick(Sender: TObject);
    procedure GetStatisticBtnClick(Sender: TObject);
    procedure UpdatePrintButtonClick(Sender: TObject);
    procedure PrintSelectCalcFields(DataSet: TDataSet);
    procedure PrintButtonClick(Sender: TObject);
    procedure FilterButtonClick(Sender: TObject);
    procedure FindFormClick(Sender: TObject);
    procedure PrintMemTableEhCalcFields(DataSet: TDataSet);
    procedure ShowFiltersBtnClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
    idPlat: Integer;
    namePredpr: string;
    procedure WMSize(var Msg: TWMSIZE); message WM_SIZE;
    procedure StatWrite(Invtype: Byte);
    function GetRecordCountByStatus(Invtype: Byte; StatusId: Integer; out count: Integer): string;
  public
    { Public declarations }
    constructor Create(AOwner: TComponent; Remote: Boolean); reintroduce;
  end;

var
  frmStatistic: TfrmStatistic;

implementation

uses
  uDM, uSearch, StatusUpdater, UtilUnit;

{$R *.dfm}

procedure TfrmStatistic.WMSize(var Msg: TWMSIZE);
begin
  if (fsModal in FormState) and (Msg.SizeType = SIZE_MINIMIZED) then
    Application.MainForm.WindowState := wsMinimized
  else
    inherited;
end;

constructor TfrmStatistic.Create(AOwner: TComponent; Remote: Boolean);
begin
  inherited Create(AOwner);
  FirstPicker.DateTime := Now;
  SecondPicker.DateTime := Now;
  SelectPredpr.Close;
  SelectPredpr.Open;

  Self.idPlat := DM.NastrPredprQidPlat.AsInteger;
  Self.namePredpr := DM.NastrPredprQnamePredpr.AsString;

  StatisticPageControl.ActivePageIndex := 0;
  UpdateStatusBtn.Enabled := not Remote;
end;

function TfrmStatistic.GetRecordCountByStatus(Invtype: Byte; StatusId: Integer; out count: Integer): string;
begin
  statQ.Close;

  case Invtype of
    0:
      statQ.SQL[statQ.SQL.Count - 1] := 'AND (history.idSender <> :idPlat)';
    1:
      statQ.SQL[statQ.SQL.Count - 1] := 'AND (history.idSender = :idPlat)';
  end;

  statQ.Parameters.ParamByName('idPlat').Value := Self.idPlat;
  statQ.Parameters.ParamByName('invStatus').Value := StatusId;
  statQ.Parameters.ParamByName('First').Value := DateToStr(FirstPicker.Date);
  statQ.Parameters.ParamByName('Second').Value := DateToStr(SecondPicker.Date);
  statQ.Open;

  count := count + statQ.fieldByName('COUNT').AsInteger;

  if not statQ.IsEmpty then
    Result := statQ.fieldByName('COUNT').AsString
  else
    Result := 'Ошибка получения статуса из базы';
end;

procedure TfrmStatistic.ShowFiltersBtnClick(Sender: TObject);
begin
  if FiltersPanel.Visible then
  begin
    ShowFiltersBtn.Caption := 'Показать фильтры';
    ShowFiltersBtn.ImageIndex := 15;
    FiltersPanel.Visible := False;
  end
  else
  begin
    ShowFiltersBtn.Caption := 'Скрыть фильтры';
    ShowFiltersBtn.ImageIndex := 14;
    FiltersPanel.Visible := True;
  end;
end;

procedure TfrmStatistic.StatWrite(Invtype: Byte);
var
  total_count: Integer;
begin
  //Процедура вывода количества ЭСЧФ по статусу
  total_count := 0;

  with StatisticMemo.Lines do
  begin
    case Invtype of
      0:
        Add('Поступившие:');
      1:
        Add('Выставленные:');
    end;

    Add('   В разработке - ' + GetRecordCountByStatus(Invtype, 1, total_count));
    Add('   Выставлен - ' + GetRecordCountByStatus(Invtype, 3, total_count));
    Add('   На согласовании - ' + GetRecordCountByStatus(Invtype, 4, total_count));
    Add('   Выставлен. Подписан получателем - ' + GetRecordCountByStatus(Invtype, 5, total_count));
    Add('   Аннулирован - ' + GetRecordCountByStatus(Invtype, 6, total_count));
    Add('   Выставлен. Аннулирован поставщиком - ' + GetRecordCountByStatus(Invtype, 7, total_count));
    Add('   Не найдено - ' + GetRecordCountByStatus(Invtype, 8, total_count));
    Add('   Нет данных - ' + GetRecordCountByStatus(Invtype, 0, total_count));

    if Invtype = 1 then
      Add('   Ошибка при отправке - ' + GetRecordCountByStatus(Invtype, 9, total_count));

    Add('Итого: ' + IntToStr(total_count));
  end;
end;

procedure TfrmStatistic.UpdateStatusBtnClick(Sender: TObject);
var
  ThreadStatus: TThreadStatus;
  Ini: Tinifile;
  Config: TConfig;
begin
  StatusMemo.Clear;

  with ListQ do
  begin
    Close;
    Parameters.ParamByName('First').Value := DateToStr(FirstPicker.Date);
    Parameters.ParamByName('Second').Value := DateToStr(SecondPicker.Date);

    if AllRB.Checked then
      SQL[SQL.Count - 1] := 'AND (ISNULL(h.invStatus,0) not in (6,7))';

    if NotFinalRB.Checked then
      SQL[SQL.Count - 1] := 'AND (ISNULL(h.invStatus,0) not in (5,6,7))';

    Open;
  end;

  Ini := TiniFile.Create(extractfilepath(paramstr(0)) + 'Gear.ini');
  Config.ProxyIp := Ini.ReadString('Proxy', 'Ip', '');
  Config.ProxySocket := Ini.ReadString('Proxy', 'Socket', '');
  Config.ProxyLogin := Ini.ReadString('Proxy', 'Login', '');
  Config.ProxyPassword := Ini.ReadString('Proxy', 'Password', '');
  Ini.Free;

  //Инициализация обновления статусов
  ThreadStatus := TThreadStatus.Create(true, ListQ, StatusProgressBar, StatusSheet, StatusMemo, Config);
  ThreadStatus.FreeOnTerminate := true;
  ThreadStatus.Priority := tpNormal;
  ThreadStatus.Start;
end;

procedure TfrmStatistic.GetStatisticBtnClick(Sender: TObject);
begin
  StatisticMemo.Lines.Clear;
  StatisticMemo.Lines.Add(Self.namePredpr);
  StatWrite(0);
  StatisticMemo.Lines.Add('');
  StatWrite(1);
end;

procedure TfrmStatistic.UpdatePrintButtonClick(Sender: TObject);
begin
  PrintMemTableEh.Active := False;

  PrintSelect.Close;
  PrintSelect.Parameters.ParamByName('First').Value := DateToStr(FirstPicker.Date);
  PrintSelect.Parameters.ParamByName('Second').Value := DateToStr(SecondPicker.Date);

  if Length(PrintComboBox.Text) = 0 then
    PrintSelect.SQL[PrintSelect.SQL.Count - 2] := '-- Все'
  else
    PrintSelect.SQL[PrintSelect.SQL.Count - 2] := 'AND idRecipient=' + VarToStr(PrintComboBox.KeyValue);

  PrintSelect.Open;

  PrintMemTableEh.Active := True;

  PrintButton.Enabled := not PrintSelect.IsEmpty;
  FilterButton.Enabled := not PrintSelect.IsEmpty;
  StatusCheckLB.Enabled := not PrintSelect.IsEmpty;

  if not PrintSelect.IsEmpty then
    PrintPredprLabel.Caption := PrintComboBox.Text
  else
    PrintPredprLabel.Caption := '';
end;

procedure TfrmStatistic.PrintSelectCalcFields(DataSet: TDataSet);
begin
  PrintSelectStatus.AsString := GetStatusTextById(PrintSelectinvStatus.AsInteger);
end;

procedure TfrmStatistic.PrintButtonClick(Sender: TObject);
begin
  InvDBGridEh.DataGrouping.GroupLevels[0].ExpandNodes;
  InvPrintDBGridEh.Title.Clear;
  InvPrintDBGridEh.Title.Text := PrintPredprLabel.Caption;
  InvPrintDBGridEh.Preview;
end;

procedure TfrmStatistic.PrintMemTableEhCalcFields(DataSet: TDataSet);
begin
  PrintMemTableEhStatus.AsString := GetStatusTextById(PrintMemTableEhinvStatus.AsInteger);
end;

procedure TfrmStatistic.FilterButtonClick(Sender: TObject);
var
  i: Integer;
begin
  with PrintMemTableEh do
  begin
    Filtered := False;
    Filter := '';

    for i := 0 to StatusCheckLB.Count - 1 do
      if StatusCheckLB.Checked[i] then
        Filter := Filter + ' (invStatus=' + InttoStr(i) + ') OR';

    Filter := Copy(Filter, 1, Length(Filter) - 3);
    Filtered := True;
  end;
end;

procedure TfrmStatistic.FindFormClick(Sender: TObject);
begin
  frmSearch := TfrmSearch.Create(Self, PrintComboBox);
  frmSearch.ShowModal;
  frmSearch.Free;
end;

procedure TfrmStatistic.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if Application.MainForm.WindowState = wsMinimized then
    Application.MainForm.WindowState := wsNormal;
end;

end.

