unit U_ConfiguratorUpdateInfo;

interface

uses
  Windows, U_LNG, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Contnrs,

  U_BaseCommon, U_BaseConstants, U_SCSLists, RzTabs, RzButton, ExtCtrls, RzPanel, cxStyles,
  cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB,
  cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView,
  cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
  cxCheckBox, cxCurrencyEdit, cxColorComboBox, cxSpinEdit, StdCtrls, Mask,
  RzEdit, RzSpnEdt, cxMemo, RzRadChk, RzRadGrp, Buttons, siComp, siLngLnk,
  cxTextEdit, ComCtrls, RzBtnEdt,

  U_Common_Classes, FIB, FIBQuery, pFIBQuery, Menus, RzCmboBx, RzLstBox, U_SCSComponent,
  cxDBLookupComboBox, cxLookAndFeels, cxLookAndFeelPainters, cxNavigator;

type

  TTableTextColumnsInfo = class(TMyObject)
    public
      TableName: string;
      TextFields: TStringList;

      constructor Create;
      destructor Destroy; override;
  end;

  TF_ConfiguratorUpdateInfo = class(TForm)
    RzPageControl1: TRzPageControl;
    RzGroupBox1: TRzGroupBox;
    RzBitBtn1: TRzBitBtn;
    tsUpdStructInfo: TRzTabSheet;
    tsUpdInfoRelation: TRzTabSheet;
    gbRecord: TRzGroupBox;
    GT_UpdStructInfo: TcxGridDBTableView;
    GL_UpdStructInfo: TcxGridLevel;
    Grid_UpdStructInfo: TcxGrid;
    GT_UpdStructInfoID: TcxGridDBColumn;
    GT_UpdStructInfoDateEntry: TcxGridDBColumn;
    GT_UpdStructInfoBUILD_ID: TcxGridDBColumn;
    GT_UpdStructInfoScript: TcxGridDBColumn;
    GT_UpdStructInfoSortID: TcxGridDBColumn;
    RzGroupBox3: TRzGroupBox;
    btAddAsNew: TRzBitBtn;
    btUpdate: TRzBitBtn;
    btDelete: TRzBitBtn;
    RzPanel1: TRzPanel;
    deDateEntry: TRzDateTimeEdit;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    seBuildID: TRzSpinEdit;
    seSortID: TRzSpinEdit;
    RzPanel2: TRzPanel;
    Label4: TLabel;
    meScript: TRzMemo;
    cbIncSortIDBeforeNew: TRzCheckBox;
    RzGroupBox2: TRzGroupBox;
    RzPanel3: TRzPanel;
    RzGroupBox4: TRzGroupBox;
    RzPanel4: TRzPanel;
    GT_UpdInfo: TcxGridDBTableView;
    GL_UpdInfo: TcxGridLevel;
    Grid_UpdInfo: TcxGrid;
    Grid_UpdInfoRel: TcxGrid;
    GT_UpdInfoRel: TcxGridDBTableView;
    GL_UpdInfoRel: TcxGridLevel;
    Label5: TLabel;
    edUpdInfoTableName: TRzEdit;
    Label6: TLabel;
    edUpdInfoGeneratorName: TRzEdit;
    cbUpdInfoIsOn: TRzCheckBox;
    Label7: TLabel;
    seUpdInfoSortID: TRzSpinEdit;
    cbUpdInfoIncBeforeNew: TRzCheckBox;
    btUpdInfoAsNew: TRzBitBtn;
    btUpdInfoUpdate: TRzBitBtn;
    btUpdInfoDelete: TRzBitBtn;
    Splitter1: TSplitter;
    rgUpdInfoTableType: TRzRadioGroup;
    rgUpdInfoRelRelationType: TRzRadioGroup;
    Label8: TLabel;
    edUpdInfoRelTableName: TRzEdit;
    Label9: TLabel;
    edUpdInfoRelFieldName: TRzEdit;
    btUpdInfoRelAsNew: TRzBitBtn;
    btUpdInfoRelUpdate: TRzBitBtn;
    btUpdInfoRelDelete: TRzBitBtn;
    GT_UpdInfoID: TcxGridDBColumn;
    GT_UpdInfoISON: TcxGridDBColumn;
    GT_UpdInfoTABLE_NAME: TcxGridDBColumn;
    GT_UpdInfoGENERATOR_NAME: TcxGridDBColumn;
    GT_UpdInfoSORT_ID: TcxGridDBColumn;
    GT_UpdInfoTABLE_TYPE: TcxGridDBColumn;
    GT_UpdInfoRelID: TcxGridDBColumn;
    GT_UpdInfoRelRELATION_TYPE: TcxGridDBColumn;
    GT_UpdInfoRelREL_TABLE_NAME: TcxGridDBColumn;
    GT_UpdInfoRelREL_FIELD_NAME: TcxGridDBColumn;
    RzPanel5: TRzPanel;
    btCleatScript: TSpeedButton;
    Label10: TLabel;
    seUpdInfoRel: TRzSpinEdit;
    GT_UpdInfoRelSORT_ID: TcxGridDBColumn;
    GT_UpdInfoUpdateAllData: TcxGridDBColumn;
    cbUpdateAllData: TRzCheckBox;
    lng_Forms: TsiLangLinked;
    btAsNewFromFile: TRzButton;
    OpenDialog: TOpenDialog;
    edSeparator: TRzEdit;
    Label11: TLabel;
    TabSheet1: TRzTabSheet;
    Label12: TLabel;
    edUpdateTableName: TRzEdit;
    edSrcCSVFile: TRzButtonEdit;
    Label13: TLabel;
    Label14: TLabel;
    Label15: TLabel;
    Label16: TLabel;
    edUpdateKeyField: TRzEdit;
    lvUpdateFields: TListView;
    btUpdateTableFromCSVFile: TRzBitBtn;
    lbUpdateFromCSVLog: TListBox;
    Label17: TLabel;
    pmnuLVUpdateFields: TPopupMenu;
    miSetPriorFiled: TMenuItem;
    edOpenBracket: TRzEdit;
    Label18: TLabel;
    edCloseBracket: TRzEdit;
    TabSheet2: TRzTabSheet;
    RzPageControl2: TRzPageControl;
    TabSheet3: TRzTabSheet;
    TabSheet4: TRzTabSheet;
    Label19: TLabel;
    cbSrcLang: TRzComboBox;
    btSetValuesFromLngFld: TRzBitBtn;
    cbNotWriteEmptyValues: TRzCheckBox;
    Label20: TLabel;
    Label21: TLabel;
    edDirToExport: TRzButtonEdit;
    btExportTextFields: TRzBitBtn;
    Label22: TLabel;
    lbExportTextValueFields: TListBox;
    cbDelSrcFields: TRzCheckBox;
    cbPackBase: TRzCheckBox;
    btCheckCyrillic: TRzBitBtn;
    meSetTextValuesToActualFields: TMemo;
    SetValuesToLngFld: TRzBitBtn;
    TabSheet5: TRzTabSheet;
    RzGroupBox5: TRzGroupBox;
    Label23: TLabel;
    edComponImagesFolder: TRzEdit;
    btChoiceComponImagesFolder: TSpeedButton;
    RzGroupBox6: TRzGroupBox;
    btImgByArtProducer: TRzRadioButton;
    btImgByArtDistributor: TRzRadioButton;
    btComponImgImport: TRzButton;
    RzGroupBox7: TRzGroupBox;
    lbComponImgImportLog: TRzListBox;
    RzGroupBox8: TRzGroupBox;
    Label24: TLabel;
    btSelectGuideFilesDir: TSpeedButton;
    edGuideFilesRootDir: TRzEdit;
    btImportGuideFiles: TRzButton;
    cbGuideFileType: TRzComboBox;
    Label25: TLabel;
    btObjIconNameArticuls: TButton;
    btGetNBTreeCompons: TButton;
    meLog: TMemo;
    procedure FormCreate(Sender: TObject);
    procedure GT_UpdStructInfoFocusedRecordChanged(
      Sender: TcxCustomGridTableView; APrevFocusedRecord,
      AFocusedRecord: TcxCustomGridRecord;
      ANewItemRecordFocusingChanged: Boolean);
    procedure btAddAsNewClick(Sender: TObject);
    procedure btUpdateClick(Sender: TObject);
    procedure btDeleteClick(Sender: TObject);
    procedure RzGroupBox1Resize(Sender: TObject);
    procedure btUpdInfoAsNewClick(Sender: TObject);
    procedure btUpdInfoUpdateClick(Sender: TObject);
    procedure btUpdInfoDeleteClick(Sender: TObject);
    procedure btUpdInfoRelAsNewClick(Sender: TObject);
    procedure btUpdInfoRelUpdateClick(Sender: TObject);
    procedure btUpdInfoRelDeleteClick(Sender: TObject);
    procedure GT_UpdInfoTABLE_TYPEGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_UpdInfoRelRELATION_TYPEGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_UpdInfoFocusedRecordChanged(
      Sender: TcxCustomGridTableView; APrevFocusedRecord,
      AFocusedRecord: TcxCustomGridRecord;
      ANewItemRecordFocusingChanged: Boolean);
    procedure GT_UpdInfoRelFocusedRecordChanged(
      Sender: TcxCustomGridTableView; APrevFocusedRecord,
      AFocusedRecord: TcxCustomGridRecord;
      ANewItemRecordFocusingChanged: Boolean);
    procedure btCleatScriptClick(Sender: TObject);
    procedure btAsNewFromFileClick(Sender: TObject);
    procedure edSrcCSVFileButtonClick(Sender: TObject);
    procedure btUpdateTableFromCSVFileClick(Sender: TObject);
    procedure miSetPriorFiledClick(Sender: TObject);
    procedure lvUpdateFieldsMouseDown(Sender: TObject;
      Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
    procedure btSetValuesFromLngFldClick(Sender: TObject);
    procedure btExportTextFieldsClick(Sender: TObject);
    procedure btCheckCyrillicClick(Sender: TObject);
    procedure SetValuesToLngFldClick(Sender: TObject);
    procedure btChoiceComponImagesFolderClick(Sender: TObject);
    procedure btComponImgImportClick(Sender: TObject);
    procedure btSelectGuideFilesDirClick(Sender: TObject);
    procedure btImportGuideFilesClick(Sender: TObject);
    procedure btObjIconNameArticulsClick(Sender: TObject);
    procedure btGetNBTreeComponsClick(Sender: TObject);
  private
    GForm: TForm;
    FSprTablesTextColumnsInfo: TObjectList;
    FTablesTextColumnsInfo: TObjectList;

    procedure AddEditUpdInfo(AMakeEdit: TMakeEdit);
    procedure AddEditUpdInfoRel(AMakeEdit: TMakeEdit);
    procedure AddEditUpdStructInfo(AMakeEdit: TMakeEdit);
    procedure SetControlsUpdInfo(ARecordToControls: Boolean);
    procedure SetControlsUpdInfoRel(ARecordToControls: Boolean);
    procedure SetControlsUpdStructInfo(ARecordToControls: Boolean);

    procedure ImportGuideFiles(const ADirName: string; AIDDestDirType, AFType: Integer; AFileCount: PInteger);
  public
    constructor Create(AOwner: TComponent; AForm: TForm); overload;
    destructor Destroy; override;

    procedure Execute;
  end;

//var
  //F_ConfiguratorUpdatetInfo: TF_ConfiguratorUpdatetInfo;

implementation
Uses U_Main, Unit_DM_SCS, U_ProtectionCommon;//, bz2;
{$R *.dfm}

{ TTableTextColumnsInfo }

constructor TTableTextColumnsInfo.Create;
begin
  inherited;
  TableName := '';
  TextFields := TStringList.Create;
end;

destructor TTableTextColumnsInfo.Destroy;
begin
  FreeAndNil(TextFields);
  inherited;
end;


{ TF_ConfiguratorUpdatetInfo }

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

destructor TF_ConfiguratorUpdateInfo.Destroy;
begin
  FreeAndNil(FSprTablesTextColumnsInfo);
  ClearComboBoxRz(cbGuideFileType);
  
  inherited;
end;

procedure TF_ConfiguratorUpdateInfo.Execute;
begin
  cbIncSortIDBeforeNew.Checked := false;
  cbUpdInfoIncBeforeNew.Checked := false;

  SetControlsUpdInfo(true);
  SetControlsUpdInfoRel(true);
  SetControlsUpdStructInfo(true);

  ShowModal;
end;

procedure TF_ConfiguratorUpdateInfo.FormCreate(Sender: TObject);
var
  TableTextColumnsInfo: TTableTextColumnsInfo;

  function AddTableTextColumnInfoToList(ATableName: String; ATablesTextColumnsInfo: TObjectList): TTableTextColumnsInfo;
  begin
    Result := TTableTextColumnsInfo.Create;
    Result.TableName := ATableName;
    ATablesTextColumnsInfo.Add(Result);
  end;

begin
  // Tolik 01/11/2019 --
  seBuildID.Max := 10000000000;
  seBuildID.Min := 0;
  seSortID.Min := 0;
  seSortID.Max := 10000000000;
  seUpdInfoSortID.Max := 10000000000;
  seUpdInfoSortID.Min := 0;
  seUpdInfoRel.Min := 0;
  seUpdInfoRel.Max := 10000000000;
  //
  GT_UpdStructInfo.DataController.DataSource := TF_Main(GForm).DM.dsrcUpdStructInfo;
  GT_UpdInfo.DataController.DataSource := TF_Main(GForm).DM.dSrcUpdInfo;
  GT_UpdInfoRel.DataController.DataSource := TF_Main(GForm).DM.dSrcUpdInfoRel;

  FSprTablesTextColumnsInfo := TObjectList.Create(true);
  FTablesTextColumnsInfo := TObjectList.Create(true);

  //********************** Справочники ****************
  // Дерево справочников
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnDirectoryType, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);
  // Валюты
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnCurrency, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);
  TableTextColumnsInfo.TextFields.Add(fnNameBrief);
  // Производители
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnProducers, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);
  TableTextColumnsInfo.TextFields.Add(fnDescription);

  // Тип компоненты
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnComponentTypes, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);
  TableTextColumnsInfo.TextFields.Add(fnNamePlural);
  // Свойства типов компонентов
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnCompTypePropRelation, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnPValue);

  // Типы интерфейсов
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnInterfaceType, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);
  // Интерфейсы
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnInterface, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);
  TableTextColumnsInfo.TextFields.Add(fnDescription);
  
  // Типы сетей
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnNetType, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);
  // Условные обозначения
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnObjectIcons, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);
  // Свойства
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnProperties, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);
  TableTextColumnsInfo.TextFields.Add(fnIzm);
  TableTextColumnsInfo.TextFields.Add(fnDefValue);
  TableTextColumnsInfo.TextFields.Add(fnDescription);
  // Типы данных
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnDataType, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);

  // Нормы
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnNBNorms, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);
  TableTextColumnsInfo.TextFields.Add(fnIzm);
  // Ресурсы
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnNBResources, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);
  TableTextColumnsInfo.TextFields.Add(fnIzm);
  // Виды поставок
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnSuppliesKinds, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);
  TableTextColumnsInfo.TextFields.Add(fnIzm);
  TableTextColumnsInfo.TextFields.Add(fnNameTradUOM);
  TableTextColumnsInfo.TextFields.Add(fnIzmTradUOM);
  // Строки для ввода
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnInputStrings, FSprTablesTextColumnsInfo);
  TableTextColumnsInfo.TextFields.Add(fnName);

  //********************** Другие таблици **************************
  // Папки
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnCatalog, FSprTablesTextColumnsInfo{FTablesTextColumnsInfo});
  TableTextColumnsInfo.TextFields.Add(fnName);
  // Компоненты
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnComponent, FSprTablesTextColumnsInfo{FTablesTextColumnsInfo});
  TableTextColumnsInfo.TextFields.Add(fnName);
  TableTextColumnsInfo.TextFields.Add(fnNameShort);
  TableTextColumnsInfo.TextFields.Add(fnIzm);
  TableTextColumnsInfo.TextFields.Add(fnNotice);
  // Интерфейсы компонент
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnInterfaceRelation, FSprTablesTextColumnsInfo{FTablesTextColumnsInfo});
  TableTextColumnsInfo.TextFields.Add(fnNotice);
  TableTextColumnsInfo.TextFields.Add(fnSideSection);
  // Свойства компонентов
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnCompPropRelation, FSprTablesTextColumnsInfo{FTablesTextColumnsInfo});
  TableTextColumnsInfo.TextFields.Add(fnPValue);
  // Ресурсы
  TableTextColumnsInfo := AddTableTextColumnInfoToList(tnResources, FSprTablesTextColumnsInfo{FTablesTextColumnsInfo});
  TableTextColumnsInfo.TextFields.Add(fnName);
  TableTextColumnsInfo.TextFields.Add(fnIzm);

  // Список языков
  cbSrcLang.Items.Add('ENG');
  //cbSrcLang.Items.Add('SPA');
  cbSrcLang.ItemIndex := 0;

  cbGuideFileType.Items.Clear;
  AddIDToComboRz(gftCompSpecification, 'Спецификации на компоненты', cbGuideFileType);
  cbGuideFileType.ItemIndex := 0;
