unit U_CurrencyPreparer;

interface

uses
  Windows, U_LNG, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, RzPanel, RzButton, StdCtrls, RzLstBox, RzCmboBx,
  Buttons,

  U_BaseCommon, U_BaseConstants, U_Common, U_SCSComponent, U_SCSLists, siComp, siLngLnk,
  RzTabs, DB;

type
  TF_CurrencyPreparer = class(TForm)
    RzGroupBox2: TRzGroupBox;
    RzBitBtn1: TRzBitBtn;
    RzBitBtn2: TRzBitBtn;
    lng_Forms: TsiLangLinked;
    RzPageControl1: TRzPageControl;
    TabSheet1: TRzTabSheet;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    cbMainCurrency: TRzComboBox;
    cbSecondCurrency: TRzComboBox;
    RzGroupBox3: TRzGroupBox;
    btAddToDel: TSpeedButton;
    btRemoveFromDel: TSpeedButton;
    lbToDelete: TRzListBox;
    cbCountryCurrency: TRzComboBox;
    btPrepareCurrency: TRzBitBtn;
    TabSheet2: TRzTabSheet;
    cbNBType: TRzComboBox;
    Label4: TLabel;
    btSetNBType: TRzBitBtn;
    btClearBackupBaseDate: TRzBitBtn;
    procedure cbMainCurrencyChange(Sender: TObject);
    procedure cbSecondCurrencyChange(Sender: TObject);
    procedure btAddToDelClick(Sender: TObject);
    procedure btRemoveFromDelClick(Sender: TObject);
    procedure cbCountryCurrencyChange(Sender: TObject);
    procedure btPrepareCurrencyClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure btSetNBTypeClick(Sender: TObject);
    procedure btClearBackupBaseDateClick(Sender: TObject);
  private
    GForm: TForm;

    FFirstMCurrency: TCurrency;
    FFirstSCurrency: TCurrency;
    FCountryCurrency: TCurrency;

    FCurrMCurrency: TCurrency;
    FCurrSCurrency: TCurrency;
    FCurrCountryCurrency: TCurrency;

    procedure DeleteCurrenciesFromListBox(AIDList: TIntList);
    procedure OnChangeCurrencyCombo(ASenderCombo, AOtherCombo: TRzComboBox; var ASenderCurrency, AOtherCurrency: TCurrency);
    procedure SetControls;
  public
    Constructor Create(AOwner: TComponent; AForm: TForm);
    Destructor  Destroy; override;
    //Tolik -- 16/03/2018 --
    //function Execute: Boolean;
    function Execute(aShowNBTab: Boolean = True): Boolean;
    //
  end;

//var
//  F_CurrencyPreparer: TF_CurrencyPreparer;

implementation

Uses Unit_DM_SCS, U_Main;

{$R *.dfm}

{ TForm1 }

constructor TF_CurrencyPreparer.Create(AOwner: TComponent; AForm: TForm);
begin
  GForm := AForm;
  inherited Create(AOwner);
end;

destructor TF_CurrencyPreparer.Destroy;
begin
  inherited;
end;
// Tolik -- 16/03/2018 --
//function TF_CurrencyPreparer.Execute: Boolean;
function TF_CurrencyPreparer.Execute(aShowNBTab: Boolean = True): Boolean;
//
var
  //CatalogIDs: TIntList;
  //CurrencyToDel: TCurrency;
  //i: integer;

  //ptrOldMainCurrency: PObjectCurrencyRel;
  //ptrNewMainCurrency: PObjectCurrencyRel;
  //ptrNewSecondCurrency: PObjectCurrencyRel;
  NBType: Integer;