end;

procedure TF_ConfiguratorUpdateInfo.GT_UpdStructInfoFocusedRecordChanged(
  Sender: TcxCustomGridTableView; APrevFocusedRecord,
  AFocusedRecord: TcxCustomGridRecord;
  ANewItemRecordFocusingChanged: Boolean);
begin
  SetControlsUpdStructInfo(true);
end;

procedure TF_ConfiguratorUpdateInfo.AddEditUpdInfo(AMakeEdit: TMakeEdit);
var
  GridFocusedRecordChangedEvent: TcxGridFocusedRecordChangedEvent;
begin
  GridFocusedRecordChangedEvent := GT_UpdInfo.OnFocusedRecordChanged;
  GT_UpdInfo.OnFocusedRecordChanged := nil;
  try
    with TF_Main(GForm).DM do
    begin
      case AMakeEdit of
        meMake:
          dsetUpdInfo.Append;
        meEdit:
          dsetUpdInfo.Edit;
      end;
      if dsetUpdInfo.State <> dsBrowse then
      begin
        dsetUpdInfo.FN(fnIsOn).AsInteger := BoolToInt(cbUpdInfoIsOn.Checked);
        dsetUpdInfo.FN(fnTableName).AsString := edUpdInfoTableName.Text;
        dsetUpdInfo.FN(fnGeneratorName).AsString := edUpdInfoGeneratorName.Text;
        dsetUpdInfo.FN(fnTableType).AsInteger := rgUpdInfoTableType.ItemIndex + 1;
        dsetUpdInfo.FN(fnUpdateAllData).AsInteger := BoolToInt(cbUpdateAllData.Checked);
        dsetUpdInfo.FN(fnSortID).AsInteger := Round(seUpdInfoSortID.Value);
        dsetUpdInfo.Post;
      end;
    end;
  except
    on E: Exception do AddExceptionToLog('TF_ConfiguratorUpdateInfo.AddEditUpdInfo: '+E.Message);
  end;
  GT_UpdInfo.OnFocusedRecordChanged := GridFocusedRecordChangedEvent;
end;


procedure TF_ConfiguratorUpdateInfo.AddEditUpdInfoRel(AMakeEdit: TMakeEdit);
var
  GridFocusedRecordChangedEvent: TcxGridFocusedRecordChangedEvent;
begin
  GridFocusedRecordChangedEvent := GT_UpdInfoRel.OnFocusedRecordChanged;
  GT_UpdInfoRel.OnFocusedRecordChanged := nil;
  try
    with TF_Main(GForm).DM do
    begin
      case AMakeEdit of
        meMake:
          dsetUpdInfoRel.Append;
        meEdit:
          dsetUpdInfoRel.Edit;
      end;
      if dsetUpdInfoRel.State <> dsBrowse then
      begin
        dsetUpdInfoRel.FN(fnRelationType).AsInteger := rgUpdInfoRelRelationType.ItemIndex + 1;
        dsetUpdInfoRel.FN(fnRelTableName).AsString := edUpdInfoRelTableName.Text;
        dsetUpdInfoRel.FN(fnRelFieldName).AsString := edUpdInfoRelFieldName.Text;
        dsetUpdInfoRel.FN(fnSortID).AsInteger := Round(seUpdInfoRel.Value);
        dsetUpdInfoRel.Post;
      end;
    end;
  except
    on E: Exception do AddExceptionToLog('TF_ConfiguratorUpdateInfo.AddEditUpdInfoRel: '+E.Message);
  end;
  GT_UpdInfoRel.OnFocusedRecordChanged := GridFocusedRecordChangedEvent;