begin
  Result := false;

  if aShowNbTab then
    RzPageControl1.Pages[1].TabVisible := True
  else
    RzPageControl1.Pages[1].TabVisible := False;

  cbMainCurrency.OnChange := nil;
  cbSecondCurrency.OnChange := nil;

  FFirstMCurrency := TF_Main(GForm).DM.GetCurrencyByType(ctMain);
  FFirstSCurrency := TF_Main(GForm).DM.GetCurrencyByType(ctSecond);
  FCountryCurrency := TF_Main(GForm).DM.GetCountryCurrency;
  FCurrMCurrency := FFirstMCurrency;
  FCurrSCurrency := FFirstSCurrency;
  FCurrCountryCurrency := FCountryCurrency;

  FillComboBoxRz(cbMainCurrency, GForm, false, tnCurrency, fnID, fnName, '', FCurrMCurrency.ID);
  FillComboBoxRz(cbSecondCurrency, GForm, false, tnCurrency, fnID, fnName, '', FCurrSCurrency.ID);
  FillComboBoxRz(cbCountryCurrency, GForm, false, tnCurrency, fnID, fnName, '', FCountryCurrency.ID);

  lbToDelete.Items.Clear;

  cbMainCurrency.OnChange := cbMainCurrencyChange;
  cbSecondCurrency.OnChange := cbSecondCurrencyChange;

  NBType := TF_Main(GForm).DM.GetNBType;
  if NBType = 0 then
    NBType := nbtNone;
  SelectItemByIDinComboRz(cbNBType, NBType);

  SetControls;

  if ShowModal = mrOk then
  begin
    //with TF_Main(GForm).DM do
//    begin
//      CatalogIDs := GetCatalogIDsByLevel(dirCurrencyLevel, Query_Select);
//      BeginProgress('', 2 + CatalogIDs.Count + lbToDelete.Items.Count);
//      try
//        //*** Главная и вторая валюта НБ по умолчанию
//        ChengeCurrencyRatiosWithPrices(FFirstMCurrency, FCurrMCurrency, FCurrSCurrency, Query_Select, Query_Operat);
//        StepProgress;
//
//        //*** Валюта стрпны
//        if FCurrCountryCurrency.ID <> FCountryCurrency.ID then
//        begin
//          SetSQLToFIBQuery(Query_Operat, GetSQLByParams(qtUpdate, tnCurrency, '', nil, fnIsCountry), false);
//          Query_Operat.Params[0].AsInteger := biFalse;
//          Query_Operat.ExecQuery;
//          UpdateIntTableFieldByID(tnCurrency, fnIsCountry, FCurrCountryCurrency.ID, biTrue, qmPhisical);
//        end;
//        StepProgress;
//
//        //*** Валюты папок
//        //ptrNewMainCurrency := GetDefObjectCurrencyByMainFld(ctMain);
//        //ptrNewSecondCurrency := GetDefObjectCurrencyByMainFld(ctSecond);
//        for i := 0 to CatalogIDs.Count - 1 do
//        begin
//          //ptrNewMainCurrency := GetObjectCurrencyByMainFld(CatalogIDs[i], ctMain);
//          //ptrNewSecondCurrency := GetObjectCurrencyByMainFld(CatalogIDs[i], ctSecond);
//          //GetZeroMem(ptrOldMainCurrency, SizeOf(TObjectCurrencyRel));
//          //ptrOldMainCurrency^ := ptrNewMainCurrency^;
//
//          ptrOldMainCurrency := GetObjectCurrencyByMainFld(CatalogIDs[i], ctMain);
//          ptrNewMainCurrency := GetObjectCurrencyByIDCurrency(CatalogIDs[i], FCurrMCurrency.ID);
//          ptrNewSecondCurrency := GetObjectCurrencyByIDCurrency(CatalogIDs[i], FCurrSCurrency.ID);
//
//          if (ptrOldMainCurrency <> nil) and (ptrNewMainCurrency <> nil) and (ptrNewSecondCurrency <> nil) then
//            ChangeObjectCurrencyRatiosWithPrices(CatalogIDs[i], ptrOldMainCurrency, ptrNewMainCurrency, ptrNewSecondCurrency,
//              Query_Select, Query_Operat);
//          StepProgress;
//
//          if ptrNewMainCurrency <> nil then
//            FreeMem(ptrNewMainCurrency);
//          if ptrNewSecondCurrency <> nil then
//            FreeMem(ptrNewSecondCurrency);
//          if ptrOldMainCurrency <> nil then
//            FreeMem(ptrOldMainCurrency);
//        end;
//        FreeAndNil(CatalogIDs);
//
//        //*** Удалить валюты из списка удаляемых
//        for i := 0 to lbToDelete.Items.Count - 1 do
//        begin
//          CurrencyToDel := GetCurrencyByID(Integer(lbToDelete.Items.Objects[i]));
//          if (CurrencyToDel.Main <> ctMain) and (CurrencyToDel.Main <> ctSecond) and (CurrencyToDel.IsCountry <> biTrue) then
//            DeleteRecordFromTableByID(tnCurrency, Integer(lbToDelete.Items.Objects[i]), qmPhisical);
//          StepProgress;
//        end;
//      finally
//        EndProgress;
//      end;
//      TF_Main(GForm).RefreshNode(true);
//    end;
  end;

  ClearComboBoxRz(cbMainCurrency);
  ClearComboBoxRz(cbSecondCurrency);