end;


procedure TF_ConfiguratorUpdateInfo.AddEditUpdStructInfo(AMakeEdit: TMakeEdit);
var
  Stream: TMemoryStream;
  GridFocusedRecordChangedEvent: TcxGridFocusedRecordChangedEvent;
begin
  GridFocusedRecordChangedEvent := GT_UpdStructInfo.OnFocusedRecordChanged;
  GT_UpdStructInfo.OnFocusedRecordChanged := nil;
  try
    with TF_Main(GForm).DM do
    begin
      case AMakeEdit of
        meMake:
          dsetUpdStructInfo.Append;
        meEdit:
          dsetUpdStructInfo.Edit;
      end;
      if dsetUpdStructInfo.State <> dsBrowse then
      begin
        dsetUpdStructInfo.FN(fnDateEntry).AsDateTime := deDateEntry.Date;
        dsetUpdStructInfo.FN(fnBuildID).AsInteger := Round(seBuildID.Value);
        dsetUpdStructInfo.FN(fnSortID).AsInteger := Round(seSortID.Value);

        Stream := TMemoryStream.Create;
        try
          meScript.Lines.SaveToStream(Stream);
          Stream.Position := 0;
          TBlobField(dsetUpdStructInfo.FN(fnScript)).LoadFromStream(Stream);
        finally
          FreeAndNil(Stream);
        end;
        dsetUpdStructInfo.Post;
      end;
    end;
  except
    on E: Exception do AddExceptionToLog('TF_ConfiguratorUpdateInfo.AddEditUpdStructInfo: '+E.Message);
  end;
  GT_UpdStructInfo.OnFocusedRecordChanged := GridFocusedRecordChangedEvent;
end;

procedure TF_ConfiguratorUpdateInfo.SetControlsUpdInfo(ARecordToControls: Boolean);
begin
  with TF_Main(GForm).DM do
  begin
    btUpdInfoUpdate.Enabled := (dsetUpdInfo.RecordCount > 0);
    btUpdInfoDelete.Enabled := (dsetUpdInfo.RecordCount > 0);
    if ARecordToControls and (dsetUpdInfo.RecordCount > 0) then
    begin
      cbUpdInfoIsOn.Checked := IntToBool(dsetUpdInfo.FN(fnIsOn).AsInteger);
      edUpdInfoTableName.Text := dsetUpdInfo.FN(fnTableName).AsString;
      edUpdInfoGeneratorName.Text := dsetUpdInfo.FN(fnGeneratorName).AsString;
      rgUpdInfoTableType.ItemIndex := dsetUpdInfo.FN(fnTableType).AsInteger - 1;
      cbUpdateAllData.Checked := IntToBool(dsetUpdInfo.FN(fnUpdateAllData).AsInteger);
      seUpdInfoSortID.Value := dsetUpdInfo.FN(fnSortID).AsInteger;
    end;
  end;
end;

procedure TF_ConfiguratorUpdateInfo.SetControlsUpdInfoRel(ARecordToControls: Boolean);
begin
  with TF_Main(GForm).DM do
  begin
    btUpdInfoRelAsNew.Enabled := (dsetUpdInfo.RecordCount > 0);
    btUpdInfoRelUpdate.Enabled := (dsetUpdInfoRel.RecordCount > 0);
    btUpdInfoRelDelete.Enabled := (dsetUpdInfoRel.RecordCount > 0);
    if ARecordToControls and (dsetUpdInfoRel.RecordCount > 0) then
    begin
      rgUpdInfoRelRelationType.ItemIndex := dsetUpdInfoRel.FN(fnRelationType).AsInteger - 1;
      edUpdInfoRelTableName.Text := dsetUpdInfoRel.FN(fnRelTableName).AsString;
      edUpdInfoRelFieldName.Text := dsetUpdInfoRel.FN(fnRelFieldName).AsString;
      seUpdInfoRel.Value := dsetUpdInfoRel.FN(fnSortID).AsInteger;
    end;
  end;
end;

procedure TF_ConfiguratorUpdateInfo.SetControlsUpdStructInfo(ARecordToControls: Boolean);
var
  Stream: TMemoryStream;
begin
  with TF_Main(GForm).DM do
  begin
    btUpdate.Enabled := (dsetUpdStructInfo.RecordCount > 0);
    btDelete.Enabled := (dsetUpdStructInfo.RecordCount > 0);

    if ARecordToControls and (dsetUpdStructInfo.RecordCount > 0) then
    begin
      deDateEntry.Date := dsetUpdStructInfo.FN(fnDateEntry).AsDateTime;
      seBuildID.Value := dsetUpdStructInfo.FN(fnBuildID).AsInteger;
      seSortID.Value := dsetUpdStructInfo.FN(fnSortID).AsInteger;

      Stream := TMemoryStream.Create;
      try
        TBlobField(dsetUpdStructInfo.FN(fnScript)).SaveToStream(Stream);
        Stream.Position := 0;
        meScript.Lines.LoadFromStream(Stream);
      finally
        FreeAndNil(Stream);
      end;
    end;
  end;
end;

procedure TF_ConfiguratorUpdateInfo.ImportGuideFiles(const ADirName: string; AIDDestDirType, AFType: Integer; AFileCount: PInteger);
var
  DirName: String;
  CanGrab: Boolean;
  fs: TSearchRec;

  FileName: String;
  FileExt: String;
  FileStream: TFileStream;
  NewGuideFileID: Integer;
  DirItemType: Integer;
  IDDestDirType: Integer;

  procedure ShowMsg(const AMsg: String);
  begin
    MessageInfo(AMsg);
    CanGrab := false;
  end;

begin
  CanGrab := true;
  if Not DirectoryExists(ADirName) then
    ShowMsg('Папка не найдена');
  if CanGrab then
  begin
    DirName := IncludeTrailingBackslash(ADirName);
    DirItemType := GetDirItemTypeByGuideFileType(AFType);
    // Создаем папку в справочниках
    IDDestDirType := TF_Main(GForm).FNormBase.DM.InsertDirTypeFolder(ExtractDirName(DirName), DirItemType, AIDDestDirType);

    if FindFirst(DirName+'*.*', faAnyFile - faVolumeID, fs) = 0 then
      repeat
        if (fs.Name <> '..') then
        begin
          if (fs.Attr and faDirectory = 0) then
          begin
            FileName := ExtractFileNameOnly(fs.Name);
            FileExt := ExtractFileExt(fs.Name);
            if AnsiLowerCase(FileExt) = '.doc' then
            begin
              FileStream := TFileStream.Create(DirName + fs.Name, fmOpenRead);
              FileStream.Position := 0;
              try
                NewGuideFileID := TF_Main(GForm).FNormBase.DM.SaveGuideFile(0, AFType, FileName, FileExt, nil, FileStream, false);
                if NewGuideFileID <> 0 then
                begin
                  TF_Main(GForm).FNormBase.DM.InsertToDirecoryTypeRel(IDDestDirType, NewGuideFileID, GetMasterFNameByDirItemType(DirItemType));
                  if AFileCount <> nil then
                    AFileCount^ := AFileCount^ + 1;
                end;
              finally
                FileStream.Free;
              end;
            end;
          end
          else
          if (fs.Attr and faDirectory = faDirectory) and (fs.Name <> '.') then
          begin
            ImportGuideFiles(DirName + fs.Name, IDDestDirType, AFType, AFileCount);
          end;
        end;
      until FindNext(fs) <> 0;
    FindClose(fs);
  end;
end;

procedure TF_ConfiguratorUpdateInfo.btAddAsNewClick(Sender: TObject);
begin
  if cbIncSortIDBeforeNew.Checked then
    seSortID.Value := seSortID.Value + 1; 
  AddEditUpdStructInfo(meMake);
end;

procedure TF_ConfiguratorUpdateInfo.btUpdateClick(Sender: TObject);
begin
  AddEditUpdStructInfo(meEdit);
end;

procedure TF_ConfiguratorUpdateInfo.btDeleteClick(Sender: TObject);
begin
  if MessageModal(cConfiguratorUpdateInfo_Msg1, ApplicationName, MB_ICONQUESTION or MB_YESNO) = IDYES then
    TF_Main(GForm).DM.dsetUpdStructInfo.Delete;
end;

procedure TF_ConfiguratorUpdateInfo.RzGroupBox1Resize(Sender: TObject);
begin
  SetMiddleControlChilds(TControl(Sender), TControl(Self));
end;

procedure TF_ConfiguratorUpdateInfo.btUpdInfoAsNewClick(Sender: TObject);
begin
  if cbUpdInfoIncBeforeNew.Checked then
    seUpdInfoSortID.Value := seUpdInfoSortID.Value + 1;
  AddEditUpdInfo(meMake);
end;

procedure TF_ConfiguratorUpdateInfo.btUpdInfoUpdateClick(Sender: TObject);
begin
  AddEditUpdInfo(meEdit);
end;

procedure TF_ConfiguratorUpdateInfo.btUpdInfoDeleteClick(Sender: TObject);
begin
  if MessageModal(cConfiguratorUpdateInfo_Msg1, ApplicationName, MB_ICONQUESTION or MB_YESNO) = IDYES then
    TF_Main(GForm).DM.dsetUpdInfo.Delete;
end;

procedure TF_ConfiguratorUpdateInfo.btUpdInfoRelAsNewClick(
  Sender: TObject);
begin
  AddEditUpdInfoRel(meMake);
end;

procedure TF_ConfiguratorUpdateInfo.btUpdInfoRelUpdateClick(
  Sender: TObject);
begin
  AddEditUpdInfoRel(meEdit);
end;

procedure TF_ConfiguratorUpdateInfo.btUpdInfoRelDeleteClick(
  Sender: TObject);
begin
  if MessageModal(cConfiguratorUpdateInfo_Msg1, ApplicationName, MB_ICONQUESTION or MB_YESNO) = IDYES then
    TF_Main(GForm).DM.dsetUpdInfoRel.Delete;
end;

procedure TF_ConfiguratorUpdateInfo.GT_UpdInfoTABLE_TYPEGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  if AText = '1' then
    AText := cConfiguratorUpdateInfo_Msg2_1;
  if AText = '2' then
    AText := cConfiguratorUpdateInfo_Msg2_2;
end;

procedure TF_ConfiguratorUpdateInfo.GT_UpdInfoRelRELATION_TYPEGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
 if AText = '1' then
    AText := 'Detail';
  if AText = '2' then
    AText := 'Directory';
end;

procedure TF_ConfiguratorUpdateInfo.GT_UpdInfoFocusedRecordChanged(
  Sender: TcxCustomGridTableView; APrevFocusedRecord,
  AFocusedRecord: TcxCustomGridRecord;
  ANewItemRecordFocusingChanged: Boolean);
begin
  SetControlsUpdInfo(true);
  SetControlsUpdInfoRel(true);
end;

procedure TF_ConfiguratorUpdateInfo.GT_UpdInfoRelFocusedRecordChanged(
  Sender: TcxCustomGridTableView; APrevFocusedRecord,
  AFocusedRecord: TcxCustomGridRecord;
  ANewItemRecordFocusingChanged: Boolean);
begin
  SetControlsUpdInfoRel(true);
end;

procedure TF_ConfiguratorUpdateInfo.btCleatScriptClick(Sender: TObject);
begin
  meScript.Lines.Clear;
  meScript.SetFocus;
end;

procedure TF_ConfiguratorUpdateInfo.btAsNewFromFileClick(Sender: TObject);
var
  FHandle: TextFile;

  Buffer: string;
  BufferLength: Integer;
  ch: Char;
  SeparatorStr: String;
  SeparatorLength: Integer;

  CmpPos: Integer;
  IsLoadingScript: Boolean;
  IsSeparator: Boolean;
  Stream: TMemoryStream;
begin
  {$if Defined(ES_GRAPH_SC)}
    OpenDialog.InitialDir := ExeDir;
  {$else}
    OpenDialog.InitialDir := ExtractFileDir(ParamStr(0));
  {$ifend}
  if OpenDialog.Execute then
  begin
    Buffer := '';

    SeparatorStr := edSeparator.Text;
    SeparatorLength := Length(SeparatorStr);

    AssignFile(FHandle, OpenDialog.FileName);
    Reset(FHandle);

    IsLoadingScript := false;
    CmpPos := 1;

    GT_UpdStructInfo.OnFocusedRecordChanged := nil;
    try
      while Not Eof(FHandle) do
      begin
        Read(FHandle, ch);
        Buffer := Buffer + ch;

        BufferLength := Length(Buffer);

        IsSeparator := false;
        if ch = SeparatorStr[CmpPos] then
        begin
          Inc(CmpPos);
          if CmpPos > SeparatorLength then
          begin
            CmpPos := 1;
            IsSeparator := true;

            if BufferLength >= SeparatorLength then
              //*** разжелитель находится в конце буффера
              SetLength(Buffer, BufferLength - SeparatorLength);
          end;
        end
        else
          CmpPos := 1;

        //*** Если достигнут конец файла, то считать что достигнут разделитель
        if Eof(FHandle) then
          IsSeparator := true;

        if IsSeparator then
        begin
          if Buffer <> '' then
          begin
            if cbIncSortIDBeforeNew.Checked then
              seSortID.Value := seSortID.Value + 1;

            TF_Main(GForm).DM.dsetUpdStructInfo.Append;
            TF_Main(GForm).DM.dsetUpdStructInfo.FN(fnDateEntry).AsDateTime := deDateEntry.Date;
            TF_Main(GForm).DM.dsetUpdStructInfo.FN(fnBuildID).AsInteger := Round(seBuildID.Value);
            TF_Main(GForm).DM.dsetUpdStructInfo.FN(fnSortID).AsInteger := Round(seSortID.Value);

            Stream := TMemoryStream.Create;
            Stream.WriteBuffer(PChar(Buffer)^, Length(Buffer));
            Stream.Position := 0;
            //TBlobField(TF_Main(GForm).DM.dsetUpdStructInfo.FN(fnScript)).AsString := Buffer;
            TBlobField(TF_Main(GForm).DM.dsetUpdStructInfo.FN(fnScript)).LoadFromStream(Stream);
            TF_Main(GForm).DM.dsetUpdStructInfo.Post;

            FreeAndNil(Stream);
          end;
          Buffer := '';
        end;
      end;
    finally
      GT_UpdStructInfo.OnFocusedRecordChanged := GT_UpdStructInfoFocusedRecordChanged;
    end;
    CloseFile(FHandle);
  end;
end;

procedure TF_ConfiguratorUpdateInfo.edSrcCSVFileButtonClick(
  Sender: TObject);
var
  OpenDialog: TOpenDialog;
  FileHandler: TextFile;
  FirstStr: String;
  StringSections: TStringList;
  HaveEmptySection: Boolean;
  i, j: integer;

  PosNamePref: Integer;
  NearFieldName: String;

  ListItem: TListitem;
begin
  OpenDialog := TOpenDialog.Create(Self);
  try
    OpenDialog.Filter := 'CSV files (*.csv)|*.csv';
    if OpenDialog.Execute then
    begin
      //*** Прочитать первую строку файла
      FirstStr := '';
      AssignFile(FileHandler, OpenDialog.FileName);
      Reset(FileHandler);
      try
        while Not Eof(FileHandler) do
        begin
          // Прочитать строку
          ReadLn(FileHandler, FirstStr);
          // Получить список непустых секций
          StringSections := GetStringsFromStr(FirstStr, ';', false);
          try
            if StringSections.Count > 0 then
            begin
              edSrcCSVFile.Text := OpenDialog.FileName;

              // Получить имя таблици
              edUpdateTableName.Text := AnsiUpperCase(ExtractFileNameOnly(OpenDialog.FileName));

              lvUpdateFields.Items.Clear;
              for i := 0 to StringSections.Count - 1 do
              begin
                if i = 0 then
                  edUpdateKeyField.Text := StringSections[i]
                else
                begin
                  ListItem := lvUpdateFields.Items.Add;
                  ListItem.Checked := false;
                  ListItem.Caption := StringSections[i];

                  NearFieldName := StringSections[i];
                  for j := 0 to cbSrcLang.Items.Count - 1 do
                  begin
                    PosNamePref := Pos('_'+cbSrcLang.Items[j], NearFieldName);
                    if PosNamePref <> 0 then
                    begin
                      Delete(NearFieldName, PosNamePref, Length(NearFieldName)-(PosNamePref-1) );
                      if ListItem.SubItems.Count = 0 then
                        ListItem.SubItems.Add('');
                      ListItem.SubItems[0] := NearFieldName;
                      Break; //// BREAK ////
                    end;
                  end;
                end;
              end;
              Break; //// BREAK ////
            end;
          finally
            FreeAndNil(StringSections);
          end;
        end;
      finally
        CloseFile(FileHandler);
      end;
    end;
  finally
    OpenDialog.Free;
  end;
end;

procedure TF_ConfiguratorUpdateInfo.btUpdateTableFromCSVFileClick(
  Sender: TObject);
var
  FieldCountToUpd: Integer;
  QSelect: TpFIBQuery;
  QOperat: TpFIBQuery;

  i, j: Integer;
  CurrFieldName: String;
  PriorFieldName: String;
  FieldPosition: Integer;

  KeyFieldName: String;
  UpdateFieldNames: TStringList;
  SrcFileStrings: TStringList;
  FieldListFromFile: TStringList;
  StrSections: TStringList;

  KeyFieldIndex: Integer;
  KeyFieldValue: String;
  FieldIndex: Integer;
  UpdFieldValue: String;

  UpdatedRecordCount: Integer;

  IsLoadedRecord: Boolean;
  NewFldLength: Integer;
  SrcFldName: String;