end;

procedure TF_CurrencyPreparer.OnChangeCurrencyCombo(ASenderCombo, AOtherCombo: TRzComboBox; var ASenderCurrency, AOtherCurrency: TCurrency);
var
  NewCurrency: TCurrency;
  SavedOnChangeOtherCombo: TNotifyEvent;
  CurrencyIDs: TIntList;

  i: Integer;
  IDToDel: Integer;
begin
  NewCurrency.ID := GetIDFromComboBoxRz(ASenderCombo);
  NewCurrency := TF_Main(GForm).DM.GetCurrencyByID(NewCurrency.ID);

  //*** Если новая валюта такая как в другом COMBO, то в нем установить такую валюту,
  //    как была в ASenderCombo до изменения
  if NewCurrency.ID = AOtherCurrency.ID then
  begin
    SavedOnChangeOtherCombo := AOtherCombo.OnChange;
    AOtherCombo.OnChange := nil;
    try
      SelectItemByIDinComboRz(AOtherCombo, ASenderCurrency.ID);
      AOtherCurrency := ASenderCurrency;
    finally
      AOtherCombo.OnChange := SavedOnChangeOtherCombo;
    end;
  end;
  ASenderCurrency := NewCurrency;

  //*** Удалить валюты из списка удаляемых
  CurrencyIDs := TIntList.Create;
  CurrencyIDs.Add(ASenderCurrency.ID);
  CurrencyIDs.Add(AOtherCurrency.ID);
  DeleteCurrenciesFromListBox(CurrencyIDs);
  FreeAndNil(CurrencyIDs);

  //i := 0;
  //while i <= lbToDelete.Items.Count - 1 do
  //begin
  //  IDToDel := Integer(lbToDelete.Items.Objects[i]);
  //  if (IDToDel = ASenderCurrency.ID) or (IDToDel = AOtherCurrency.ID) then
  //    lbToDelete.Items.Delete(i)
  //  else
  //    Inc(i);
  //end;
  SetControls;
end;

procedure TF_CurrencyPreparer.cbCountryCurrencyChange(Sender: TObject);
var
  IDCurrency: Integer;
  CurrencyIDList: TIntList;
begin
  IDCurrency := GetIDFromComboBoxRz(cbCountryCurrency);
  if IDCurrency <> 0 then
  begin
    FCurrCountryCurrency.ID := IDCurrency; 
    FCurrCountryCurrency := TF_Main(GForm).DM.GetCurrencyByID(FCurrCountryCurrency.ID);

    CurrencyIDList := TIntList.Create;
    DeleteCurrenciesFromListBox(CurrencyIDList);
    FreeAndNil(CurrencyIDList);

    SetControls;
  end;
end;

procedure TF_CurrencyPreparer.DeleteCurrenciesFromListBox(AIDList: TIntList);
var
  i: Integer;
  IDToDel: Integer;
begin
  i := 0;
  while i <= lbToDelete.Items.Count - 1 do
  begin
    IDToDel := Integer(lbToDelete.Items.Objects[i]);
    //if (IDToDel = ASenderCurrency.ID) or (IDToDel = AOtherCurrency.ID) then
    if AIDList.IndexOf(IDToDel) <> -1 then
      lbToDelete.Items.Delete(i)
    else
      Inc(i);
  end;
end;

procedure TF_CurrencyPreparer.SetControls;
begin
  btRemoveFromDel.Enabled := (lbToDelete.ItemIndex <> -1);
end;

procedure TF_CurrencyPreparer.cbMainCurrencyChange(Sender: TObject);
begin
  OnChangeCurrencyCombo(cbMainCurrency, cbSecondCurrency, FCurrMCurrency, FCurrSCurrency);
end;

procedure TF_CurrencyPreparer.cbSecondCurrencyChange(Sender: TObject);
begin
  OnChangeCurrencyCombo(cbSecondCurrency, cbMainCurrency, FCurrSCurrency, FCurrMCurrency);
end;

procedure TF_CurrencyPreparer.btAddToDelClick(Sender: TObject);
var
  IDToDel: integer;
  CurrencyToDel: TCurrency;
  strMsg: string;
begin
  IDToDel := F_NormBase.DM.GetCurrencyIDFromGuide(0, fmMake);
  if IDToDel <> 0 then
  begin
    CurrencyToDel := TF_Main(GForm).DM.GetCurrencyByID(IDToDel);

    strMsg := '';
    if CurrencyToDel.ID = FCurrMCurrency.ID then
      strMsg := 'Валюта '+CurrencyToDel.Name+' уже установлена как базовая'
    else
    if CurrencyToDel.ID = FCurrSCurrency.ID then
      strMsg := 'Валюта '+CurrencyToDel.Name+' уже установлена как вторая'
    else
    if CurrencyToDel.ID = FCurrCountryCurrency.ID then
      strMsg := 'Валюта '+CurrencyToDel.Name+' уже установлена как валюта страны';

    if strMsg <> '' then
      MessageModal(strMsg, ApplicationName, MB_ICONINFORMATION or MB_OK)
    else
    begin
      lbToDelete.Items.AddObject(CurrencyToDel.Name, TObject(CurrencyToDel.ID));
      lbToDelete.ItemIndex := lbToDelete.Items.Count-1;
      SetControls;
    end;
  end;
end;

procedure TF_CurrencyPreparer.btRemoveFromDelClick(Sender: TObject);
begin
  if lbToDelete.ItemIndex <> -1 then
  begin
    lbToDelete.Items.Delete(lbToDelete.ItemIndex);
    SetControls;
  end;
end;

procedure TF_CurrencyPreparer.btPrepareCurrencyClick(Sender: TObject);
var
  CatalogIDs: TIntList;
  CurrencyToDel: TCurrency;
  i: integer;

  ptrOldMainCurrency: PObjectCurrencyRel;
  ptrNewMainCurrency: PObjectCurrencyRel;
  ptrNewSecondCurrency: PObjectCurrencyRel;
begin
  with TF_Main(GForm).DM do
  begin
    CatalogIDs := GetCatalogIDsByLevel(dirCurrencyLevel, Query_Select);
    BeginProgress('', 2 + CatalogIDs.Count + lbToDelete.Items.Count);
    try
      //*** Главная и вторая валюта НБ по умолчанию
      ChengeCurrencyRatiosWithPrices(FFirstMCurrency, FCurrMCurrency, FCurrSCurrency, Query_Select, Query_Operat);
      StepProgress;

      //*** Валюта стрпны
      if FCurrCountryCurrency.ID <> FCountryCurrency.ID then
      begin
        SetSQLToFIBQuery(Query_Operat, GetSQLByParams(qtUpdate, tnCurrency, '', nil, fnIsCountry), false);
        Query_Operat.Params[0].AsInteger := biFalse;
        Query_Operat.ExecQuery;
        UpdateIntTableFieldByID(tnCurrency, fnIsCountry, FCurrCountryCurrency.ID, biTrue, qmPhisical);
      end;
      StepProgress;

      //*** Валюты папок
      //ptrNewMainCurrency := GetDefObjectCurrencyByMainFld(ctMain);
      //ptrNewSecondCurrency := GetDefObjectCurrencyByMainFld(ctSecond);
      for i := 0 to CatalogIDs.Count - 1 do
      begin
        //ptrNewMainCurrency := GetObjectCurrencyByMainFld(CatalogIDs[i], ctMain);
        //ptrNewSecondCurrency := GetObjectCurrencyByMainFld(CatalogIDs[i], ctSecond);
        //GetZeroMem(ptrOldMainCurrency, SizeOf(TObjectCurrencyRel));
        //ptrOldMainCurrency^ := ptrNewMainCurrency^;

        ptrOldMainCurrency := GetObjectCurrencyByMainFld(CatalogIDs[i], ctMain);
        ptrNewMainCurrency := GetObjectCurrencyByIDCurrency(CatalogIDs[i], FCurrMCurrency.ID);
        ptrNewSecondCurrency := GetObjectCurrencyByIDCurrency(CatalogIDs[i], FCurrSCurrency.ID);

        if (ptrOldMainCurrency <> nil) and (ptrNewMainCurrency <> nil) and (ptrNewSecondCurrency <> nil) then
          ChangeObjectCurrencyRatiosWithPrices(CatalogIDs[i], ptrOldMainCurrency, ptrNewMainCurrency, ptrNewSecondCurrency,
            Query_Select, Query_Operat);
        StepProgress;

        if ptrNewMainCurrency <> nil then
          FreeMem(ptrNewMainCurrency);
        if ptrNewSecondCurrency <> nil then
          FreeMem(ptrNewSecondCurrency);
        if ptrOldMainCurrency <> nil then
          FreeMem(ptrOldMainCurrency);
      end;
      FreeAndNil(CatalogIDs);

      //*** Удалить валюты из списка удаляемых
      for i := 0 to lbToDelete.Items.Count - 1 do
      begin
        CurrencyToDel := GetCurrencyByID(Integer(lbToDelete.Items.Objects[i]));
        if (CurrencyToDel.Main <> ctMain) and (CurrencyToDel.Main <> ctSecond) and (CurrencyToDel.IsCountry <> biTrue) then
          DeleteRecordFromTableByID(tnCurrency, Integer(lbToDelete.Items.Objects[i]), qmPhisical);
        StepProgress;
      end;
    finally
      EndProgress;
    end;
    TF_Main(GForm).RefreshNode(true);
  end;