begin
  try
    lbUpdateFromCSVLog.Items.Clear;

    QSelect := TF_Main(GForm).DM.Query_Select;
    QOperat := TF_Main(GForm).DM.Query_Operat;

    // Определить количество обновляемых полей
    FieldCountToUpd := 0;
    for i := 0 to lvUpdateFields.Items.Count - 1 do
      if lvUpdateFields.Items[i].Checked then
        Inc(FieldCountToUpd);
    if FieldCountToUpd = 0 then
      lbUpdateFromCSVLog.Items.Add('Нет отмеченных полей для обновления')
    else
    if Not CheckExistsTableInBase(TF_Main(GForm).DM.Query_Select, edUpdateTableName.Text) then
       lbUpdateFromCSVLog.Items.Add('Таблици отсутствует в базе')
    else
    if Not CheckFieldInTable(edUpdateTableName.Text, edUpdateKeyField.Text, TF_Main(GForm).DM.Query_Select) then
      lbUpdateFromCSVLog.Items.Add('Не найдено ключевое поле в базе')
    else
    if Not FileExists(edSrcCSVFile.Text) then
      lbUpdateFromCSVLog.Items.Add('Не найден файл '+edSrcCSVFile.Text)
    else
    begin
      lbUpdateFromCSVLog.Items.Add('Проверка отсутствующих полей');
      UpdateFieldNames := TStringList.Create;

      SrcFileStrings := TStringList.Create;
      SrcFileStrings.LoadFromFile(edSrcCSVFile.Text);

      KeyFieldName := edUpdateKeyField.Text;

      // Создать несуществующие поля
      for i := 0 to lvUpdateFields.Items.Count - 1 do
        if lvUpdateFields.Items[i].Checked then
        begin
          CurrFieldName := lvUpdateFields.Items[i].Caption;
          if Not CheckFieldInTable(edUpdateTableName.Text, CurrFieldName, TF_Main(GForm).DM.Query_Select) then
          begin
            NewFldLength := 255;
            // Определяем длину поля
            if Length(CurrFieldName) > 4 then
            begin
              SrcFldName := CurrFieldName;
              Delete(SrcFldName, Length(SrcFldName)-3, 4);
              if CheckFieldInTable(edUpdateTableName.Text, SrcFldName, TF_Main(GForm).DM.Query_Select) then
              begin
                NewFldLength := GetFieldLengthInTable(edUpdateTableName.Text, SrcFldName, TF_Main(GForm).DM.Query_Select);
              end;
            end;

            lbUpdateFromCSVLog.Items.Add('Создание поля '+CurrFieldName);
            TF_Main(GForm).DM.AddFieldToTable(edUpdateTableName.Text, CurrFieldName, ftString, NewFldLength);

            // Установить позицию нового поля
            PriorFieldName := '';
            if lvUpdateFields.Items[i].SubItems.Count > 0 then
              PriorFieldName := lvUpdateFields.Items[i].SubItems[0];
            if PriorFieldName <> '' then
            begin
              if CheckFieldInTable(edUpdateTableName.Text, PriorFieldName, TF_Main(GForm).DM.Query_Select) then
              begin
                // получить позицию предыдущего поля
                FieldPosition := GetFieldPositionInTable(edUpdateTableName.Text, PriorFieldName, TF_Main(GForm).DM.Query_Select);
                if FieldPosition <> -1 then
                begin
                  Inc(FieldPosition, 2);
                  // установить новую позицию нового поля
                  SetFieldPositionInTable(edUpdateTableName.Text, CurrFieldName, FieldPosition, QOperat);
                end;
              end;
            end;
          end;
          UpdateFieldNames.Add(CurrFieldName);
        end;


      // вычитавем список всех полей из файла и обновляем
      SetSQLToFIBQuery(QOperat, GetSQLByParams(qtUpdate, edUpdateTableName.Text,
                       KeyFieldName+' = :'+KeyFieldName, UpdateFieldNames, ''), false);
      //SetSQLToFIBQuery(QSelect, GetSQLByParams(qtSelect, edUpdateTableName.Text,
      //                 KeyFieldName+' = :'+KeyFieldName, UpdateFieldNames, ''), false);
      FieldListFromFile := nil;
      KeyFieldIndex := -1;
      UpdatedRecordCount := 0;
      for i := 0 to SrcFileStrings.Count - 1 do
      begin
        StrSections := nil;

        if FieldListFromFile = nil then
          // в списке полей не должно быть пустых строк
          StrSections := GetStringsFromStr(SrcFileStrings[i], ';', false)
        else
          StrSections := GetStringsFromStr(SrcFileStrings[i], ';', true);

        if StrSections.Count = 0 then
          FreeAndNil(StrSections)
        else
        begin
          // первая не пустая строка содержит поля
          if FieldListFromFile = nil then
          begin
            FieldListFromFile := StrSections;
            // Получить индекс ключевого поля
            KeyFieldIndex := FieldListFromFile.IndexOf(KeyFieldName);
            if KeyFieldIndex = -1 then
              Break; //// BREAK ////
          end
          else
          begin
            KeyFieldValue := StrSections[KeyFieldIndex];

            // Удалиь пробелы
            KeyFieldValue := RemoveSymbolFromStr(KeyFieldValue, ' ');

            if Length(KeyFieldValue) > 0 then
            begin
              if edOpenBracket.Text <> '' then
                if KeyFieldValue[1] <> edOpenBracket.Text[1] then
                  KeyFieldValue := edOpenBracket.Text[1] + KeyFieldValue;
              if edCloseBracket.Text <> '' then
                if KeyFieldValue[Length(KeyFieldValue)] <> edCloseBracket.Text[1] then
                  KeyFieldValue := KeyFieldValue + edCloseBracket.Text[1];
            end;

            lbUpdateFromCSVLog.Items.Add('Обновление записи для '+KeyFieldName+' = '+KeyFieldValue);

            IsLoadedRecord := false;

            QOperat.Close;
            QOperat.ParamByName(KeyFieldName).Value := KeyFieldValue;
            // Внести другие поля
            for j := 0 to UpdateFieldNames.Count - 1 do
              if UpdateFieldNames[j] <> KeyFieldName then
              begin
                UpdFieldValue := '';
                FieldIndex := FieldListFromFile.IndexOf(UpdateFieldNames[j]);
                if FieldIndex <> -1 then
                  if FieldIndex <= (StrSections.Count - 1) then
                    UpdFieldValue := StrSections[FieldIndex];

                { 
                // Если значение пустое, запрещено вносить пустое значение, то вычитываем существующее
                if (UpdFieldValue = '') and cbNotWriteEmptyValues.Checked then
                begin
                  if Not IsLoadedRecord then
                  begin
                    QSelect.Close;
                    QSelect.Params[0].Value := KeyFieldValue;
                    QSelect.ExecQuery;

                    IsLoadedRecord := true;
                  end;
                  if QSelect.RecordCount > 0  then
                    UpdFieldValue := QSelect.FN(UpdateFieldNames[j]).Value;
                end;}

                QOperat.ParamByName(UpdateFieldNames[j]).AsString := UpdFieldValue;
              end;
            QOperat.ExecQuery;
            //QSelect.Close;

            Inc(UpdatedRecordCount);

            FreeAndNil(StrSections);
          end;
        end;
      end;
      QOperat.Close;

      lbUpdateFromCSVLog.Items.Add('Обновлено '+IntToStr(UpdatedRecordCount)+' записей');

      if FieldListFromFile <> nil then
        FreeAndNil(FieldListFromFile);
      FreeAndNil(UpdateFieldNames);
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_ConfiguratorUpdateInfo.btUpdateTableFromCSVFileClick', E.Message);
  end;
end;

procedure TF_ConfiguratorUpdateInfo.miSetPriorFiledClick(Sender: TObject);
var
  NewFieldName: String;
begin
  NewFieldName := InputBox(ApplicationName, 'Введите наименование поля', '');
  if NewFieldName <> '' then
  begin
    if lvUpdateFields.Selected.SubItems.Count = 0 then
      lvUpdateFields.Selected.SubItems.Add('');
    lvUpdateFields.Selected.SubItems[0] := NewFieldName;
  end;
end;

procedure TF_ConfiguratorUpdateInfo.lvUpdateFieldsMouseDown(
  Sender: TObject; Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
var
  ItemFromCursor: TListItem;
  ScrPoint: TPoint;
begin
  if Button = mbRight then
  begin
    ItemFromCursor := lvUpdateFields.GetItemAt(X, Y);
    if ItemFromCursor <> nil then
      lvUpdateFields.Selected := ItemFromCursor;

    GetCursorPos(ScrPoint);
    pmnuLVUpdateFields.Popup(ScrPoint.X, ScrPoint.Y);
  end;
end;


procedure TF_ConfiguratorUpdateInfo.btSetValuesFromLngFldClick(
  Sender: TObject);
var
  i, j, k: Integer;
  TableTextColumnsInfo: TTableTextColumnsInfo;

  FieldListToSel: TStringList;
  FieldListToUpd: TStringList;

  SelectedGUIDs: TStringList;
  SelectedFieldValues: TStringList;

  FieldValue: String;
  QSelect: TpFIBQuery;
  QOperat: TpFIBQuery;
begin
  try
    FieldListToSel := TStringList.Create;
    FieldListToUpd := TStringList.Create;

    SelectedGUIDs := TStringList.Create;
    SelectedFieldValues := TStringList.Create;

    QSelect := TF_Main(GForm).DM.Query_Select;
    QOperat := TF_Main(GForm).DM.Query_Operat;

    meSetTextValuesToActualFields.Clear;

    meSetTextValuesToActualFields.Lines.Add('Начало вкидки');

    Screen.Cursor := crHourGlass;
    try
      for i := 0 to FSprTablesTextColumnsInfo.Count - 1 do
      begin
        TableTextColumnsInfo := TTableTextColumnsInfo(FSprTablesTextColumnsInfo[i]);

        meSetTextValuesToActualFields.Lines.Add(DupStr(' ', 3)+ 'Начало обработки таблици '+TableTextColumnsInfo.TableName);

        FieldListToSel.Clear;
        FieldListToUpd.Clear;

        //FieldListToSel.Add(fnGuid);
        // Отобрать список полей
        //for j := 0 to TableTextColumnsInfo.TextFields.Count - 1 do
        //begin
        //  FieldListToSel.Add(TableTextColumnsInfo.TextFields[j]+'_'+cbSrcLang.Text);
        //  FieldListToUpd.Add(TableTextColumnsInfo.TextFields[j]);
        //end;

        // Запрос на отбор данных
        for j := 0 to TableTextColumnsInfo.TextFields.Count - 1 do
        begin
          meSetTextValuesToActualFields.Lines.Add(DupStr(' ', 6)+ 'Вкидка из поля '+
              TableTextColumnsInfo.TextFields[j]+'_'+cbSrcLang.Text+' в поле '+TableTextColumnsInfo.TextFields[j]);

          FieldListToSel.Clear;
          FieldListToSel.Add(fnGuid);
          FieldListToSel.Add(TableTextColumnsInfo.TextFields[j]+'_'+cbSrcLang.Text);

          FieldListToUpd.Add(TableTextColumnsInfo.TextFields[j]);
          try
            // Отобрать значение из поля
            SetSQLToFIBQuery(QSelect, GetSQLByParams(qtSelect, TableTextColumnsInfo.TableName,
                             '', FieldListToSel, ''), true);
            SelectedGUIDs.Clear;
            SelectedFieldValues.Clear;
            while Not QSelect.Eof do
            begin
              SelectedGUIDs.Add(QSelect.FieldByName(FieldListToSel[0]).AsString);
              SelectedFieldValues.Add(QSelect.FieldByName(FieldListToSel[1]).AsString);
              QSelect.Next;
            end;

            // Вкинуть значение в конечное поле
            SetSQLToFIBQuery(QOperat, GetSQLByParams(qtUpdate, TableTextColumnsInfo.TableName,
                               fnGUID+' = :'+fnGUID, nil, TableTextColumnsInfo.TextFields[j]), false);
            for k := 0 to SelectedGUIDs.Count - 1 do
            begin
              if (SelectedFieldValues[k] <> '') or Not cbNotWriteEmptyValues.Checked then
              begin
                QOperat.Close;
                QOperat.ParamByName(fnGUID).AsString := SelectedGUIDs[k];
                QOperat.ParamByName(TableTextColumnsInfo.TextFields[j]).AsString := SelectedFieldValues[k];
                QOperat.ExecQuery;
              end;
            end;
          except
            on E: Exception do AddExceptionToLogEx('TF_ConfiguratorUpdateInfo.btSetTextValuesToFieldsClick', E.Message);
          end;
        end;
        meSetTextValuesToActualFields.lines.Add(DupStr(' ', 3)+ 'Конец обработки таблици '+TableTextColumnsInfo.TableName);
      end;
      meSetTextValuesToActualFields.Lines.Add('Конец вкидки');

      if cbDelSrcFields.Checked then
      begin
        meSetTextValuesToActualFields.lines.Add('Удаления языковых полей');

        for i := 0 to FSprTablesTextColumnsInfo.Count - 1 do
        begin
          TableTextColumnsInfo := TTableTextColumnsInfo(FSprTablesTextColumnsInfo[i]);
          meSetTextValuesToActualFields.lines.Add(DupStr(' ', 3)+ 'для таблици '+TableTextColumnsInfo.TableName);

          for j := 0 to TableTextColumnsInfo.TextFields.Count - 1 do
            for k := 0 to cbSrcLang.Items.Count - 1 do
            begin
              meSetTextValuesToActualFields.lines.Add(DupStr(' ', 6) + TableTextColumnsInfo.TextFields[j]+'_'+cbSrcLang.Items[k]);
              if CheckFieldInTable(TableTextColumnsInfo.TableName, TableTextColumnsInfo.TextFields[j]+'_'+cbSrcLang.Items[k], QSelect) then
                DelFieldFromTable(TableTextColumnsInfo.TableName, TableTextColumnsInfo.TextFields[j]+'_'+cbSrcLang.Items[k], QOperat);
            end;
        end;
      end;
    finally
      Screen.Cursor := crDefault;
    end;
    if cbPackBase.Checked then
      F_NormBase.Act_PackBase.Execute;


    FreeAndNil(SelectedGUIDs);
    FreeAndNil(SelectedFieldValues);

    FreeAndNil(FieldListToSel);
    FreeAndNil(FieldListToUpd);
  except
    on E: Exception do AddExceptionToLogEx('TF_ConfiguratorUpdateInfo.btSetTextValuesToFieldsClick', E.Message);
  end;
end;

procedure TF_ConfiguratorUpdateInfo.btExportTextFieldsClick(
  Sender: TObject);
var
  DirName: String;
  TableFileName: String;
  QSelect: TpFIBQuery;

  TableTextColumnsInfo: TTableTextColumnsInfo;
  SelectFieldNames: TStringList;
  SelectCondition: String;
  i, j, k: Integer;
  IsCyrSymb: Boolean;
  TableSavedRowCount: Integer;

  FileHandler: TextFile;
begin
  try
    DirName := TF_Main(GForm).BrowseNewDirName('Экспорт текстовых полей в файлы...',
                          '',
                          FileNameCorrect('NormBaseStrings'+' '+DateTimeToStr(Now)));

    QSelect := TF_Main(GForm).DM.Query_Select;

    if DirName <> '' then
    begin
      DirName := DirName + '\';
      if Not DirectoryExists(DirName) then
        CreateDir(DirName);

      Screen.Cursor := crHourGlass;
      try
        lbExportTextValueFields.Clear;
        lbExportTextValueFields.Items.Add('Начало экспорта');

        SelectFieldNames := TStringList.Create;

        for i := 0 to FSprTablesTextColumnsInfo.Count - 1 do
        begin
          TableTextColumnsInfo := TTableTextColumnsInfo(FSprTablesTextColumnsInfo[i]);

          lbExportTextValueFields.Items.Add(DupStr(' ', 3)+ 'Начало экспорта таблици '+TableTextColumnsInfo.TableName);

          try
            // Определить поля для экспорта
            SelectFieldNames.Clear;
            SelectFieldNames.Add(fnGUID);
            for j := 0 to TableTextColumnsInfo.TextFields.Count - 1 do
            begin
              SelectFieldNames.Add(TableTextColumnsInfo.TextFields[j]);
              lbExportTextValueFields.Items.Add(DupStr(' ', 6)+ 'отбор поля '+SelectFieldNames[SelectFieldNames.Count-1]);

              for k := 0 to cbSrcLang.Items.Count - 1 do
              begin
                SelectFieldNames.Add(TableTextColumnsInfo.TextFields[j]+'_'+cbSrcLang.Items[k]);
                lbExportTextValueFields.Items.Add(DupStr(' ', 6)+
                  'отбор поля '+SelectFieldNames[SelectFieldNames.Count-1]+'_'+cbSrcLang.Items[k]);
              end;
            end;
            //for j := 0 to TableTextColumnsInfo.TextFields.Count - 1 do
            //  for k := 0 to cbSrcLang.Items.Count - 1 do
            //  begin
            //    SelectFieldNames.Add(TableTextColumnsInfo.TextFields[j]+'_'+cbSrcLang.Items[k]);
            //    lbExportTextValueFields.Items.Add(DupStr(' ', 6)+
            //      'отбор поля '+SelectFieldNames[SelectFieldNames.Count-1]+'_'+cbSrcLang.Items[k]);
            //  end;



            if TableTextColumnsInfo.TableName = tnProperties then
              SelectFieldNames.Add(fnIDDataType);
            SetSQLToFIBQuery(QSelect, GetSQLByParams(qtSelect, TableTextColumnsInfo.TableName,
                             '', SelectFieldNames, ''), true);
            if TableTextColumnsInfo.TableName = tnProperties then
              SelectFieldNames.Delete(SelectFieldNames.Count-1);

            TableFileName := DirName + TableTextColumnsInfo.TableName+'.'+enCsv;

            lbExportTextValueFields.Items.Add(DupStr(' ', 6)+ 'Сохранение таблици в файл '+TableFileName);
            TableSavedRowCount := 0;

            if QSelect.RecordCount > 0 then
            begin
              AssignFile(FileHandler, TableFileName);
              Rewrite(FileHandler);
              try
                // Записать названия полей
                for j := 0 to SelectFieldNames.Count - 1 do
                begin
                  if j <> 0 then
                    Write(FileHandler, ';');
                  Write(FileHandler, SelectFieldNames[j]);
                end;
                Writeln(FileHandler);

                // Записать значения полей
                while Not QSelect.Eof do
                begin
                  // Проверяем, есть ли в строке русский символ
                  IsCyrSymb := false;
                  for j := 0 to SelectFieldNames.Count - 1 do
                  begin
                    if CheckStrHaveRusSymb(QSelect.FN(SelectFieldNames[j]).AsString) then
                    begin
                      IsCyrSymb := true;
                      Break; //// BREAK ////
                    end;
                  end;

                  if IsCyrSymb then
                  begin
                    for j := 0 to SelectFieldNames.Count - 1 do
                    begin
                      if j <> 0 then
                        Write(FileHandler, ';');

                      // пишем пустое знач. если поле "знач по умолчанию" не строкового типаЫ
                      if (TableTextColumnsInfo.TableName = tnProperties) and
                         (SelectFieldNames[j] = fnDefValue) and
                         (QSelect.FN(fnIDDataType).AsInteger <> dtString) then
                        Write(FileHandler, '')
                      else
                        Write(FileHandler, CorrectStrToCSV(QSelect.FN(SelectFieldNames[j]).AsString));
                    end;
                    Writeln(FileHandler);

                    TableSavedRowCount := TableSavedRowCount + 1;
                  end;
                  QSelect.Next;
                end;
              finally
                CloseFile(FileHandler);
              end;
            end;
          except
            on E: Exception do AddExceptionToLogEx('TF_ConfiguratorUpdateInfo.btExportTextFieldsClick', E.Message);
          end;

          if TableSavedRowCount = 0 then
            lbExportTextValueFields.Items.Add(DupStr(' ', 3)+ 'Нету строк для экспорта, файл не создан')
          else
            lbExportTextValueFields.Items.Add(DupStr(' ', 3)+ IntToStr(TableSavedRowCount)+ ' строк');
          lbExportTextValueFields.Items.Add(DupStr(' ', 3)+ 'Конец экспорта таблици '+TableTextColumnsInfo.TableName);
        end;
        lbExportTextValueFields.Items.Add('Конец экспорта');

        FreeAndNil(SelectFieldNames);
      finally
        Screen.Cursor := crDefault;
      end;
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_ConfiguratorUpdateInfo.btExportTextFieldsClick', E.Message);
  end;
end;

procedure TF_ConfiguratorUpdateInfo.btCheckCyrillicClick(Sender: TObject);
var
  i, j, k: Integer;
  TableTextColumnsInfo: TTableTextColumnsInfo;
  SelFieldNames: TStringList;

  LogStr: String;
  TablesTextColumnsInfo: TObjectList;

  TablesNames: TStringList;
  TableFields: TStringList;
  TableFieldNames: TStringList;
  FieldTypes: TIntList;

  QSelect: TpFIBQuery;
  TableWordCount: Integer;
  AllWoardCount: Integer;
begin
  try

    QSelect := TF_Main(GForm).DM.Query_Select;

    {
    lbSetTextValuesToActualFields.Clear;
    lbSetTextValuesToActualFields.Items.Add('Начало проверки');


    SelFieldNames := TStringList.Create;


    TablesTextColumnsInfo := TObjectList.Create(false);
    TablesTextColumnsInfo.Assign(FSprTablesTextColumnsInfo);
    TablesTextColumnsInfo.Assign(FTablesTextColumnsInfo, laOr);

    for i := 0 to TablesTextColumnsInfo.Count - 1 do
    begin
      TableTextColumnsInfo := TTableTextColumnsInfo(TablesTextColumnsInfo[i]);

      lbSetTextValuesToActualFields.Items.Add(DupStr(' ', 3)+ 'Начало проверки таблици '+TableTextColumnsInfo.TableName);

      SelFieldNames.Clear;
      SelFieldNames.AddStrings(TableTextColumnsInfo.TextFields);
      if SelFieldNames.Count > 0 then
        SelFieldNames.Add(fnGuid);

      SetSQLToFIBQuery(QSelect, GetSQLByParams(qtSelect, TableTextColumnsInfo.TableName,
                             '', SelFieldNames, ''), true);
      while Not QSelect.Eof do
      begin
        LogStr := '';
        for j := 0 to TableTextColumnsInfo.TextFields.Count - 1 do
        begin
          if CheckStrHaveRusSymb(QSelect.FN(TableTextColumnsInfo.TextFields[j]).AsString) then
          begin
            if LogStr = '' then
              LogStr := 'Запись с '+QSelect.FN(fnGUID).AsString+' поля:';
            LogStr := LogStr + ' '+TableTextColumnsInfo.TextFields[j] + '('+QSelect.FN(TableTextColumnsInfo.TextFields[j]).AsString+')';
          end;
        end;

        if LogStr <> '' then
          lbSetTextValuesToActualFields.Items.Add(LogStr);

        QSelect.Next;
      end;


      lbSetTextValuesToActualFields.Items.Add(DupStr(' ', 3)+ 'Конец проверки таблици '+TableTextColumnsInfo.TableName);
    end;
    FreeAndNil(SelFieldNames);

    FreeAndNil(TablesTextColumnsInfo);

    lbSetTextValuesToActualFields.Items.Add('Конец проверки'); }


    meSetTextValuesToActualFields.Clear;
    meSetTextValuesToActualFields.lines.Add('Начало проверки');

    FieldTypes := TIntList.Create;
    FieldTypes.Add(iftChar);
    FieldTypes.Add(iftVarChar);

    TablesNames := GetTablesFromBase(QSelect);
    TableFieldNames := TStringList.Create;

    AllWoardCount := 0;

    for i := 0 to TablesNames.Count - 1 do
    begin
      TableFields := GetFieldsFromTable(TablesNames[i], FieldTypes, QSelect);

      // Если в таблице есть поле GUID и еще как минимум одно строковое поле
      if (TableFields.IndexOf(fnGuid) <> -1) and (TableFields.Count > 1) then
      begin
        TableWordCount := 0;
        TableFieldNames.Clear;

        meSetTextValuesToActualFields.lines.Add(DupStr(' ', 2)+ 'Таблица '+TablesNames[i]);
        meSetTextValuesToActualFields.lines.Add(DupStr(' ', 2)+ '{');

        SetSQLToFIBQuery(QSelect, GetSQLByParams(qtSelect, TablesNames[i],
                             '', TableFields, ''), true);
        while Not QSelect.Eof do
        begin
          LogStr := '';
          for j := 0 to TableFields.Count - 1 do
          begin
            if CheckStrHaveRusSymb(QSelect.FN(TableFields[j]).AsString) then
            begin
              if LogStr = '' then
                LogStr := 'Запись с '+QSelect.FN(fnGUID).AsString+' поля:';
              LogStr := LogStr + ' '+TableFields[j] + '('+QSelect.FN(TableFields[j]).AsString+')';
              if TableFieldNames.IndexOf(TableFields[j]) = -1 then
                TableFieldNames.Add(TableFields[j]);

              TableWordCount := TableWordCount + 1;
            end;
          end;

          if LogStr <> '' then
            meSetTextValuesToActualFields.lines.Add(DupStr(' ', 4)+ LogStr);

          QSelect.Next;
        end;

        meSetTextValuesToActualFields.lines.Add(DupStr(' ', 2)+ '} Рус. слов: '+IntToStr(TableWordCount));
        if TableFieldNames.Count > 0 then
        begin
          meSetTextValuesToActualFields.lines.Add(DupStr(' ', 2)+ 'Поля');
          meSetTextValuesToActualFields.lines.Add(DupStr(' ', 2)+ '{');
          for j := 0 to TableFieldNames.Count - 1 do
          begin
            meSetTextValuesToActualFields.lines.Add(DupStr(' ', 4)+ TableFieldNames[j]);
          end;
          meSetTextValuesToActualFields.lines.Add(DupStr(' ', 2)+ '}');
        end;
        AllWoardCount := AllWoardCount + TableWordCount;
      end;
    end;

    meSetTextValuesToActualFields.lines.Add('Всего рус. слов: '+IntToStr(AllWoardCount));
    FreeAndNil(TableFields);

    FreeAndNil(TableFieldNames);
    FreeAndNil(TablesNames);
    FreeAndNil(FieldTypes);
  except
    on E: Exception do AddExceptionToLogEx('TF_ConfiguratorUpdateInfo.btCheckCyrillicClick', E.Message);
  end;
end;

procedure TF_ConfiguratorUpdateInfo.SetValuesToLngFldClick(
  Sender: TObject);
var
  i, j, k: Integer;
  TableTextColumnsInfo: TTableTextColumnsInfo;

  FieldListToSel: TStringList;
  FieldListToUpd: TStringList;

  SelectedGUIDs: TStringList;
  SelectedFieldValues: TStringList;

  FieldValue: String;
  CurrFieldUpd: String;
  QSelect: TpFIBQuery;
  QOperat: TpFIBQuery;
begin
  try
    FieldListToSel := TStringList.Create;
    FieldListToUpd := TStringList.Create;

    SelectedGUIDs := TStringList.Create;
    SelectedFieldValues := TStringList.Create;

    QSelect := TF_Main(GForm).DM.Query_Select;
    QOperat := TF_Main(GForm).DM.Query_Operat;

    meSetTextValuesToActualFields.Clear;

    meSetTextValuesToActualFields.Lines.Add('Начало вкидки');

    Screen.Cursor := crHourGlass;
    try
      for i := 0 to FSprTablesTextColumnsInfo.Count - 1 do
      begin
        TableTextColumnsInfo := TTableTextColumnsInfo(FSprTablesTextColumnsInfo[i]);

        meSetTextValuesToActualFields.Lines.Add(DupStr(' ', 3)+ 'Начало обработки таблици '+TableTextColumnsInfo.TableName);

        FieldListToSel.Clear;
        FieldListToUpd.Clear;

        //FieldListToSel.Add(fnGuid);
        // Отобрать список полей
        //for j := 0 to TableTextColumnsInfo.TextFields.Count - 1 do
        //begin
        //  FieldListToSel.Add(TableTextColumnsInfo.TextFields[j]+'_'+cbSrcLang.Text);
        //  FieldListToUpd.Add(TableTextColumnsInfo.TextFields[j]);
        //end;

        // Запрос на отбор данных
        for j := 0 to TableTextColumnsInfo.TextFields.Count - 1 do
        begin
          CurrFieldUpd := TableTextColumnsInfo.TextFields[j]+'_'+cbSrcLang.Text;

          meSetTextValuesToActualFields.Lines.Add(DupStr(' ', 6)+ 'Вкидка из поля '+
              CurrFieldUpd+' в поле '+TableTextColumnsInfo.TextFields[j]);

          FieldListToSel.Clear;
          FieldListToSel.Add(fnGuid);
          FieldListToSel.Add(TableTextColumnsInfo.TextFields[j]);

          FieldListToUpd.Add(CurrFieldUpd);
          try
            if Not CheckFieldInTable(TableTextColumnsInfo.TableName, CurrFieldUpd, TF_Main(GForm).DM.Query_Select) then
            begin
              meSetTextValuesToActualFields.Lines.Add(DupStr(' ', 6)+ 'Создание поля '+CurrFieldUpd);
              TF_Main(GForm).DM.AddFieldToTable(TableTextColumnsInfo.TableName, CurrFieldUpd, ftString, 255);
            end;

            // Отобрать значение из поля
            SetSQLToFIBQuery(QSelect, GetSQLByParams(qtSelect, TableTextColumnsInfo.TableName,
                             '', FieldListToSel, ''), true);
            SelectedGUIDs.Clear;
            SelectedFieldValues.Clear;
            while Not QSelect.Eof do
            begin
              SelectedGUIDs.Add(QSelect.FieldByName(FieldListToSel[0]).AsString);
              SelectedFieldValues.Add(QSelect.FieldByName(FieldListToSel[1]).AsString);
              QSelect.Next;
            end;

            // Вкинуть значение в конечное поле
            SetSQLToFIBQuery(QOperat, GetSQLByParams(qtUpdate, TableTextColumnsInfo.TableName,
                               fnGUID+' = :'+fnGUID, nil, CurrFieldUpd), false);
            for k := 0 to SelectedGUIDs.Count - 1 do
            begin
              if (SelectedFieldValues[k] <> '') or Not cbNotWriteEmptyValues.Checked then
              begin
                QOperat.Close;
                QOperat.ParamByName(fnGUID).AsString := SelectedGUIDs[k];
                QOperat.ParamByName(CurrFieldUpd).AsString := SelectedFieldValues[k];
                QOperat.ExecQuery;
              end;
            end;
          except
            on E: Exception do AddExceptionToLogEx('TF_ConfiguratorUpdateInfo.btSetTextValuesToFieldsClick', E.Message);
          end;
        end;
        meSetTextValuesToActualFields.lines.Add(DupStr(' ', 3)+ 'Конец обработки таблици '+TableTextColumnsInfo.TableName);
      end;
      meSetTextValuesToActualFields.Lines.Add('Конец вкидки');
    finally
      Screen.Cursor := crDefault;
    end;
    if cbPackBase.Checked then
      F_NormBase.Act_PackBase.Execute;


    FreeAndNil(SelectedGUIDs);
    FreeAndNil(SelectedFieldValues);

    FreeAndNil(FieldListToSel);
    FreeAndNil(FieldListToUpd);
  except
    on E: Exception do AddExceptionToLogEx('TF_ConfiguratorUpdateInfo.btSetValuesToLngFldClick', E.Message);
  end;
end;

procedure TF_ConfiguratorUpdateInfo.btChoiceComponImagesFolderClick(
  Sender: TObject);
var
  NewDir: String;
begin
  NewDir := TF_Main(GForm).BrowseNewDirName('Выберите папку с изображениями', '', '');
  if NewDir <> '' then
    edComponImagesFolder.Text := NewDir;
end;

procedure TF_ConfiguratorUpdateInfo.btComponImgImportClick(
  Sender: TObject);
var
  CanGrab: Boolean;
  fs: TSearchRec;
  ImportedCount: Integer;
  ImageCount: Integer;
  FileCount: Integer;
  FileStatus: String;

  ArtFld: String;
  ArtNo: String;

  QSelect: TpFIBQuery;
  QSelectSmart: TpFIBQuery;
  QSelSrc: TpFIBQuery;
  QUpdate: TpFIBQuery;

  FileStream: TFileStream;

  procedure ShowMsg(const AMsg: String);
  begin
    MessageInfo(AMsg);
    CanGrab := false;
  end;

begin
  CanGrab := true;
  if Not DirectoryExists(edComponImagesFolder.Text) then
    ShowMsg('Папка не найдена');
  if CanGrab then
  begin
    lbComponImgImportLog.Items.Clear;
    ImportedCount := 0;
    ImageCount := 0;
    FileCount := 0;

    ArtFld := '';
    if btImgByArtProducer.Checked then
      ArtFld := fnArticulProducer
    else if btImgByArtDistributor.Checked then
      ArtFld := fnArticulDistributor;

    QSelect := TF_Main(GForm).DM.Query_Select;
    QSelectSmart := nil;
    QUpdate := TF_Main(GForm).DM.Query_Operat;

    QSelectSmart := TF_Main(GForm).DM.Query;
    SetSQLToFIBQuery(QSelectSmart, GetSQLByParams(qtSelect, tnComponent,
      'UPPER('+ArtFld+') CONTAINING :'+ArtFld, nil, fnID), false);

    SetSQLToFIBQuery(QSelect, GetSQLByParams(qtSelect, tnComponent,
      'UPPER('+ArtFld+') = :'+ArtFld, nil, fnID), false);

    SetSQLToFIBQuery(QUpdate, GetSQLByParams(qtUpdate, tnComponent,
      fnID+' = :'+fnID, nil, fnPicture), false);

    if FindFirst(edComponImagesFolder.Text+'*.*', faAnyFile - faDirectory - faVolumeID, fs) = 0 then
      repeat
        if (fs.Attr and faDirectory = 0) and (fs.Name <> '..') then
        begin
          FileStatus := '';
          FileCount := FileCount + 1;
          if ExtractFileExt(AnsiLowerCase(fs.Name)) = '.jpg' then
          begin
            ImageCount := ImageCount + 1;

            ArtNo := ExtractFileNameOnly(fs.Name);

            QSelect.Close;
            QSelect.Params[0].AsString := AnsiUpperCase(ArtNo);
            QSelect.ExecQuery;
            QSelSrc := QSelect;
            if (QSelect.RecordCount = 0) then
            begin
              QSelectSmart.Close;
              QSelectSmart.Params[0].AsString := AnsiUpperCase(CutBeginZeroDefisInArticle(ArtNo));
              QSelectSmart.ExecQuery;
              QSelSrc := QSelectSmart;
            end;

            if QSelSrc.RecordCount > 0 then
            begin
              FileStream := TFileStream.Create(edComponImagesFolder.Text+'\'+fs.Name, fmOpenRead);
              try
                QUpdate.Close;
                QUpdate.ParamByName(fnID).AsInteger := QSelSrc.Fields[0].AsInteger;
                SetParamAsStreamToQuery(QUpdate, fnPicture, FileStream);
                QUpdate.ExecQuery;
                FileStream.Position := 0;
              finally
                FileStream.Free;
              end;
              ImportedCount := ImportedCount + 1;
              FileStatus := 'IMPORTED';
            end
            else
            begin
              FileStatus := 'COMPON NOT EXISTS';
            end;
          end
          else
          begin
            FileStatus := 'NO JPG IMAGE';
          end;

          lbComponImgImportLog.Items.Add(fs.Name+' '+FileStatus);
        end;
      until FindNext(fs) <> 0;
    FindClose(fs);

    lbComponImgImportLog.Items.Add('FileCount - '+IntToStr(FileCount));
    lbComponImgImportLog.Items.Add('ImageCount - '+IntToStr(ImageCount));
    lbComponImgImportLog.Items.Add('ImportedCount - '+IntToStr(ImportedCount));
  end;
end;

procedure TF_ConfiguratorUpdateInfo.btSelectGuideFilesDirClick(Sender: TObject);
var
  NewDir: String;
begin
  NewDir := TF_Main(GForm).BrowseNewDirName('Выберите корневую папку...', '', '');
  if NewDir <> '' then
    edGuideFilesRootDir.Text := NewDir;
end;

procedure TF_ConfiguratorUpdateInfo.btImportGuideFilesClick(
  Sender: TObject);
var
  GuideFileType: Integer;
  IDTopDirType: Integer;
  FileCount: Integer;
begin
  GuideFileType := GetIDFromComboBoxRz(cbGuideFileType);
  // ID папки верхнего уровня
  IDTopDirType := TF_Main(GForm).FNormBase.DM.GetTopIDDirType(GetDirItemTypeByGuideFileType(GuideFileType));
  if IDTopDirType <> 0 then
  begin
    FileCount := 0;
    ImportGuideFiles(edGuideFilesRootDir.Text, IDTopDirType, GuideFileType, @FileCount);
    ShowMessage('Внесено '+IntToStr(FileCount)+' файлов');
  end;
end;

procedure TF_ConfiguratorUpdateInfo.btObjIconNameArticulsClick(
  Sender: TObject);
var
  QSelect: TpFIBQuery;
  QUpdate: TpFIBQuery;
  IconName: String;
  Article: String;
  ArtCount: Integer;

  function FindArticleInName(const AName: String): String;
  var
    Len: Integer;
    i: integer;
  begin
    Result := '';
    Len := Length(AName);
    if Len > 0 then
    begin
      i := 1;
      while i <= Len do
      begin
        if AName[i] = 'R' then
        begin
          inc(i);
          // Заносим число в результат
          while (i <= Len) and (AName[i] in ['0'..'9']) do
          begin
            Result := Result + AName[i];
            inc(i);
          end;
          if Result <> '' then
          begin
            Result := 'R'+Result;
            Break; //// BREAK ////
          end;
        end
        else
          inc(i);
      end;
    end;
  end;

begin
  lbComponImgImportLog.Items.Clear;
  ArtCount := 0;

  QSelect := TF_Main(GForm).FNormBase.DM.Query_Select;
  QUpdate := TF_Main(GForm).FNormBase.DM.Query_Operat;
  // Отбираем наименования уго с 27.08.2010
  SetSQLToFIBQuery(QSelect, GetSQLByParams(qtSelect, tnObjectIcons,
      fnDateIn+' >= ''27.08.2010''', nil, fnID+','+fnGUID+','+fnName), true);
  // Скрипт обновления УГО для дизайна
  SetSQLToFIBQuery(QUpdate, GetSQLByParams(qtUpdate, tnComponent,
      fnArticulProducer+' = :'+fnArticulProducer, nil, fnIDSymbol), false);
  while Not QSelect.Eof do
  begin
    IconName := QSelect.FN(fnName).AsString;
    Article := FindArticleInName(IconName);
    if Article <> '' then
    begin
      // Вносим ссылку на УГО для дизайна
      QUpdate.Close;
      QUpdate.ParamByName(fnArticulProducer).AsString := Article;
      QUpdate.ParamByName(fnIDSymbol).AsInteger := QSelect.FN(fnID).AsInteger;
      QUpdate.ExecQuery;

      ArtCount := ArtCount + 1;
      lbComponImgImportLog.Items.Add(Article+' '+QSelect.FN(fnGUID).AsString);
    end;
    QSelect.Next;
  end;
  lbComponImgImportLog.Items.Add('Article count is '+IntToStr(ArtCount));
  lbComponImgImportLog.Items.SaveToFile('c:\articuls.txt');
end;

procedure TF_ConfiguratorUpdateInfo.btGetNBTreeComponsClick(
  Sender: TObject);
var
  TopNode: TTreeNode;
  Articles: TStringList;
  Names: TStringList;
  CompTypes: TStringList;
  NBCompType: TNBComponentType;

  DefinedArts: TStringList;
  QSelect: TpFIBQuery;

  procedure StepNode(ANode: TTreeNode);
  var
    Dat: PObjectData;
    ChildNode: TTreeNode;
  begin
    Dat := ANode.Data;
    if IsComponItemType(Dat.ItemType) then
    begin
      SetSQLToFIBQuery(QSelect, GetSQLByParams(qtSelect, tnComponent,
        fnID+' = '''+IntToStr(Dat.ObjectID)+'''', nil, fnID+','+fnArticulProducer+','+fnName+','+fnIDComponentType), true);
      if DefinedArts.IndexOf(QSelect.FN(fnArticulProducer).AsString) = -1 then
      begin
        //Articles.Add(QSelect.FN(fnArticulProducer).AsString);
        Articles.Add(''''+QSelect.FN(fnArticulProducer).AsString+''',');
        Names.Add(QSelect.FN(fnName).AsString);

        NBCompType := TF_Main(GForm).FNormBase.GSCSBase.NBSpravochnik.GetComponentTypeObjByID(QSelect.FN(fnIDComponentType).AsInteger);
        if NBCompType = nil then
          CompTypes.Add('')
        else
          CompTypes.Add(NBCompType.ComponentType.GUID+' '+NBCompType.ComponentType.Name);
      end;
    end
    else
    begin
      ChildNode := ANode.getFirstChild;
      while ChildNode <> nil do
      begin
        StepNode(ChildNode);
        ChildNode := ChildNode.getNextSibling;
      end;
    end;
  end;

begin
  Articles := TStringList.Create;
  Names := TStringList.Create;
  CompTypes := TStringList.Create;

  DefinedArts := TStringList.Create;
  DefinedArts.LoadFromFile('c:\articuls_skip.txt');

  QSelect := TF_Main(GForm).FNormBase.DM.Query_Select;

  TopNode := TF_Main(GForm).FNormBase.GetTopNode;
  TopNode := TopNode.getNextSibling;
  StepNode(TopNode);

  meLog.Lines.Clear;
  meLog.Lines.Add('Articles ');
  meLog.Lines.AddStrings(Articles);
  meLog.Lines.Add('');
  meLog.Lines.Add('Names ');
  meLog.Lines.AddStrings(Names);
  meLog.Lines.Add('');
  meLog.Lines.Add('CompTypes ');
  meLog.Lines.AddStrings(CompTypes);

  DefinedArts.Free;
  CompTypes.Free;
  Articles.Free;
  Names.Free;
end;

end.