end;

procedure TF_CurrencyPreparer.FormCreate(Sender: TObject);
begin
  cbNBType.Items.Clear;

  AddIDToComboRz(nbtNone, '', cbNBType);
  AddIDToComboRz(nbtGeneral, 'Общая', cbNBType);
  AddIDToComboRz(nbtTrial, 'Триал', cbNBType);
  AddIDToComboRz(nbtSCSUA, 'СКС UA', cbNBType);
  AddIDToComboRz(nbtSCSRU, 'СКС RU', cbNBType);
  AddIDToComboRz(nbtTelecomUA, 'Телеком UA', cbNBType);
  AddIDToComboRz(nbtTelecomRU, 'Телеком RU', cbNBType);
  AddIDToComboRz(nbTube, 'Трубы', cbNBType);
  AddIDToComboRz(nbCableProjectPE, 'CableProject', cbNBType);
  AddIDToComboRz(nbGraphStroyCalc, 'Граф. СК', cbNBType);
  AddIDToComboRz(nbtTelcoCAD, 'TELCOCAD', cbNBType);

  cbNBType.ItemIndex := nbtGeneral;
end;

procedure TF_CurrencyPreparer.btSetNBTypeClick(Sender: TObject);
var
  NBType: Integer;
begin
  //NBType := GetIDFromComboBoxRz(cbNBType) * nbTypeKoeff;
  //if Not CheckFieldInTable(tnGradeGrid, fnDescription, TF_Main(GForm).DM.Query_Select) then
  //begin
  //  AddFieldToTable(tnGradeGrid, fnDescription, ftString, NBType, TF_Main(GForm).DM.Query_Operat);
  //end;
  //SetFieldInfo(tnGradeGrid, fnDescription, 'RDB$FIELD_LENGTH', NBType, TF_Main(GForm).DM.Query_Select, TF_Main(GForm).DM.Query_Operat);
  //SetFieldInfo(tnGradeGrid, fnDescription, 'RDB$CHARACTER_LENGTH', NBType, TF_Main(GForm).DM.Query_Select, TF_Main(GForm).DM.Query_Operat);
  NBType := GetIDFromComboBoxRz(cbNBType);
  SetNBType(NBType, TF_Main(GForm).DM.Query_Select, TF_Main(GForm).DM.Query_Operat);
end;

procedure TF_CurrencyPreparer.btClearBackupBaseDateClick(Sender: TObject);
begin
  UpdateTableFieldAllRec(F_NormBase.DM.Query_Operat, tnSettings, fnBackUpDate, null);
  UpdateTableFieldAllRec(F_ProjMan.DM.Query_Operat, tnSettings, fnBackUpDate, null);
  MessageInfo('OK');
end;

end.
