unit U_AddComponent;

interface

uses
  Windows, U_LNG, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, ExtDlgs, DBCtrls, Mask, {DBCtrlsEh,}
  DB, FIBDataSet, pFIBDataSet, cxControls, cxContainer, cxEdit, cxCheckBox,
  cxDBEdit, Spin, cxLookAndFeelPainters, cxButtons, cxTextEdit, cxMaskEdit,
  cxSpinEdit, cxDropDownEdit, {cxColorComboBox,} {cxDBColorComboBox,} cxImage,
  cxMemo, cxRadioGroup, ExtCtrls, ComCtrls, cxStyles, cxCustomData,
  cxGraphics, cxFilter, cxData, cxDBData, cxGridLevel, cxClasses,
  cxGridCustomView, cxGridCustomTableView, cxGridTableView,
  cxGridDBTableView, cxGrid, Menus, cxGridBandedTableView, kbmMemTable,
  ActnList, cxCurrencyEdit, ToolWin, cxDataStorage, U_BaseCommon, U_BaseSettings, XPMenu,
  RzEdit, Grids, DBGrids, cxColorComboBox, cxGroupBox, cxDBLookupComboBox,
  cxBlobEdit,

  U_SCSLists, U_SCSClasses, U_SCSComponent, U_BaseConstants,
  RzPanel, RzTabs, RzLabel, cxEditRepositoryItems, cxCalc,
  RzButton, Contnrs, siComp, siLngLnk, RzRadChk, cxLookAndFeels, cxNavigator,
  clipbrd;
 

const
  // Fields indexes
  fiNormIsOn = 1;
  fiNormTotalCost = 8;
  fiResourceIsOn = 1;
  fiResourcePrice = 5;
  fiResourceAdditionalPrice = 6;
  fiResourceKolvo = 7;
  fiResourceCost = 8;

  strNoDefined = cAddComponent_Msg1;

type
  TF_AddComponent = class(TForm)
    OpenPictureDialog1: TOpenPictureDialog;
    PopupMenu: TPopupMenu;
    pmnu_Add: TMenuItem;
    pmnu_Del: TMenuItem;
    pmnu_Edit: TMenuItem;
    ActionList_Component: TActionList;
    Act_AddInterface: TAction;
    Act_DelInterface: TAction;
    Act_EditInterface: TAction;
    Act_AddProperty: TAction;
    Act_DelProperty: TAction;
    Act_EditProperty: TAction;
    Act_Add: TAction;
    Act_Del: TAction;
    Act_Edit: TAction;
    Act_AddComplectEd: TAction;
    Act_DelComplectEd: TAction;
    Act_EditComplectEd: TAction;
    Act_Default: TAction;
    Act_Cancel: TAction;
    Act_AddPort: TAction;
    Act_EditPort: TAction;
    Act_DelPort: TAction;
    Act_AddCableCanalConnector: TAction;
    Act_EditCableCanalConnector: TAction;
    Act_DelCableCanalConnector: TAction;
    pcMain: TRzPageControl;
    tsCommon: TRzTabSheet;
    tsView: TRzTabSheet;
    gbOkCancel: TRzGroupBox;
    Timer_AfterEditProperty: TTimer;
    tsWorkingAndResources: TRzTabSheet;
    gbNorms: TRzGroupBox;
    ToolBar1: TToolBar;
    ToolButton5: TToolButton;
    ToolButton6: TToolButton;
    ToolButton8: TToolButton;
    ToolButton9: TToolButton;
    GroupBox_ResourcesRel: TRzGroupBox;
    ToolBar_Resources: TToolBar;
    ToolButton4: TToolButton;
    ToolButton2: TToolButton;
    ToolButton3: TToolButton;
    Grid_Resources: TcxGrid;
    GT_Resources: TcxGridDBTableView;
    GT_ResourcesNPP: TcxGridDBColumn;
    GT_ResourcesIsOn: TcxGridDBColumn;
    GT_ResourcesCypher: TcxGridDBColumn;
    GT_ResourcesName: TcxGridDBColumn;
    GT_ResourcesIzm: TcxGridDBColumn;
    GT_ResourcesPrice: TcxGridDBColumn;
    GT_ResourcesAdditionalPrice: TcxGridDBColumn;
    GT_ResourcesKolvo: TcxGridDBColumn;
    GT_ResourcesCost: TcxGridDBColumn;
    GT_ResourcesRType: TcxGridDBColumn;
    GL_Resources: TcxGridLevel;
    GroupBox_OtherData: TRzGroupBox;
    ToolBar_OtherData: TToolBar;
    ToolButton_Make: TToolButton;
    ToolButton_Edit: TToolButton;
    ToolButton_Delete: TToolButton;
    ToolButton1: TToolButton;
    Label_AddEditDelComplects: TLabel;
    Grid: TcxGrid;
    GT_Port: TcxGridDBTableView;
    GT_PortNpp: TcxGridDBColumn;
    GT_PortNAME: TcxGridDBColumn;
    GT_PortISBusy: TcxGridDBColumn;
    GT_PortTYPE: TcxGridDBColumn;
    GT_PortKind: TcxGridDBColumn;
    GT_PortNppPort: TcxGridDBColumn;
    GT_PortNameConnected: TcxGridDBColumn;
    GT_PortNameConnectCable: TcxGridDBColumn;
    GT_PortGender: TcxGridDBColumn;
    GT_PortMultiple: TcxGridDBColumn;
    GT_PortisNative: TcxGridDBColumn;
    GT_PortValueI: TcxGridDBColumn;
    GT_PortCoordZ: TcxGridDBColumn;
    GT_PortNumPair: TcxGridDBColumn;
    GT_PortColor: TcxGridDBColumn;
    GT_PortSide: TcxGridDBColumn;
    GT_PortNotice: TcxGridDBColumn;
    GT_Interface: TcxGridDBTableView;
    GT_InterfaceNpp: TcxGridDBColumn;
    GT_InterfaceName: TcxGridDBColumn;
    GT_InterfaceType: TcxGridDBColumn;
    GT_InterfaceKind: TcxGridDBColumn;
    GT_InterfaceGender: TcxGridDBColumn;
    GT_InterfaceIsBusy: TcxGridDBColumn;
    GT_InterfaceMultiple: TcxGridDBColumn;
    GT_InterfaceIsNative: TcxGridDBColumn;
    GT_InterfaceValueI: TcxGridDBColumn;
    GT_InterfaceCoordZ: TcxGridDBColumn;
    GT_InterfaceNumPairsStr: TcxGridDBColumn;
    GT_InterfaceColor: TcxGridDBColumn;
    GT_InterfaceSide: TcxGridDBColumn;
    GT_InterfaceNotice: TcxGridDBColumn;
    GT_Property: TcxGridDBTableView;
    GT_PropertyName: TcxGridDBColumn;
    GT_PropertyPValue: TcxGridDBColumn;
    GT_PropertyIzm: TcxGridDBColumn;
    GT_PropertyTakeIntoConnect: TcxGridDBColumn;
    GT_PropertyTakeIntoJoin: TcxGridDBColumn;
    GT_PropertyDescription: TcxGridDBColumn;
    GT_PropertyDBDataType: TcxGridDBColumn;
    GT_Complects: TcxGridDBTableView;
    GT_ComplectsName: TcxGridDBColumn;
    GT_ComplectsKolvo: TcxGridDBColumn;
    GT_ComplectsPrice1: TcxGridDBColumn;
    GT_ComplectsCost1: TcxGridDBColumn;
    GT_ComplectsPrice2: TcxGridDBColumn;
    GT_ComplectsCost2: TcxGridDBColumn;
    GT_CableCanalConnectors: TcxGridDBTableView;
    GT_CableCanalConnectorsName: TcxGridDBColumn;
    GT_CableCanalConnectorsConnectorType: TcxGridDBColumn;
    GL_PORT: TcxGridLevel;
    GL_Interface: TcxGridLevel;
    GL_Property: TcxGridLevel;
    GL_Complects: TcxGridLevel;
    GL_CableCanalConnectors: TcxGridLevel;
    Panel_TotalCost: TPanel;
    Label6: TLabel;
    CurrencyEdit_ResourcesCost: TcxCurrencyEdit;
    Splitter1: TSplitter;
    Act_AddNorm: TAction;
    Act_AddResourceToMTNorm: TAction;
    Act_EditNormResource: TAction;
    Act_DeleteNormResource: TAction;
    Act_AddResource: TAction;
    Act_EditResource: TAction;
    Act_DelResource: TAction;
    Grid_NORMS: TcxGrid;
    GT_NORMS: TcxGridDBTableView;
    GT_NORMSNPP: TcxGridDBColumn;
    GT_NORMSIsOn: TcxGridDBColumn;
    GT_NORMSCypher: TcxGridDBColumn;
    GT_NORMSName: TcxGridDBColumn;
    GT_NORMSWork_Kind: TcxGridDBColumn;
    GT_NORMSIZM: TcxGridDBColumn;
    GT_NORMSCost: TcxGridDBColumn;
    GT_NORMSKolvo: TcxGridDBColumn;
    GT_NORMSTotalCost: TcxGridDBColumn;
    GT_NORMSZarplat: TcxGridDBColumn;
    GL_NORMS: TcxGridLevel;
    PopupMenu_NormsResources: TPopupMenu;
    N1: TMenuItem;
    N2: TMenuItem;
    N3: TMenuItem;
    N4: TMenuItem;
    PopupMenu_Resources: TPopupMenu;
    N5: TMenuItem;
    N6: TMenuItem;
    N7: TMenuItem;
    EditRepository_Norm: TcxEditRepository;
    EditRepository_NormCurrency_NormCost: TcxEditRepositoryCurrencyItem;
    EditRepository_NormCurrency_NormTotalCost: TcxEditRepositoryCurrencyItem;
    EditRepository_NormCurrency_ResourcePrice: TcxEditRepositoryCurrencyItem;
    EditRepository_NormCurrency_ResourceCost: TcxEditRepositoryCurrencyItem;
    GT_NORMSRType: TcxGridDBColumn;
    BitBtn_OK: TRzBitBtn;
    BitBtn_Cancel: TRzBitBtn;
    cbApplyNorms_: TcxCheckBox;
    cbApplyResources_: TcxCheckBox;
    ToolButton7: TToolButton;
    Act_AddCompDataFromOtherCompon: TAction;
    ToolButton10: TToolButton;
    Act_DublicatePortInterface: TAction;
    N8: TMenuItem;
    GT_InterfaceRNumber: TcxGridDBColumn;
    GT_PortRNumber: TcxGridDBColumn;
    GT_PortInterfRelNames: TcxGridDBColumn;
    GT_NORMSExpenseForLength: TcxGridDBColumn;
    RzPanel3: TRzPanel;
    Label1: TLabel;
    Label_NameShort: TLabel;
    lbCyper: TLabel;
    Label_ArticulDistributor: TLabel;
    Label_ArticulProducer: TLabel;
    Label_NetType: TLabel;
    Label_Izm: TLabel;
    Label_Producer: TLabel;
    Label_Notice: TLabel;
    btCanComplect: TSpeedButton;
    cbApplyCanComplect: TcxCheckBox;
    cbApplyNotice: TcxCheckBox;
    cbApplyProducer: TcxCheckBox;
    cbApplyNetType: TcxCheckBox;
    cbApplyIzm: TcxCheckBox;
    cbApplyArticulDistributor: TcxCheckBox;
    cbApplyArticulProducer: TcxCheckBox;
    cbApplyNameShort: TcxCheckBox;
    cbApplyName: TcxCheckBox;
    Edit_Name: TcxTextEdit;
    Edit_NameShort: TcxTextEdit;
    MaskEdit_Cyper: TRzMaskEdit;
    Edit_ArticulDistributor: TcxTextEdit;
    Edit_ArticulProducer: TcxTextEdit;
    ComboBox_NetType: TcxComboBox;
    Button_ChangeNetType: TcxButton;
    Edit_Izm: TcxTextEdit;
    ComboBox_Producer: TcxComboBox;
    Button_Producer: TcxButton;
    Edit_Notice: TcxTextEdit;
    gbPrice: TRzGroupBox;
    pnSuppliesKind: TRzPanel;
    Label12: TLabel;
    lbPriceSupply: TLabel;
    cbSuppliesKind: TcxComboBox;
    btSuppliesKind: TcxButton;
    cePriceSupply: TcxCurrencyEdit;
    GroupBox_Price: TRzGroupBox;
    Label_Price1: TLabel;
    Label_Price2: TLabel;
    Label_NDS1: TLabel;
    Label_NDS2: TLabel;
    CurrencyEdit_NDS1: TcxCurrencyEdit;
    CurrencyEdit_NDS2: TcxCurrencyEdit;
    CurrencyEdit_Price2: TcxCurrencyEdit;
    CurrencyEdit_Price1: TcxCurrencyEdit;
    cbApplyComponData: TcxCheckBox;
    RzPanel4: TRzPanel;
    Label2: TLabel;
    Label3: TLabel;
    lbSymbolImage: TLabel;
    cbApplySymbol: TcxCheckBox;
    cbApplyComponIcon: TcxCheckBox;
    cbApplyImage: TcxCheckBox;
    Image_CompIcons: TcxImage;
    Button_OpenCompIcons: TcxButton;
    Button_ClearComponIcon: TcxButton;
    Image_Symbol: TcxImage;
    btOpenSymbolImage: TcxButton;
    btClearSymbolImage: TcxButton;
    Image: TcxImage;
    Button_OpenPicture: TcxButton;
    Button_ClearImage: TcxButton;
    RzPanel5: TRzPanel;
    RzPanel1: TRzPanel;
    meDescription: TRzMemo;
    RzPanel2: TRzPanel;
    cbApplyDescription: TcxCheckBox;
    RzPanel6: TRzPanel;
    Label7: TLabel;
    pcApplyForAll: TRzPageControl;
    tsApplyInNB: TRzTabSheet;
    tsApplyInPM: TRzTabSheet;
    pnApplyForCurrentDir: TRzPanel;
    GroupBox_ApplyForAllComponents: TRzGroupBox;
    Act_TurnFromMemTableToSpravochnik: TAction;
    N9: TMenuItem;
    RzGroupBox1: TRzGroupBox;
    cbApplyComponentType: TcxCheckBox;
    ComboBox_ComponentType: TcxComboBox;
    Button_TypeComponent: TcxButton;
    GL_CrossConnection: TcxGridLevel;
    GT_CrossConnection: TcxGridDBTableView;
    GT_CrossConnectionNameFrom: TcxGridDBColumn;
    GT_CrossConnectionNameTo: TcxGridDBColumn;
    GT_CrossConnectionNameWith: TcxGridDBColumn;
    Act_AddCrossConnection: TAction;
    Act_EditCrossConnection: TAction;
    Act_DelCrossConnection: TAction;
    seIndex: TcxSpinEdit;
    lbIndex: TLabel;
    pnProjManElements: TRzPanel;
    Label_UserLength: TLabel;
    cbApplyUserLength: TcxCheckBox;
    SpinEdit_UserLength: TcxSpinEdit;
    gbNameMark: TRzGroupBox;
    Edit_NameMark: TcxTextEdit;
    rbMarkByDefault: TcxRadioButton;
    rbMarkByTemplate: TcxRadioButton;
    GT_InterfaceKolvo: TcxGridDBColumn;
    GT_PortKolvo: TcxGridDBColumn;
    GT_PortKolvoBusy: TcxGridDBColumn;
    GT_InterfaceKolvoBusy: TcxGridDBColumn;
    GT_InterfaceSideSection: TcxGridDBColumn;
    btImportComponByArtProducer: TcxButton;
    lng_Forms: TsiLangLinked;
    CheckBox_HasNds: TRzCheckBox;
    cbComponentIsTemplate: TRzCheckBox;
    cbImportFromTemplate: TRzCheckBox;
    cbCanComplect: TRzCheckBox;
    cbDismount: TRzCheckBox;
    cbUseDismounted: TRzCheckBox;
    cbApplyForCurrentDir: TRzCheckBox;
    cbIncludingSubFolders: TRzCheckBox;
    CheckBox_ApplyForList: TRzCheckBox;
    CheckBox_ApplyForProject: TRzCheckBox;
    CheckBox_ApplyIncludingMark: TRzCheckBox;
    lbSelectFieldsFromApplyInPM: TRzLabel;
    pmSelectApplyFields: TPopupMenu;
    Act_SelectAllApplyFields: TAction;
    Act_DeSelectAllApplyFields: TAction;
    N10: TMenuItem;
    N11: TMenuItem;
    lbSelectFieldsFromApplyInNB: TRzLabel;
    Act_SelectCurrPageAllApplyFields: TAction;
    Act_DeSelectCurrPagetAllApplyFields: TAction;
    N12: TMenuItem;
    N13: TMenuItem;
    cbApplyPrice: TcxCheckBox;
    GT_PropertySysName: TcxGridDBColumn;
    pnApplyNormsResources: TRzPanel;
    cbApplyNorms: TcxCheckBox;
    ToolButton11: TToolButton;
    Act_DelAll: TAction;
    N14: TMenuItem;
    GT_NORMSCountForPoint: TcxGridDBColumn;
    GT_NORMSStepOfPoint: TcxGridDBColumn;
    ToolButton12: TToolButton;
    Act_AddResourceComponToMTNorm: TAction;
    GT_NORMSIsResource: TcxGridDBColumn;
    GT_NORMSGUIDNBCompon: TcxGridDBColumn;
    GT_NORMSTotalKolvo: TcxGridDBColumn;
    btClose: TRzBitBtn;
    cbApplyResources: TcxCheckBox;
    Timer_ChoiceCompType: TTimer;
    lbSpecification: TLabel;
    cbSpecification: TcxComboBox;
    btChangeSpecification: TcxButton;
    cbApplySpecification: TcxCheckBox;
    cbApplyForOnlySelected: TRzCheckBox;
    cbIsMarkInCaptions: TRzCheckBox;
    cbApplyIsMarkInCaptions: TcxCheckBox;
    cbApplyForFocusedProp: TRzCheckBox;
    cbAutoAddInter: TRzCheckBox;
    GT_NORMSLaborTime: TcxGridDBColumn;
    GT_NORMSPricePerTime: TcxGridDBColumn;
    N15: TMenuItem;
    Act_ShowInNormBase: TAction;
    XP_Menu1: TXPMenu;
    cbNotUseUgoBounds: TRzCheckBox;
    procedure Button_OpenPictureClick(Sender: TObject);
    procedure BitBtn_OKClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure BitBtn_CancelClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure btCanComplectClick(Sender: TObject);
    procedure Act_AddInterfaceExecute(Sender: TObject);
    procedure Act_DelInterfaceExecute(Sender: TObject);
    procedure Act_EditInterfaceExecute(Sender: TObject);
    procedure Act_AddPropertyExecute(Sender: TObject);
    procedure Act_EditPropertyExecute(Sender: TObject);
    procedure Act_DelPropertyExecute(Sender: TObject);
    procedure GT_InterfaceTypeGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: string);
    procedure ComboBox_NetTypeKeyPress(Sender: TObject; var Key: Char);
    procedure Button_ChangeNetTypeClick(Sender: TObject);
    procedure CurrencyEdit_Price1_KeyUp(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure CurrencyEdit_Price2KeyUp(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure Act_AddExecute(Sender: TObject);
    procedure Act_DelExecute(Sender: TObject);
    procedure Act_EditExecute(Sender: TObject);
    procedure GridActiveTabChanged(Sender: TcxCustomGrid;
      ALevel: TcxGridLevel);
    procedure ColorEditChange(Sender: TObject);
    procedure GT_PropertyPValueGetProperties(Sender: TcxCustomGridTableItem;
      ARecord: TcxCustomGridRecord;
      var AProperties: TcxCustomEditProperties);
    procedure Act_AddComplectEdExecute(Sender: TObject);
    procedure Act_DelComplectEdExecute(Sender: TObject);
    procedure Act_EditComplectEdExecute(Sender: TObject);
    procedure GridEnter(Sender: TObject);
    procedure GridExit(Sender: TObject);
    procedure FormHide(Sender: TObject);
    procedure GT_InterfaceGenderGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: string);
    procedure FormDestroy(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure Button_OpenCompIconsClick(Sender: TObject);
    procedure Act_DefaultExecute(Sender: TObject);
    procedure GT_InterfaceNumPairsStrGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: string);
    procedure GT_InterfaceSideGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: string);
    procedure GT_InterfaceValueIGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: string);
    procedure Act_CancelExecute(Sender: TObject);
    procedure Edit_NamePropertiesChange(Sender: TObject);
    procedure ComboBox_NetTypePropertiesChange(Sender: TObject);
    procedure GT_InterfaceKindGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: string);
    procedure Button_TypeComponentClick(Sender: TObject);
    procedure Button_ProducerClick(Sender: TObject);
    procedure ComboBox_ComponentTypePropertiesChange(Sender: TObject);
    procedure Act_AddPortExecute(Sender: TObject);
    procedure Act_EditPortExecute(Sender: TObject);
    procedure Act_DelPortExecute(Sender: TObject);
    procedure GT_InterfaceFocusedRecordChanged(
      Sender: TcxCustomGridTableView; APrevFocusedRecord,
      AFocusedRecord: TcxCustomGridRecord;
      ANewItemRecordFocusingChanged: Boolean);
    procedure GT_PortFocusedRecordChanged(Sender: TcxCustomGridTableView;
      APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord;
      ANewItemRecordFocusingChanged: Boolean);
    procedure GT_PropertyFocusedRecordChanged(
      Sender: TcxCustomGridTableView; APrevFocusedRecord,
      AFocusedRecord: TcxCustomGridRecord;
      ANewItemRecordFocusingChanged: Boolean);
    procedure Edit_IzmPropertiesChange(Sender: TObject);
    procedure Edit_NameShortPropertiesChange(Sender: TObject);
    procedure Edit_NameMarkPropertiesChange(Sender: TObject);
    procedure GT_InterfaceNppGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: string);
    procedure Button_ClearImageClick(Sender: TObject);
    procedure Button_ClearComponIconClick(Sender: TObject);
    procedure GT_PortNppGetDisplayText(Sender: TcxCustomGridTableItem;
      ARecord: TcxCustomGridRecord; var AText: string);
    procedure CheckBox_HasNdsPropertiesChange(Sender: TObject);
    procedure Act_AddCableCanalConnectorExecute(Sender: TObject);
    procedure Act_EditCableCanalConnectorExecute(Sender: TObject);
    procedure Act_DelCableCanalConnectorExecute(Sender: TObject);
    procedure GT_CableCanalConnectorsConnectorTypeGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: string);
    procedure CheckBox_ApplyForProjectPropertiesChange(Sender: TObject);
    procedure CheckBox_ApplyForListPropertiesChange(Sender: TObject);
    procedure Edit_NameShortKeyPress(Sender: TObject; var Key: Char);
    procedure btOpenSymbolImageClick(Sender: TObject);
    procedure btClearSymbolImageClick(Sender: TObject);
    procedure rbMarkByDefaultClick(Sender: TObject);
    procedure rbMarkByTemplateClick(Sender: TObject);
    procedure Edit_NameMarkEditing(Sender: TObject; var CanEdit: Boolean);
    procedure Timer_AfterEditPropertyTimer(Sender: TObject);
    procedure GT_PropertyEditValueChanged(Sender: TcxCustomGridTableView;
      AItem: TcxCustomGridTableItem);
    procedure GT_PropertyEditChanged(Sender: TcxCustomGridTableView;
      AItem: TcxCustomGridTableItem);
    procedure SpinEdit_UserLengthPropertiesEditValueChanged(
      Sender: TObject);
    procedure GT_NORMSCellClick(Sender: TcxCustomGridTableView;
      ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
      AShift: TShiftState; var AHandled: Boolean);
    procedure GT_NORMSEditing(Sender: TcxCustomGridTableView;
      AItem: TcxCustomGridTableItem; var AAllow: Boolean);
    procedure GT_NORMSFocusedRecordChanged(Sender: TcxCustomGridTableView;
      APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord;
      ANewItemRecordFocusingChanged: Boolean);
    procedure GT_NORMSCostPropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure GT_NORMSKolvoPropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure GT_ResourcesPricePropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure GT_ResourcesAdditionalPricePropertiesValidate(
      Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure GT_ResourcesKolvoPropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure Act_AddNormExecute(Sender: TObject);
    procedure Act_AddResourceToMTNormExecute(Sender: TObject);
    procedure Act_EditNormResourceExecute(Sender: TObject);
    procedure Act_DeleteNormResourceExecute(Sender: TObject);
    procedure Act_AddResourceExecute(Sender: TObject);
    procedure Act_EditResourceExecute(Sender: TObject);
    procedure Act_DelResourceExecute(Sender: TObject);
    procedure GT_NORMSRTypeGetDisplayText(Sender: TcxCustomGridTableItem;
      ARecord: TcxCustomGridRecord; var AText: string);
    procedure cbApplyForCurrentDirPropertiesChange(Sender: TObject);
    procedure cbSuppliesKindPropertiesChange(Sender: TObject);
    procedure btSuppliesKindClick(Sender: TObject);
    procedure Act_AddCompDataFromOtherComponExecute(Sender: TObject);
    procedure CurrencyEdit_Price1Exit(Sender: TObject);
    procedure cbApplyComponDataClick(Sender: TObject);
    procedure Act_DublicatePortInterfaceExecute(Sender: TObject);
    procedure GT_InterfaceRNumberGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: string);
    procedure GT_PortRNumberGetDisplayText(Sender: TcxCustomGridTableItem;
      ARecord: TcxCustomGridRecord; var AText: string);
    procedure GT_NORMSNPPGetDisplayText(Sender: TcxCustomGridTableItem;
      ARecord: TcxCustomGridRecord; var AText: string);
    procedure gbOkCancelResize(Sender: TObject);
    procedure Act_TurnFromMemTableToSpravochnikExecute(Sender: TObject);
    procedure Act_AddCrossConnectionExecute(Sender: TObject);
    procedure Act_EditCrossConnectionExecute(Sender: TObject);
    procedure Act_DelCrossConnectionExecute(Sender: TObject);
    procedure seIndexPropertiesChange(Sender: TObject);
    procedure Act_EnterExecute(Sender: TObject);
    procedure cePriceSupplyKeyUp(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure cbDismountClick(Sender: TObject);
    procedure GT_CableCanalConnectorsDblClick(Sender: TObject);
    procedure ComboBox_ComponentTypeExit(Sender: TObject);
    procedure GT_NORMSEditChanged(Sender: TcxCustomGridTableView;
      AItem: TcxCustomGridTableItem);
    procedure GT_NORMSEditValueChanged(Sender: TcxCustomGridTableView;
      AItem: TcxCustomGridTableItem);
    procedure btImportComponByArtProducerClick(Sender: TObject);
    procedure lbSelectFieldsFromApplyInPMClick(Sender: TObject);
    procedure Act_SelectAllApplyFieldsExecute(Sender: TObject);
    procedure Act_DeSelectAllApplyFieldsExecute(Sender: TObject);
    procedure lbSelectFieldsFromApplyInNBClick(Sender: TObject);
    procedure Act_SelectCurrPageAllApplyFieldsExecute(Sender: TObject);
    procedure Act_DeSelectCurrPagetAllApplyFieldsExecute(Sender: TObject);
    procedure GT_PropertyPValueGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_PropertyIzmGetDisplayText(Sender: TcxCustomGridTableItem;
      ARecord: TcxCustomGridRecord; var AText: String);
    procedure GT_NORMSExpenseForLengthGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_NORMSExpenseForLengthPropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure GT_NORMSInitEdit(Sender: TcxCustomGridTableView;
      AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit);
    procedure GT_InterfaceCoordZGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure pcMainChanging(Sender: TObject; NewIndex: Integer;
      var AllowChange: Boolean);
    procedure Act_DelAllExecute(Sender: TObject);
    procedure GT_NORMSCountForPointPropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure GT_NORMSStepOfPointGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure GT_NORMSStepOfPointPropertiesValidate(
      Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure Act_AddResourceComponToMTNormExecute(Sender: TObject);
    procedure GT_NORMSCustomDrawCell(Sender: TcxCustomGridTableView;
      ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
      var ADone: Boolean);
    procedure GT_NORMSTotalKolvoGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure ComboBox_ProducerPropertiesChange(Sender: TObject);
    procedure cePriceSupplyPropertiesChange(Sender: TObject);
    procedure Edit_NoticePropertiesChange(Sender: TObject);
    procedure Timer_ChoiceCompTypeTimer(Sender: TObject);
    procedure btChangeSpecificationClick(Sender: TObject);
    procedure GT_NORMSLaborTimePropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure GT_NORMSPricePerTimePropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure GT_NORMSLaborTimeGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure Act_ShowInNormBaseExecute(Sender: TObject);
    procedure Edit_NameDblClick(Sender: TObject);
  private
    { Private declarations }
    GForm: TForm;
    FMakeEdit: TMakeEdit;

    InterfFields: TStringList;
    PortFields: TStringList;
    PropertFields: TStringList;
    ComplectsFields: TStringList;
    IOfI_RelFields: TStringList;
    ComponIconsFields: TStringList;
    CableCanalConnectorsFields: TStringList;
    //CrossConnectionsFields: TStringList;

    GGenLastCableCanalConnectorID: Integer;
    GGenLastCompPropRelID: Integer;
    GGenLastCrossConnectionID: Integer;
    GGenLastInterfID: Integer;
    GGenLastPortInterfRelID: Integer;
    GGenLastNormID: Integer;
    GGenLastResourceID: Integer;
    //GGenLastPropertyID: Integer;

    GLastPort: Integer;
    GWasChanging: Boolean;
    FIsLoadingForm: Boolean;

    FApplyCheckBoxes: TObjectList;
    FApplyCheckBoxesBorderColor: TColor;
    FApplyCheckBoxesBorderStyle: TcxEditBorderStyle;
    FApplyCheckBoxesPageIndex: TIntList;
    FApplyControls: TObjectList;
    FApplyComponElementsVisible: TIntList;
    FApplyComponElementsChecked: TIntList;

    FComponBeforeEdit: TSCSComponent;
    FCurrComponentType: TComponentType;
    FCurrency: TCurrency;
    FNBCurrency: TCurrency;
    FIDCatalog: Integer;
    FOutNormsResources: TSCSNormsResources;
    FTraccaLength: Double;

    FSuppliesKind: TSuppliesKind;

    FSpravochnik: TSpravochnik;
    FProjSpravochnik: TSpravochnik;
    FListSpravochnik: TSpravochnik;

    FChangedComponTypeInCombo: Boolean;
    FIsTemplate: Boolean;

    procedure OncbApplyForChange(Sender: TObject);
    procedure OncbApplyForPMChange(Sender: TObject);
    procedure SetGenLastID(ATableKind: TTableKind);
    function GetMaxNumPair(AMemTable: TkbmMemTable): Integer;
    function GenNewID(ATableKind: TTableKind): Integer;
    //function GetStrWithoutSpaces(AString: String): String;

    procedure AddApplyCheckBoxToList(ACheckBox: TcxCheckBox; APageIndex: Integer);
    function CheckRequiredProperties: Boolean;
    procedure ClearFormGrids;
    procedure ClearPortInterfaceMemTable(AMemTable: TkbmMemTable; AIsPort: Boolean);
    function CreateFormOnlyComponent: TSCSComponent;
    function CreateFormComponent: TSCSComponent;
    function CreateFormInterfaces: TSCSInterfaces;
    function CreateFormProperties: TList;
    function CreateFormCableCanalConnectors: TList;
    function CreateFormCrossConnections: TSCSObjectList;
    procedure DeleteAllPortsAndInterf;
    function DelRequiredEmptyProps: Boolean;
    function GetComponentActualPrice: Double;
    function GetComponentNameMarkByTemplate: string;
    function GetNormResourcesCountByCompPropRelID(AIDCompPropRel: Integer): Integer;
    function GetSignType: Integer;
    procedure ImportComponentByID(AID: Integer);
    procedure SetAsDeletedMTRecords(AMemTable, ADetailMemTable: TkbmMemTable;
      ADeletedIDs, ADeletedIDsFromDetail: TIntList);

    procedure SendComponentToForm(AComponent: TSCSComponent; AFromChangeComponType: Boolean);
    procedure SendInterfacesPortsToMemTable(ASCSComponent: TSCSComponent; AAsNew, AAskDelInterf: Boolean);

    procedure DefineComponCurrencies;
    procedure DefineComponSecondPrice(AFirstPrice: Double);
    procedure DefineNormResByProperty(Aproperty: PProperty);
    procedure DefineParamsBySupply(APriceSupply: Double; ADefIzm: Boolean);
    procedure DefineSupplyPriceByComponActualPrice;
    procedure DefineSupplyPriceByComponPrice(AComponPrice: Double);
    procedure DefinecbApplyCompData;
    procedure DefineUniversalInterfacesByProperty(AProp: PProperty; const ACompTypeSysName: string);
    procedure DeleteNormResByIDCompPropRel(AIDCompPropRel: Integer);
    procedure LoadNetTypesToForm;
    procedure LoadCompSpecificationToForm;
    procedure LoadProducersToForm;
    procedure LoadSuppliesKindsToForm;
    // Для новых норм ресурсов, пришедших из новых свойств, устанавливает новый ID Свойства
    procedure SetNewCompPropIDsToNormRes(AOldCompPropIDs, ANewCompPropIDs: TintList);
    procedure SetValueToAllApplyCheckBoxes(AValue: Boolean);
    procedure SetValueToCurrPageApplyCheckBoxes(AValue: Boolean);
    procedure VisibleApplyCheckBoxes(AVisible, ASetAsChecked: Boolean);

    procedure OnChangeComponPropertyVal(AProperty: PProperty; AOldProperty: PProperty=nil);
    procedure OnSetComponPropertyVal(AMakeEdit: TMakeEdit; AProperty: PProperty; AOldProperty: PProperty=nil);
    procedure OnControlChange(Sender: TObject);
  public
    { Public declarations }
    //Tolik 21/02/2022 --
    GComponGuidNB: String;
    //
    GFormMode: TFormMode;

    GIDComponent: Integer;
    GIDObjectIcon: Integer;
    GIDSymbolImage: Integer;
    GGUIDObjectIcon: string;
    GGUIDSymbolImage: string;

    GName_Currency: string;
    GID_Currency: Integer;
    GCompAdded: Boolean;
    GChangedPicture: Boolean;
    GChangedInterface: Boolean;
    GChangedProperty: Boolean;
    GChangedComplect: Boolean;
    GChangedObjectIcons: Boolean;
    GChangedUserLength: Boolean;
    GChangedIndex: Boolean;
    GChangedNameShort: Boolean;
    GisEditingPrice: Boolean;
    GColors: TStringList;

    GDeletedInterfRel: TIntList;
    GDeletedPort: TIntList;
    GDeletedPortInterfRels: TIntList;
    //GDeletedComponIcons: TIntList;
    GDeletedPropRel: TIntList;
    GDeletedComplects: TIntList;
    GDeletedIOfIRel: TIntList;
    GDeletedCableCanalConnectors: TIntList;
    GDeletedCrossConnections: TIntList;
    GDeletedNormID: TIntList;
    GDeletedResourceID: TIntList;

    property ApplyComponElementsChecked: TIntList read FApplyComponElementsChecked write FApplyComponElementsChecked;

    procedure EnableButtons;
    procedure EnableDisableApplyIncludingMark;
    function GetComponentType: TComponentType;
    procedure SetControls(APrevCompType: PComponentType);
    procedure SetReadOnlyToControls(AReadOnly: Boolean);
    procedure SetSupplyKindControls;

    //Function   GetIDFromComboBox: Integer;

    function PriceWithNDS(APrice, ANDS: Double): Double;
    function PriceWithoutNDS(APrice, ANDS: Double): Double;
    procedure SetCalcPrice;
    procedure ShowNDSPrice;
    procedure EnableMakeEditCompon(AEnable: Boolean);
    procedure RefreshFields(ATarget: TkbmMemTable; ASTableName,
      ATargetKeyName, ASourceKeyName: string; AFieldsNames: TStringList);
    procedure EnableControl(AEnable: Boolean);
    procedure SetVisibleByIsLine(AIsLineType: Integer);
    procedure VisibleInterfaceColumns(AVisible: Boolean);
    function GetMainformName: string;
    function GetPropertyBySysName(ASysyName: string): string;
    function GetPropertyBySysNameAsFloat(ASysyName: string): Double;
    function isBusyInterface: Boolean;
    procedure SetPropertyValueBySysName(ASysyName, AValue: string);
    procedure SetPropertyValueBySysNameAsFloat(ASysyName: string; AValue: Double);
    //Procedure AddPropertyToNBCompon(aProp: PProperty); // Tolik 05/03/2021 --
    Procedure AddPropertyToNBCompon(aProp: TNBProperty; aValue: string); // Tolik 05/03/2021 --

    procedure SdvigNppPortAfterDel(ADelNPPPort: Integer);

    procedure AddInterfacePort(AIsPort: Integer);
    procedure EditInterfacePort(AIsPort: Integer);
    procedure DelAllInterfacesPorts(AIsPort: Boolean);
    procedure DelAllProperties;
    procedure DelAllCableCanalConnectors;
    procedure DelAllCrossConnections;
    procedure DelInterfacePort(AIsPort: Integer);
    procedure DelPropsBySysNames(ASysNames: TStringList);
    procedure DefineAllPortInterfRelNames;
    procedure DefineCurrPortInterfRelNames(AAutoEditPost: Boolean);
    function GetInterfPortMemTable: TkbmMemTable;

    procedure AddEditCableCanalConnector(AMakeEdit: TMakeEdit);
    procedure AddEditCrossConnection(AMakeEdit: TMakeEdit);
    procedure AddEditProperty(AMakeEdit: TMakeEdit);

    procedure LoadComponIcon(AIDObjectIcon: Integer; AGUIDObjectIcon: string; ATrgImage: TcxImage);
    procedure LoadImageFromObjectIcons(var AIDIcon: Integer; var AGUIDObjectIcon: string; AImage: TcxImage);
    procedure RefreshCompIcons(AID_CompStateType: Integer);

    procedure AddInterfaceToMT(AmeInterfaceRel: TmeInterfaceRel);

    procedure LoadNormsResources(AAsNew: Boolean);
    procedure SaveNormsResources;
    procedure DelResourcesFromCurrNorm;
    procedure EnableEditDelNorm;
    procedure EnableEditDelResource;
    function GetExistsResourcesIDsFromCurrNorm: TIntList;
    procedure AddEditNorm(AMakeEdit: TMakeEdit);
    procedure AddEditResource(AMakeEdit: TMakeEdit; AMemoryTableKind: TTableKind; AMakeFromCompon: Boolean);
    function GetNewNPP(AMemTable: TkbmMemTable): Integer;
    //procedure SdvigNPP(ANPPAfter: Integer; AMemTable: TkbmMemTable);
    //procedure LoadFromResourceToMT(AResource: TSCSResourceRel; AMakeEdit: TMakeEdit; AMemoryTableKind: TTableKind);
    //procedure LoadFromNormToMT(ASCSNorm: TSCSNorm; AMakeEdit: TMakeEdit; AKolvo: Double);
    //procedure LoadFromMTToResource(AMemoryTableKind: TTableKind; AResourceRel: TSCSResourceRel);
    //procedure LoadFromMTToNorm(ASCSNorm: TSCSNorm);
    procedure CalcNormCost;
    procedure CalcWorkCost;

    procedure ApplyChangedComponentType;
    function ReadOnly: Boolean;

    //function Excecute(AMakeEdit: TMakeEdit; var ): Boolean;

    constructor Create(AOwner: TComponent; AForm: TForm);

    function Execute(AFormMode: TFormMode; AIsTemplate: Boolean): Boolean;
  end;

  {
  var
    F_AddComponent: TF_AddComponent;
                                   }
implementation
uses Unit_DM_scs, U_CaseForm, U_AnswerToQuast, U_AddInterface, U_Main, Math,
  U_CanDelete, U_Common, cxExtEditRepositoryItems, FIBQuery,
  U_MakeEditCrossConnection, U_ComponDesignWizard, U_ChoiceComponType;

{$R *.dfm}

// ############################# My Functions ##################################
// #############################################################################
//
// ##### Показать / запретить кнопки #####

procedure TF_AddComponent.EnableButtons;

  procedure VisibleButtons(AVisible: Boolean);
  begin
    ToolButton_Make.Visible := AVisible;
    ToolButton_Edit.Visible := AVisible;
    ToolButton_Delete.Visible := AVisible;
    //Label_AddEditDelComplects.Align := alRight;
    //Label_AddEditDelComplects.Align := alLeft;
  end;

  procedure EnablDisabl(RecCount, ActiveLevelIndex: Integer);
  begin
    if (RecCount = 0) or (ActiveLevelIndex = liComplects) {or (TF_Main(GForm).GDBMode = bkProjectManager)} then
    begin
      Act_Edit.Enabled := false;
      Act_Del.Enabled := false;
    end
    else
    begin
      Act_Edit.Enabled := true;
      Act_Del.Enabled := true;
    end;
    Act_Add.Enabled := true;
    Act_DublicatePortInterface.Visible := ActiveLevelIndex in [liPort, liInterface];
    Act_DublicatePortInterface.Enabled := (RecCount > 0) and (ActiveLevelIndex in [liPort, liInterface]);

    Act_TurnFromMemTableToSpravochnik.Visible := ActiveLevelIndex in [liPort, liInterface];
    Act_TurnFromMemTableToSpravochnik.Enabled := (RecCount > 0) and (ActiveLevelIndex in [liPort, liInterface]);

    VisibleButtons(true);
    Label_AddEditDelComplects.Visible := (ActiveLevelIndex = liComplects);
    //if ActiveLevelIndex <> liComplects then
    //  //ToolBar_OtherData.Visible := true
    //  VisibleButtons(true)
    //else
    //  //ToolBar_OtherData.Visible := false;
    //  VisibleButtons(false);
  end;

begin
  try
    Act_AddCompDataFromOtherCompon.Visible := (TF_Main(GForm).GDBMode = bkNormBase) and GUseVisibleInterfaces and Not FIsTemplate;
    Act_AddCompDataFromOtherCompon.Enabled := false;
    Act_DelAll.Visible := (TF_Main(GForm).GDBMode = bkNormBase) and Not FIsTemplate;
    with TF_Main(GForm).DM {F_Main.DM} do
      case Grid.ActiveLevel.Index of
        liInterface:
          begin
            if MemTable_InterfaceRelEd.Active then
              EnablDisabl(MemTable_InterfaceRelEd.RecordCount, liInterface)
            else
              EnablDisabl(0, liInterface);

            Act_AddCompDataFromOtherCompon.Enabled := true;
            Act_AddCompDataFromOtherCompon.Hint := cAddComponent_Msg2_1;
          end;
        liPort:
          begin
            if MemTable_PortEd.Active then
              EnablDisabl(MemTable_PortEd.RecordCount, liPort)
            else
              EnablDisabl(0, liPort);

            Act_AddCompDataFromOtherCompon.Enabled := true;
            Act_AddCompDataFromOtherCompon.Hint := cAddComponent_Msg2_2;
          end;
        liProperty:
          begin
            if MemTable_PropertyEd.Active then
              EnablDisabl(MemTable_PropertyEd.RecordCount, liProperty)
            else
              EnablDisabl(0, liProperty);
            //if TF_Main(GForm).GDBMode = bkProjectManager then
            //  Act_Del.Enabled := false;
          end;
        liComplects:
          begin
            if MemTable_ComplectsEd.Active then
              EnablDisabl(MemTable_ComplectsEd.RecordCount, liComplects)
            else
              EnablDisabl(0, liComplects);
          end;
        liCableCanalConnectors:
          begin
            if MemTable_CableCanalConnectorsEd.Active then
              EnablDisabl(MemTable_CableCanalConnectorsEd.RecordCount, liCableCanalConnectors)
            else
              EnablDisabl(0, liCableCanalConnectors);
          end;
        liCrossConnections:
          begin
            if mtCrossConnectionEd.Active then
              EnablDisabl(mtCrossConnectionEd.RecordCount, liCrossConnections)
            else
              EnablDisabl(0, liCrossConnections);
          end;
      end;
    Act_DelAll.Enabled := Act_Del.Enabled;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.EnableButtons: ' + E.Message);
  end;
end;

procedure TF_AddComponent.EnableDisableApplyIncludingMark;
var
  CanEnable: Boolean;
begin
  CanEnable := false;
  if (CheckBox_ApplyForList.Enabled and CheckBox_ApplyForList.Checked) or
    (CheckBox_ApplyForProject.Checked) then
    CanEnable := true;
  CheckBox_ApplyIncludingMark.Enabled := CanEnable;
  lbSelectFieldsFromApplyInPM.Enabled := CanEnable;
end;

function TF_AddComponent.GetComponentType: TComponentType;
var
  SprComponentType: TNBComponentType;
begin
  Result.ID := 0;
  Result.NAME := '';
  Result.NamePlural := '';
  Result.PortKind := pkNone;
  Result.ActiveState := biFalse;
  Result.IsLine := biFalse;
  Result.IsStandart := biFalse;
  if ComboBox_ComponentType.Text <> '' then
  begin
    case TF_Main(GForm).GDBMode of
      bkNormBase:
        Result := TF_Main(GForm).FNormBase.DM.GetComponentType(GetIDFromComboBox(ComboBox_ComponentType));
      bkProjectManager:
        begin
          SprComponentType := nil;
          if TF_Main(GForm).GSCSBase.CurrProject.CurrList <> nil then
            SprComponentType := TF_Main(GForm).GSCSBase.CurrProject.CurrList.Spravochnik.GetComponentTypeWithAssign(
              GetGUIDFromComboBox(ComboBox_ComponentType), TF_Main(GForm).FNormBase.GSCSBase.NBSpravochnik);
          if SprComponentType <> nil then
            Result := SprComponentType.ComponentType;
        end;
    end;
  end;
end;

procedure TF_AddComponent.SetControls(APrevCompType: PComponentType);
var
  GUIDComponType: string;
  GDBMode: TDBKind;
  CanVisible: Boolean;
  ComponentType: TComponentType;
  HardIzm: String;
begin
  FIsLoadingForm := true;
  try
    GDBMode := TF_Main(GForm).GDBMode;

    SetReadOnlyToControls(GFormMode = fmView);

    GUIDComponType := GetGUIDFromComboBox(ComboBox_ComponentType);
    ComponentType := GetComponentType;
    if GUIDComponType = '' then
      GroupBox_OtherData.Enabled := false
    else
      GroupBox_OtherData.Enabled := true;

    //cbSuppliesKindPropertiesChange(cbSuppliesKind);

    //24.09.2007 pnSuppliesKind.Visible := (GDBMode = bkNormBase);

    if ComponentType.IsLine = biTrue then
      GT_InterfaceMultiple.Caption := GetNameInterfaceMultipleForLine //CMultipleLineInterface
    else
      GT_InterfaceMultiple.Caption := CMultiplePoinInterface;
    GL_CableCanalConnectors.Visible := (ComponentType.SysName = ctsnCableChannel) and Not FIsTemplate;
    GL_CrossConnection.Visible := (ComponentType.SysName = ctsnCupBoard) and (GDBMode = bkNormBase) and Not FIsTemplate;
    GL_Interface.Visible := GUseVisibleInterfaces;
    if Not Grid.ActiveLevel.Visible then
      if Grid.Levels.GetAvailableItem <> nil then
        Grid.ActiveLevel := Grid.Levels.GetAvailableItem;


    CanVisible := false;
    if GDBMode = bkProjectManager then
      CanVisible := true;
    //GroupBox_ApplyForAllComponents.Visible := CanVisible;
    //pnApplyForCurrentDir.Visible := Not CanVisible;
    MaskEdit_Cyper.Enabled := not CanVisible;
    lbIndex.Enabled := CanVisible;
    seIndex.Enabled := CanVisible;
    pnProjManElements.Visible := CanVisible;

    GT_NORMSExpenseForLength.Visible := ComponentType.IsLine = biTrue;
    //GT_NORMSExpenseForSection.Visible := ComponentType.IsLine = biTrue;

    SetSupplyKindControls;
    cbUseDismounted.Enabled := cbDismount.Checked;

    //*** Компонент является шаблоном
    cbComponentIsTemplate.Checked := (GIDComponent > 0) and (GIDComponent = ComponentType.IDComponTemplate);

    // Если тип компонента кабель, короб, провод, то выводим единицу измерения из настроек
    HardIzm := GetNameUOMForCompon('', @ComponentType, TF_Main(GForm).FUOM);
    if HardIzm <> '' then
      Edit_Izm.Text := HardIzm
    else
    // Если пред-й тип компоненты был линейны, а тек-й не совсем линейный, то в ед.изм. внести из вида поставки
    if APrevCompType <> nil then
    begin
      if GetNameUOMForCompon('', APrevCompType, TF_Main(GForm).FUOM) <> '' then
        if (FCurrComponentType.IsLine = biFalse) or (FCurrComponentType.CanUseAsPoint = biTrue) then
          if FSuppliesKind.ID <> 0 then
            Edit_Izm.Text := FSuppliesKind.Izm;
    end;
    Edit_Izm.Properties.ReadOnly := (HardIzm <> '');

    cbApplyNorms.Properties.Caption := cAddComponent_Msg17;
    cbApplyResources.Properties.Caption := cAddComponent_Msg18;

    if Not FIsTemplate then
      lbSymbolImage.Caption := cAddComponent_Msg23
    else
      lbSymbolImage.Caption := cAddComponent_Msg24;

    cbComponentIsTemplate.Enabled := GUseComponTemplates;
    cbComponentIsTemplate.Visible := Not FIsTemplate;
    cbImportFromTemplate.Enabled := GUseComponTemplates;
    cbImportFromTemplate.Visible := Not FIsTemplate;

    //Label_ArticulProducer.Enabled := Not FIsTemplate;
    //Edit_ArticulProducer.Enabled := Not FIsTemplate;
    //Label_ArticulDistributor.Enabled := Not FIsTemplate;
    //Edit_ArticulDistributor.Enabled := Not FIsTemplate;

    //Act_AddCompDataFromOtherCompon.Visible := Not FIsTemplate;
    lbCyper.Visible := Not FIsTemplate;
    MaskEdit_Cyper.Visible := Not FIsTemplate;

    //Tolik 15/02/2022 -- разрешить добавлять работы на шаблоны компонентов
    //tsWorkingAndResources.TabVisible := Not FIsTemplate;
    //
    pcApplyForAll.Visible := Not FIsTemplate;


    // Компонент может быть комплектующей
    cbCanComplect.Visible := GUseVisibleInterfaces and Not FIsTemplate;
    btCanComplect.Visible := GUseVisibleInterfaces and Not FIsTemplate;

    //28.08.2013 cbIsMarkInCaptions.Visible := ComponentType.IsLine = biFalse;

    CanVisible := true;
    if GDBMode = bkProjectManager then
      CanVisible := false;
    lbSpecification.Visible := CanVisible;
    cbSpecification.Visible := CanVisible;
    btChangeSpecification.Visible := CanVisible;
  finally
    FIsLoadingForm := true;
  end;
end;

procedure TF_AddComponent.SetReadOnlyToControls(AReadOnly: Boolean);
begin
  BitBtn_OK.Visible := Not AReadOnly;
  BitBtn_Cancel.Visible := Not AReadOnly;
  btClose.Visible := AReadOnly;

  //ComboBox_ComponentType.Properties.ReadOnly := AReadOnly;
  //ComboBox_NetType.Properties.ReadOnly := AReadOnly;
  //ComboBox_Producer.Properties.ReadOnly := AReadOnly;
  //cbSuppliesKind.Properties.ReadOnly := AReadOnly;

  Button_TypeComponent.Enabled := Not AReadOnly;
  Button_ChangeNetType.Enabled := Not AReadOnly;
  Button_Producer.Enabled := Not AReadOnly;
  btSuppliesKind.Enabled := Not AReadOnly;

  Button_OpenPicture.Enabled := Not AReadOnly;
  Button_OpenCompIcons.Enabled := Not AReadOnly;
  btOpenSymbolImage.Enabled := Not AReadOnly;

  Button_ClearImage.Enabled := Not AReadOnly;
  Button_ClearComponIcon.Enabled := Not AReadOnly;
  btClearSymbolImage.Enabled := Not AReadOnly;

  pcApplyForAll.Visible := Not AReadOnly;

  gbOkCancelResize(gbOkCancel);
end;

procedure TF_AddComponent.SetSupplyKindControls;
var
  IDSuppliesKind: Integer;
  GUIDSuppliesKind: string;
begin
  IDSuppliesKind := GetIDFromComboBox(cbSuppliesKind);
  GUIDSuppliesKind := GetGUIDFromComboBox(cbSuppliesKind);

  lbPriceSupply.Enabled := (IDSuppliesKind > 0) or (GUIDSuppliesKind <> '');
  cePriceSupply.Enabled := (IDSuppliesKind > 0) or (GUIDSuppliesKind <> '');
end;

// ##### Получить ID из Комбо списка #####
{Function TF_AddComponent.GetIDFromComboBox: Integer;
var Item: Integer;
    ID_NetType: TObject;
begin
    Result := 0;
    Item := ComboBox_NetType.ItemIndex;
    ID_NetType := ComboBox_NetType.Properties.Items.Objects[item];
    Result := (ID_NetType as TID).ID;
    Item := Result;
end;
}

// ##### Получить цену с НДС #####

function TF_AddComponent.PriceWithNDS(APrice, ANDS: Double): Double;
begin
  Result := Round3(APrice + APrice * (ANDS / 100));
end;

// ##### Полусить Цену без НДС #####

function TF_AddComponent.PriceWithoutNDS(APrice, ANDS: Double): Double;
begin
  Result := APrice - Round3(APrice * (ANDS / (100 + ANDS)));
end;

// Показывать цену с НДС

procedure TF_AddComponent.ShowNDSPrice;
var
  Price1: Double;
  Price2: Double;
begin
  //if RadioGroup_HasNds.ItemIndex = 1 then  // Если цена без НДС, то Показать НДС
  Price1 := 0;
  Price2 := 0;
  //if StrCanBeFloat(CurrencyEdit_Price1.Text) then
  Price1 := StrToFloatU(CorrectStrToFloat(CurrencyEdit_Price1.Text));
  //if StrCanBeFloat(CurrencyEdit_Price2.Text) then
  Price2 := StrToFloatU(CorrectStrToFloat(CurrencyEdit_Price2.Text));
  if not CheckBox_HasNds.Checked then
  begin
    Label_Nds1.Visible := true;
    Label_Nds2.Visible := true;
    CurrencyEdit_NDS1.Visible := true;
    CurrencyEdit_NDS2.Visible := true;
    CurrencyEdit_NDS1.Value := PriceWithNDS(Price1, TF_Main(GForm).GNDS);
    CurrencyEdit_NDS2.Value := PriceWithNDS(Price2, TF_Main(GForm).GNDS);
  end
  else
  begin
    Label_Nds1.Visible := false;
    Label_Nds2.Visible := false;
    CurrencyEdit_NDS1.Visible := false;
    CurrencyEdit_NDS2.Visible := false;
  end;
end;

// ##### Разрешить / Запретить Модифицирование Компоненты(Комплектующей) #####

procedure TF_AddComponent.EnableMakeEditCompon(AEnable: Boolean);
begin
  TF_Main(GForm).Act_MakeComponent.Enabled := AEnable;
  TF_Main(GForm).Act_EditComponent.Enabled := AEnable;
  TF_Main(GForm).Act_DelComponent.Enabled := AEnable;
end;

// ######################## Создать форму ######################################

procedure TF_AddComponent.FormCreate(Sender: TObject);
var
  DBMode: TDBKind;
begin
  DBMode := TF_Main(GForm).GDBMode;
  case DBMode of
    bkNormBase:
      pcApplyForAll.ActivePage := tsApplyInNB;
    bkProjectManager:
      begin
        pcApplyForAll.ActivePage := tsApplyInPM;
        cbComponentIsTemplate.Visible := false;
        cbImportFromTemplate.Visible := false;
      end;
  end;
  cbImportFromTemplate.Checked := true;

  FComponBeforeEdit := TSCSComponent.Create(GForm);

  //*** Если владелец формы "Редактирования компоненты" форма ProjectManager
  //*** то не дать возможность User-у редактировать поле isLine
  {if (GForm as TF_Main).GDBMode = bkProjectManager then
    begin
        Grid.PopupMenu := nil;
        ToolBar_OtherData.Visible := false;

        ActList := TList.Create;
        ActList.Add(Act_Add);
        ActList.Add(Act_AddComplectEd);
        ActList.Add(Act_AddInterface);
        ActList.Add(Act_AddProperty);
        ActList.Add(Act_Edit);
        ActList.Add(Act_EditComplectEd);
        ActList.Add(Act_EditInterface);
        ActList.Add(Act_EditProperty);
        ActList.Add(Act_Del);
        ActList.Add(Act_DelComplectEd);
        ActList.Add(Act_DelInterface);
        ActList.Add(Act_DelProperty);

        for i := 0 to ActList.Count - 1 do
          begin
              TAction(ActList.Items[i]).Enabled := false;
              TAction(ActList.Items[i]).Visible := false;
          end;
        ActList.Free;
    end;  }

  InterfFields := TStringList.Create;
  InterfFields.Add('ID');
  InterfFields.Add('ID_COMPONENT');
  InterfFields.Add('ID_INTERFACE');
  InterfFields.Add('NAME');
  InterfFields.Add('TYPEI');
  InterfFields.Add('Kind');
  InterfFields.Add('IsPort');
  InterfFields.Add('GENDER');
  InterfFields.Add('IsBusy');
  InterfFields.Add('Multiple');
  InterfFields.Add('isNative');
  InterfFields.Add('ValueI');
  InterfFields.Add('SORT_ID');
  InterfFields.Add(fnNpp);
  InterfFields.Add('Num_Pair');
  InterfFields.Add('Color');
  InterfFields.Add('id_adverse');
  InterfFields.Add('Side');
  InterfFields.Add(fnNotice);
  if TF_Main(GForm).GDBMode = bkProjectManager then
    InterfFields.Add('CoordZ');

  PortFields := TStringList.Create;
  PortFields.Add('ID');
  PortFields.Add('ID_COMPONENT');
  PortFields.Add('ID_INTERFACE');
  PortFields.Add(fnNpp);
  PortFields.Add('NAME');
  PortFields.Add(fnNameConnectCable);
  PortFields.Add('TYPEI');
  PortFields.Add('Kind');
  PortFields.Add('IsPort');
  PortFields.Add('IsUser_Port');
  PortFields.Add('Npp_Port');
  PortFields.Add('GENDER');
  PortFields.Add('IsBusy');
  PortFields.Add('Multiple');
  PortFields.Add('isNative');
  PortFields.Add('Color');
  PortFields.Add(fnNotice);
  if TF_Main(GForm).GDBMode = bkProjectManager then
  begin
    PortFields.Add('ID_CONNECTED');
    PortFields.Add('NAME_CONNECTED');
    PortFields.Add('CoordZ');
  end;

  ComponIconsFields := TStringList.Create;
  ComponIconsFields.Add('ID');
  ComponIconsFields.Add('ID_OBJECT_ICON');
  //ComponIconsFields.Add('Name');
  //ComponIconsFields.Add('ICON');

  PropertFields := TStringList.Create;
  PropertFields.Add(fnIsStandart);
  PropertFields.Add(fnIsDefault);
  PropertFields.Add(fnID);
  PropertFields.Add(fnIDMaster);
  PropertFields.Add(fnIDProperty);
  PropertFields.Add(fnIDDataType);
  PropertFields.Add(fnNAME);
  PropertFields.Add(fnSYSNAME);
  PropertFields.Add(fnPVALUE);
  PropertFields.Add(fnIZM);
  PropertFields.Add(fnTakeIntoConnect);
  PropertFields.Add(fnTakeIntoJoin);
  PropertFields.Add(fnIsCrossControl);
  PropertFields.Add(fnIDCrossProperty);
  PropertFields.Add(fnDescription);

  CableCanalConnectorsFields := TStringList.Create;
  CableCanalConnectorsFields.Add(fnID);
  CableCanalConnectorsFields.Add(fnIDComponent);
  CableCanalConnectorsFields.Add(fnIDNBConnector);
  CableCanalConnectorsFields.Add(fnGuidNBConnector);
  CableCanalConnectorsFields.Add(fnConnectorType);
  CableCanalConnectorsFields.Add(fnName);

  ComplectsFields := TStringList.Create;
  ComplectsFields.Add('ID');
  ComplectsFields.Add('ID_COMPONENT');
  ComplectsFields.Add('ID_CHILD');
  ComplectsFields.Add('NAME');
  ComplectsFields.Add('KOLVO');
  ComplectsFields.Add('PRICE1');
  ComplectsFields.Add('COST1');
  ComplectsFields.Add('PRICE2');
  ComplectsFields.Add('COST2');

  IOfI_RelFields := TStringList.Create;

  GDeletedInterfRel := TIntList.Create;
  GDeletedPort := TIntList.Create;
  GDeletedPortInterfRels := TIntList.Create;
  //GDeletedComponIcons := TStringList.Create;
  GDeletedPropRel := TIntList.Create;
  GDeletedComplects := TIntList.Create;
  GDeletedIOfIRel := TIntList.Create;
  GDeletedCableCanalConnectors := TIntList.Create;
  GDeletedCrossConnections := TIntList.Create;
  GDeletedNormID := TIntList.Create;
  GDeletedResourceID := TIntList.Create;

  //*** Загрузить типы сетей
  //FillComboNetType(0);
  ///FillComboBox(ComboBox_NetType, F_NormBase.DM.DataSet_NET_TYPE, 'ID', 'Name');

  GColors := TStringList.Create;
  GColors.Add('dssfsfs');

  GT_Complects.DataController.DataSource := TF_Main(GForm).DM.DataSource_MT_ComplectsEd;
  GT_Property.DataController.DataSource := TF_Main(GForm).DM.DataSource_MT_PropertyEd;
  GT_Interface.DataController.DataSource := TF_Main(GForm).DM.DataSource_MT_INTERFACERelEd;
  GT_PORT.DataController.DataSource := TF_Main(GForm).DM.DataSource_MT_PortEd;
  GT_CableCanalConnectors.DataController.DataSource := TF_Main(GForm).DM.DSrc_MT_CableCanalConnectorsEd;
  GT_CrossConnection.DataController.DataSource := TF_Main(GForm).DM.dsrcMTCrossConnectionEd;

  GT_Norms.DataController.DataSource := TF_Main(GForm).DM.DataSource_MT_NormsEd;
  GT_Resources.DataController.DataSource := TF_Main(GForm).DM.DataSource_MT_ResourcesRelEd;

  GT_InterfaceCoordZ.Visible := false;
  if TF_Main(GForm).GDBMode = bkNormBase then
  begin
    //Label_NameMark.Visible := false;
    //Edit_NameMark.Visible := false;
    //CheckBox_IsUserMark.Visible := false;
    gbNameMark.Visible := false;

    //GT_InterfaceCoordZ.Visible := false;
    GT_InterfaceNpp.Visible := false;
    GT_InterfaceKolvoBusy.Visible := false;

    GT_PORTNpp.Visible := false;
    GT_PORTNppPort.Visible := false;
    GT_PORTNameConnected.Visible := false;
    GT_PORTNameConnectCable.Visible := false;
    GT_PortKolvoBusy.Visible := false;
  end;

  TcxCurrencyEditProperties(GT_InterfaceValueI.Properties).DisplayFormat := GetDisplayFormatForFloat;

  TcxCurrencyEditProperties(GT_ComplectsPrice1.Properties).DisplayFormat := GetDisplayFormatForFloat;
  TcxCurrencyEditProperties(GT_ComplectsCost1.Properties).DisplayFormat := GetDisplayFormatForFloat;
  TcxCurrencyEditProperties(GT_ComplectsPrice2.Properties).DisplayFormat := GetDisplayFormatForFloat;
  TcxCurrencyEditProperties(GT_ComplectsCost2.Properties).DisplayFormat := GetDisplayFormatForFloat;

  //01.11.2013
  GT_NORMSLaborTime.Caption := TF_Main(GForm).GT_NormsResourcesLaborTime.Caption;
  GT_NORMSLaborTime.DataBinding.FieldName := TF_Main(GForm).GT_NormsResourcesLaborTime.DataBinding.FieldName;
  GT_NORMSPricePerTime.Caption := TF_Main(GForm).GT_NormsResourcesPricePerTime.Caption;
  GT_NORMSPricePerTime.DataBinding.FieldName := TF_Main(GForm).GT_NormsResourcesPricePerTime.DataBinding.FieldName;
  TcxCurrencyEditProperties(GT_NORMSPricePerTime.Properties).DisplayFormat := GetDisplayFormatForFloat;
  TcxCurrencyEditProperties(GT_NORMSPricePerTime.Properties).DecimalPlaces := FloatPrecision;

  TcxCurrencyEditProperties(GT_NORMSCost.Properties).DisplayFormat := GetDisplayFormatForFloat;
  TcxCurrencyEditProperties(GT_NORMSCost.Properties).DecimalPlaces := FloatPrecision;
  TcxCurrencyEditProperties(GT_NORMSKolvo.Properties).DisplayFormat := GetDisplayFormatForFloat;
  TcxCurrencyEditProperties(GT_NORMSKolvo.Properties).DecimalPlaces := FloatPrecision;
  GT_NORMSExpenseForLength.DataBinding.FieldName := fnExpenseForLength;
  TcxCurrencyEditProperties(GT_NORMSExpenseForLength.Properties).DisplayFormat := GetDisplayFormatForFloat;
  TcxCurrencyEditProperties(GT_NORMSExpenseForLength.Properties).DecimalPlaces := FloatPrecision;

  GT_NORMSCountForPoint.Caption := cNameCountForPoint;
  GT_NORMSCountForPoint.DataBinding.FieldName := fnCountForPoint;
  TcxCurrencyEditProperties(GT_NORMSCountForPoint.Properties).DisplayFormat := GetDisplayFormatForFloat;
  TcxCurrencyEditProperties(GT_NORMSCountForPoint.Properties).DecimalPlaces := FloatPrecision;

  GT_NORMSStepOfPoint.DataBinding.FieldName := fnStepOfPoint;
  TcxCurrencyEditProperties(GT_NORMSStepOfPoint.Properties).DisplayFormat := GetDisplayFormatForFloat;
  TcxCurrencyEditProperties(GT_NORMSStepOfPoint.Properties).DecimalPlaces := FloatPrecision;

  GT_NORMSTotalKolvo.Caption := cNameTotalkolvo;
  GT_NORMSTotalKolvo.DataBinding.FieldName := fnTotalKolvo;

  tsWorkingAndResources.Caption := cNameAccessoryResourceNorm;

  Act_AddResourceToMTNorm.Hint := Act_AddResourceToMTNorm.Caption; 
  Act_AddResourceComponToMTNorm.Caption := cMain_Msg168;
  Act_AddResourceComponToMTNorm.Hint := Act_AddResourceComponToMTNorm.Caption;

  //TcxCurrencyEditProperties(GT_NORMSExpenseForLength.Properties).
  //TcxLookupComboBoxProperties(GT_NORMSExpenseForLength.Properties).

  EditRepository_NormCurrency_NormCost.Properties.DisplayFormat := GetDisplayFormatForFloat;
  EditRepository_NormCurrency_NormCost.Properties.DecimalPlaces := FloatPrecision;
  EditRepository_NormCurrency_NormTotalCost.Properties.DisplayFormat := GetDisplayFormatForFloat;
  EditRepository_NormCurrency_NormTotalCost.Properties.DecimalPlaces := FloatPrecision;
  EditRepository_NormCurrency_ResourceCost.Properties.DisplayFormat := GetDisplayFormatForFloat;
  EditRepository_NormCurrency_ResourceCost.Properties.DecimalPlaces := FloatPrecision;
  EditRepository_NormCurrency_ResourcePrice.Properties.DisplayFormat := GetDisplayFormatForFloat;
  EditRepository_NormCurrency_ResourcePrice.Properties.DecimalPlaces := FloatPrecision;

  CurrencyEdit_Price1.Properties.DisplayFormat := GetDisplayFormatForFloat;
  CurrencyEdit_Price1.Properties.DecimalPlaces := FloatPrecision;
  CurrencyEdit_Price2.Properties.DisplayFormat := GetDisplayFormatForFloat;
  CurrencyEdit_Price2.Properties.DecimalPlaces := FloatPrecision;
  CurrencyEdit_NDS1.Properties.DisplayFormat := GetDisplayFormatForFloat;
  CurrencyEdit_NDS1.Properties.DecimalPlaces := FloatPrecision;
  CurrencyEdit_NDS2.Properties.DisplayFormat := GetDisplayFormatForFloat;
  CurrencyEdit_NDS2.Properties.DecimalPlaces := FloatPrecision;
  CurrencyEdit_ResourcesCost.Properties.DisplayFormat := GetDisplayFormatForFloat;
  CurrencyEdit_ResourcesCost.Properties.DecimalPlaces := FloatPrecision;
  cePriceSupply.Properties.DisplayFormat := GetDisplayFormatForFloat;
  cePriceSupply.Properties.DecimalPlaces := FloatPrecision;

  FApplyCheckBoxes := TObjectList.Create(False);
  FApplyCheckBoxesPageIndex := TIntList.Create;
  FApplyCheckBoxesBorderColor := clRed;
  FApplyCheckBoxesBorderStyle := ebsSingle;

  AddApplyCheckBoxToList(cbApplyName, 0);
  AddApplyCheckBoxToList(cbApplyNameShort, 0);
  AddApplyCheckBoxToList(cbApplyArticulProducer, 0);
  AddApplyCheckBoxToList(cbApplyArticulDistributor, 0);
  AddApplyCheckBoxToList(cbApplyIzm, 0);
  AddApplyCheckBoxToList(cbApplyUserLength, 0);
  AddApplyCheckBoxToList(cbApplyComponentType, 0);
  AddApplyCheckBoxToList(cbApplyNetType, 0);
  AddApplyCheckBoxToList(cbApplyProducer, 0);
  AddApplyCheckBoxToList(cbApplyIsMarkInCaptions, 0);
  AddApplyCheckBoxToList(cbApplyNotice, 0);
  AddApplyCheckBoxToList(cbApplyCanComplect, 0);
  AddApplyCheckBoxToList(cbApplyPrice, 0);
  AddApplyCheckBoxToList(cbApplyComponData, 0);
  AddApplyCheckBoxToList(cbApplyImage, 1);
  AddApplyCheckBoxToList(cbApplySpecification, 1);
  AddApplyCheckBoxToList(cbApplyComponIcon, 1);
  AddApplyCheckBoxToList(cbApplySymbol, 1);
  AddApplyCheckBoxToList(cbApplyDescription, 1);
  {$IF Defined(NORMSCS_PE) or Defined(SCS_SPA)}
    cbApplyNorms.Visible := false;
  {$ELSE}
    AddApplyCheckBoxToList(cbApplyNorms, 2);
  {$IFEND}
  AddApplyCheckBoxToList(cbApplyResources, 2);

  FApplyControls := TObjectList.Create(False);
  FApplyControls.Add(Edit_Name);
  FApplyControls.Add(Edit_NameShort);
  FApplyControls.Add(Edit_ArticulProducer);
  FApplyControls.Add(Edit_ArticulDistributor);
  FApplyControls.Add(Edit_Izm);
  FApplyControls.Add(SpinEdit_UserLength);
  FApplyControls.Add(ComboBox_ComponentType);
  FApplyControls.Add(ComboBox_NetType);
  FApplyControls.Add(ComboBox_Producer);
  FApplyControls.Add(cbIsMarkInCaptions);
  FApplyControls.Add(Edit_Notice);
  FApplyControls.Add(cbCanComplect);
  FApplyControls.Add(gbPrice);
  FApplyControls.Add(Grid);
  FApplyControls.Add(Image);
  FApplyControls.Add(cbSpecification);
  FApplyControls.Add(Image_CompIcons);
  FApplyControls.Add(Image_Symbol);
  FApplyControls.Add(meDescription);
  //FApplyControls.Add(gbNorms);
  {$IF Defined(NORMSCS_PE) or Defined(SCS_SPA)}
    //
  {$ELSE}
    FApplyControls.Add(gbNorms);
  {$IFEND}
  FApplyControls.Add(gbNorms); //FApplyControls.Add(GroupBox_ResourcesRel);

  FApplyComponElementsVisible := TIntList.Create;
  FApplyComponElementsVisible.Add(BoolToInt(DBMode = bkNormBase)); //liPort = 0
  FApplyComponElementsVisible.Add(BoolToInt(DBMode = bkNormBase)); //liInterface = 1
  FApplyComponElementsVisible.Add(BoolToInt(DBMode = bkNormBase)); //liProperty = 2
  FApplyComponElementsVisible.Add(biFalse); //liComplects = 3
  FApplyComponElementsVisible.Add(BoolToInt(DBMode = bkNormBase)); //liCableCanalConnectors = 4
  FApplyComponElementsVisible.Add(biFalse); //liCrossConnections = 5;

  FApplyComponElementsChecked := TIntList.Create;
  FApplyComponElementsChecked.Add(biTrue); //liPort = 0
  FApplyComponElementsChecked.Add(biTrue); //liInterface = 1
  FApplyComponElementsChecked.Add(biTrue); //liProperty = 2
  FApplyComponElementsChecked.Add(biFalse); //liComplects = 3
  FApplyComponElementsChecked.Add(biTrue); //liCableCanalConnectors = 4
  FApplyComponElementsChecked.Add(biFalse); //liCrossConnections = 5;

  {//10.08.2012
  VisibleApplyCheckBoxes(false, true);
  cbApplyName.Checked := false;
  cbApplyNameShort.Checked := false;
  cbApplyArticulProducer.Checked := false;
  cbApplyArticulDistributor.Checked := false;
  cbApplyPrice.Checked := false;
  cbApplyComponIcon.Checked := false;
  pnApplyNormsResources.Visible := false; }
  VisibleApplyCheckBoxes(false, false);

  pcMain.ActivePage := tsCommon;
  gbOkCancelResize(gbOkCancel);

  //cePriceSupply.Properties
  //cePriceSupply.ValidateEdit()

  FIsLoadingForm := false;
  Edit_Name.Properties.OnChange := OnControlChange;
  Edit_Izm.Properties.OnChange := OnControlChange;
  Edit_NameShort.Properties.OnChange := OnControlChange;
  Edit_NameMark.Properties.OnChange := OnControlChange;
  rbMarkByDefault.OnClick := OnControlChange;
  ComboBox_NetType.Properties.OnChange := OnControlChange;
  //RadioGroup_CanComplect.Properties.OnChange := OnControlChange;
  ComboBox_Producer.Properties.OnChange := OnControlChange;
  cePriceSupply.Properties.OnChange := OnControlChange;
  Edit_Notice.Properties.OnChange := OnControlChange;
  // Tolik 25//11/2019 --
  seIndex.Value := 0;
  //
  cbNotUseUgoBounds.Checked := False; // Tolik 09/03/2021 --
  {$IF Not Defined(FINAL_SCS)}
    btImportComponByArtProducer.Visible := true;
  {$IFEND}
end;

// ##### Удалить форму #####

procedure TF_AddComponent.FormDestroy(Sender: TObject);
begin
  FreeAndNil(InterfFields);
  FreeAndNil(PropertFields);
  FreeAndNil(ComplectsFields);
  FreeAndNil(IOfI_RelFields);
  FreeAndNil(ComponIconsFields);

  FreeAndNil(GDeletedInterfRel);
  FreeAndNil(GDeletedPort);
  FreeAndNil(GDeletedPortInterfRels);
  //GDeletedComponIcons.Clear;
  //GDeletedComponIcons.Free;
  FreeAndNil(GDeletedPropRel);
  FreeAndNil(GDeletedComplects);
  FreeAndNil(GDeletedIOfIRel);
  FreeAndNil(GDeletedCableCanalConnectors);
  FreeAndNil(GDeletedCrossConnections);
  FreeAndNil(GDeletedNormID);
  FreeAndNil(GDeletedResourceID);

  ClearComboBox(ComboBox_ComponentType);
  ClearComboBox(ComboBox_NetType);
  ClearComboBox(ComboBox_Producer);
  ClearComboBox(cbSpecification);

  FApplyCheckBoxes.Free;
  FApplyCheckBoxesPageIndex.Free;
  FApplyControls.Free;

  FApplyComponElementsVisible.Free;
  FApplyComponElementsChecked.Free;

  FreeAndNil(FComponBeforeEdit);
end;

procedure TF_AddComponent.FormClose(Sender: TObject;
  var Action: TCloseAction);
//var SavedID: Integer;
begin
  { with TF_Main(GForm).F_CanDelete do
     ListView_NotDel.OnChange := ListView_NotDelChange; }

   {with TF_Main(GForm).DM do
     begin
         SavedID := pFIBDataSet1.FN('ID').AsInteger;
         SelectInterfaces;
         SearchRecord(pFIBDataSet1, 'ID', SavedID);

         SavedID := DataSet_COMP_PROP_RELATION.FN('ID').AsInteger;
         SelectComponProperty;
         SearchRecord(DataSet_COMP_PROP_RELATION, 'ID', SavedID);

         MemTable_InterfaceRelEd.Active := false;
         MemTable_InterfOfInterf_RelEd.Active := false;
         MemTable_PropertyEd.Active := false;
         MemTable_ComplectsEd.Active := false;
         F_NormBase.DM.MemTable_ComponentIcons.Active := false;
     end; }
  try
    TF_Main(GForm).F_AnswerToQuast.Close;
  except
  end;
end;

// ######################## Показать форму ######################################

procedure TF_AddComponent.FormShow(Sender: TObject);
//var //i: Integer;
    //Ratio: Double;
    //ID_NetType: TObject;
    //Stream: TStream;
    //CurrTreeNode : TTreeNode;
    //ProjManCompon: TSCSComponent;

var   Prop: PProperty; // Tolik 09/03/2021 --
      SCSCompon: TSCSComponent;
begin
  try
    //Tolik 21/02/2022 --
    GComponGuidNB := '';
    //
    cbNotUseUgoBounds.Checked := False; // Tolik 09/03/2021 --
    try
      if GReadOnlyMode then
        bitbtn_Ok.Enabled := False;

      Screen.Cursor := crHourGlass;
      if GL_Interface.Visible then
        Grid.ActiveLevel := GL_Interface;
      GCompAdded := false;
      GChangedPicture := false;
      GChangedInterface := false;
      GChangedProperty := false;
      GChangedComplect := false;
      GChangedObjectIcons := false;
      GChangedUserLength := false;
      GChangedIndex := false;
      GChangedNameShort := false;
      FChangedComponTypeInCombo := false;

      FSpravochnik := nil;
      FProjSpravochnik := nil;
      FListSpravochnik := nil;

      FTraccaLength := 0;
      // преобразовать тек-ю единицу длины в метры
      FTraccaLength := FloatInUOM(1, TF_MAIN(GForm).FUOM, umMetr);

      //TF_Main(GForm).F_CanDelete.ListView_NotDel.OnChange := nil;
      Label_Price1.Caption := cAddComponent_Msg3 + ' ' + TF_Main(GForm).GLocalCurrencyM.Data.NameBrief;
      Label_Price2.Caption := cAddComponent_Msg3 + ' ' + TF_Main(GForm).GLocalCurrencyS.Data.NameBrief;
      GisEditingPrice := false;
      //lbUserLengthUOM.Caption := GetNameUOM(TF_Main(GForm).FUOM, true);
      Label_UserLength.Caption := cAddComponent_Msg16 +', '+GetNameUOM(TF_Main(GForm).FUOM, true);
      GT_InterfaceValueI.Caption := cNameFreeCutset +', '+ GetNameUOM(ConvertUOMToMin(TF_Main(GForm).FUOM), true, false)+'2';
      GT_NORMSExpenseForLength.Caption := cNameExpenseFor +' '+ IntToStr(1)+GetNameUOM(TF_Main(GForm).FUOM, true);
      GT_NORMSStepOfPoint.Caption := TF_Main(GForm).GT_NormsResourcesStepOfPoint.Caption;
      GT_NORMSTotalKolvo.Caption := GetCaptionNormsResourcesTotalKolvo(TF_Main(GForm).FUOM, FTraccaLength);

      ClearComboBox(ComboBox_ComponentType);
      if TF_Main(GForm).GDBMode = bkNormBase then
      begin
        FSpravochnik := TF_Main(GForm).GSCSBase.NBSpravochnik;

        ComboBox_ComponentType.Properties.OnChange := nil;
        FillComboBox(ComboBox_ComponentType, F_NormBase, True, tnComponentTypes, fnID, fnName, '', 0);
        ComboBox_ComponentType.Properties.OnChange := ComboBox_ComponentTypePropertiesChange;
        // Tolik 09/03/2021 --
        if F_NormBase.GSCSBase.SCSComponent <> nil then
        begin
          //Tolik 21/02/2022 -- если стоим на нормативке и на компоненте,
          // то скопировать Гуид компонента
          GComponGuidNB := F_NormBase.GSCSBase.SCSComponent.GuidNB;
          //
          Prop := F_NormBase.GSCSBase.SCSComponent.GetPropertyBySysName(pnNotUseUgoBounds);
          if Prop <> nil then
            if Prop.Value = '1' then
              cbNotUseUgoBounds.Checked := True;
        end;
        //FillComboBox(ComboBox_NetType, F_NormBase, false, tnNetType, fnID, fnName, '', 0);
        //FillComboBox(ComboBox_Producer, F_NormBase, True, tnProducers, fnID, fnName, '', 0);
      end
      else if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        if TF_Main(GForm).GSCSBase.SCSComponent.ProjectOwner <> nil then
        begin
          FProjSpravochnik := TF_Main(GForm).GSCSBase.SCSComponent.ProjectOwner.Spravochnik;
          if TF_Main(GForm).GSCSBase.SCSComponent.ProjectOwner.GetListBySCSID(TF_Main(GForm).GSCSBase.SCSComponent.ListID) <> nil then
            FListSpravochnik := TF_Main(GForm).GSCSBase.SCSComponent.ProjectOwner.GetListBySCSID(TF_Main(GForm).GSCSBase.SCSComponent.ListID).Spravochnik;
          FSpravochnik := FProjSpravochnik;
          //FProjSpravochnik.LoadNetTypesToStrings(ComboBox_NetType.Properties.Items);
          //FProjSpravochnik.LoadProducersToStrings(ComboBox_Producer.Properties.Items, true);
        end;
      end;

      LoadNetTypesToForm;
      LoadProducersToForm;
      LoadSuppliesKindsToForm;
      LoadCompSpecificationToForm;

      ZeroMemory(@FCurrComponentType, SizeOf(TComponentType));

      GDeletedInterfRel.Clear;
      GDeletedPort.Clear;
      GDeletedPortInterfRels.Clear;
      //GDeletedComponIcons.Clear;
      GDeletedPropRel.Clear;
      GDeletedComplects.Clear;
      GDeletedIOfIRel.Clear;
      GDeletedCableCanalConnectors.Clear;
      GDeletedCrossConnections.Clear;

      GLastPort := 0;

      ClearcxImage(Image);
      ClearcxImage(Image_CompIcons);
      ClearcxImage(Image_Symbol);
      CheckBox_ApplyForProject.Checked := false;
      CheckBox_ApplyForList.Checked := false;
      cbApplyForOnlySelected.Checked := false;
      CheckBox_ApplyIncludingMark.Checked := false;
      cbIncludingSubFolders.Enabled := false;
      cbApplyForFocusedProp.Enabled := false;
      cbAutoAddInter.Visible := GUseLiteFunctional;
      if cbAutoAddInter.Checked and Not GUseLiteFunctional then
        cbAutoAddInter.Checked := False;
      cbAutoAddInter.Enabled := false;
      cbApplyForCurrentDir.Checked := false;
      meDescription.Lines.Clear;
      VisibleApplyCheckBoxes(false, false);

      GIDComponent := 0;
      GIDObjectIcon := 0;
      GIDSymbolImage := 0;
      ZeroMemory(@FSuppliesKind, SizeOf(TSuppliesKind));

      GGUIDObjectIcon := '';
      GGUIDSymbolImage := '';

      FMakeEdit := GetMakeEditByFormMode(GFormMode);

      {$IF Defined(NORMSCS_PE) or Defined(SCS_SPA)}
        Act_AddNorm.Visible := true;
      {$IFEND}
      case GFormMode of
        fmMake:
          begin
            //GIDComponent := 0;
            //GIDObjectIcon := 0;
            //GIDSymbolImage := 0;
            //FIDSuppliesKind := 0;

            //GGUIDObjectIcon := '';
            //GGUIDSymbolImage := '';

            //if GUseLiteFunctional then
            //  cbImportFromTemplate.Checked := true;


            ClearFormGrids;
            pcMain.ActivePage := tsCommon;

            EnableControl(true);
            if Not FIsTemplate then
              Caption := cAddComponent_Msg4_1
            else
              Caption := cAddComponent_Msg4_3;
            //Edit_Name.SetFocus;

            Edit_Name.Text := '';
            Edit_NameShort.Text := '';
            seIndex.Value := 0;
            //Edit_MarkStr.Text := '';
            Edit_Izm.Text := '';
            Edit_Notice.Text := '';
            Edit_ArticulDistributor.Text := '';
            Edit_ArticulProducer.Text := '';
            MaskEdit_Cyper.Text := TF_Main(GForm).FNormBase.DM.GenComponentNewCypher; //GenNewComponentCypher;

            //RadioGroup_CanComplect.ItemIndex := -1;
            cbCanComplect.Checked := true;
            CheckBox_HasNds.Checked := true; //RadioGroup_HasNds.ItemIndex := 0;
            cbIsMarkInCaptions.Checked := false;

            CurrencyEdit_Price1.Value := 0;
            CurrencyEdit_Price2.Value := 0;
            CurrencyEdit_NDS1.Visible := false;
            CurrencyEdit_NDS2.Visible := false;
            GID_Currency := TF_Main(GForm).GCurrencyM.ID;
            //ComboBox_ComponentType.Properties.OnChange := nil;
            //ComboBox_ComponentType.ItemIndex := 0;
            //ComboBox_ComponentType.Properties.OnChange := ComboBox_ComponentTypePropertiesChange;

            //*** Заставить показать список типов компонент
            //13.05.2009 ComboBox_ComponentType.SetFocus;
            //13.05.2009 ComboBox_ComponentType.DroppedDown := true;
            //13.05.2009 //if SendMessage(ComboBox_ComponentType.Handle, CB_GETDROPPEDSTATE, 0, 0) <> 1 then
            //13.05.2009   //SendMessage(ComboBox_ComponentType.Handle, CB_SHOWDROPDOWN, 1, 0);

            // Выбрать тип компонента
            Timer_ChoiceCompType.Enabled := true;

            SpinEdit_UserLength.Value := 0;
            //SpinEdit_ObjectIconStep.Value := 0;

            //ComboBox_Producer.ItemIndex := 0;
            //ComboBox_NetType.ItemIndex := 0;
            //SelectItemByIDinCombo(ComboBox_NetType, ntComputer);
            SetVisibleByIsLine(biFalse);

            cbComponentIsTemplate.Checked := false;

            FComponBeforeEdit.Clear;

            DefineComponCurrencies;

            if FIsTemplate then
            begin
              CurrencyEdit_Price1.Value := 1;
              DefineComponSecondPrice(CurrencyEdit_Price1.Value);
              //CurrencyEdit_Price2.Value := 0;
            end;
          end;
        fmEdit, fmView, fmDisabled:
          //with TF_Main(GForm).GSCSBase.SCSComponent  do
          begin
            if Not FIsTemplate then
              Caption := cAddComponent_Msg4_2
            else
              Caption := cAddComponent_Msg4_4;
            GIDComponent := TF_Main(GForm).GSCSBase.SCSComponent.ID;

            FComponBeforeEdit.Assign(TF_Main(GForm).GSCSBase.SCSComponent, false, false);
            SendComponentToForm(TF_Main(GForm).GSCSBase.SCSComponent, false);

            (*
            GIDObjectIcon := IDObjectIcon;
            GIDSymbolImage := IDSymbol;

            if IsLine = biTrue then
              if TF_Main(GForm).GDBMode = bkProjectManager then
              begin
                ProjManCompon := TF_Main(GForm).GSCSBase.CurrProject.GetComponentFromReferences(ID);
                if (ProjManCompon <> nil) and (ProjManCompon.IsLine = biTrue) then
                  FTraccaLength := ProjManCompon.GetPartLength;
              end;

            Caption := 'Свойства компоненты';
            if Picture <> nil then
              try
                Picture.Position := 0;
                if Picture.Size > 0 then
                begin
                  Stream := TFileStream.Create(ComponPictFileName, fmCreate);
                  Stream.Position := 0;
                  Stream.CopyFrom(TF_Main(GForm).GSCSBase.SCSComponent.Picture, 0);
                  Stream.Position := 0;
                  FreeAndNil(Stream);
                  Image.Picture.LoadFromFile(ComponPictFileName);
                  DeleteFile(ComponPictFileName);
                  //Image.Picture.Bitmap.LoadFromStream(Stream);
                  //Stream.Free;
                end;
              except
                on E: Exception do ShowMessage('Не удалось загрузить рисунок');
              end;

            if Assigned(Description) then
              if Description.Size > 0 then
              begin
                Description.Position := 0;
                meDescription.Lines.LoadFromStream(Description);
              end;

            Edit_Name.Text := Name;
            Edit_NameShort.Text := NameShort;
            Edit_NameMark.Text := NameMark;
            Edit_MarkStr.Text := MarkStr;
            GNameMark := NameMark;
            MaskEdit_Cyper.Text := Cypher;
            Edit_Izm.Text := Izm;
            Edit_Notice.Text := Notice;
            Edit_ArticulDistributor.Text := ArticulDistributor;
            Edit_ArticulProducer.Text := ArticulProducer;

            //CheckBox_IsUserMark.Checked := IntToBool(IsUserMark);
            if IsUserMark = biTrue then
              rbMarkByDefault.Checked := true
            else
              rbMarkByTemplate.Checked := true;

            //case ISComplect of
            //  0: RadioGroup_CanComplect.ItemIndex := 1;
            //  1: RadioGroup_CanComplect.ItemIndex := 0;
            //end;
            cbCanComplect.Checked := IntToBool(ISComplect);

            //case HASNDS  of
            //  0: RadioGroup_HasNds.ItemIndex := 1;
            //  1: RadioGroup_HasNds.ItemIndex := 0;
            //end;
            cePriceSupply.Properties.OnChange := nil;
            cePriceSupply.Value := PriceSupply;
            cePriceSupply.Properties.OnChange := cePriceSupplyPropertiesChange;

            CheckBox_HasNds.Checked := IntToBool(HASNDS);

            ComboBox_ComponentType.Properties.OnChange := nil;
            LoadComponentType;
            case TF_Main(GForm).GDBMode of
              bkNormBase:
                SelectItemByIDinCombo(ComboBox_ComponentType, ID_ComponentType);
              bkProjectManager:
                begin
                  AddItemToCombo(ComboBox_ComponentType, ComponentType.Name, GUIDComponentType, ID_ComponentType,
                    GUIDComponentType, ID_ComponentType, nil);
                  SelectItemByGUIDinCombo(ComboBox_ComponentType, GUIDComponentType);
                end;
            end;
            ComboBox_ComponentType.Properties.OnChange := ComboBox_ComponentTypePropertiesChange;

            cbSuppliesKind.Properties.OnChange := nil;
            SelectItemByIDinCombo(cbSuppliesKind, IDSuppliesKind);
            cbSuppliesKind.Properties.OnChange := cbSuppliesKindPropertiesChange;
            DefineParamsBySupply(false);

            SpinEdit_UserLength.Value :=  UserLength;
            SpinEdit_ObjectIconStep.Value := ObjectIconStep;

            SelectItemByIDinCombo(ComboBox_Producer, ID_Producer);
            SelectItemByIDinCombo(ComboBox_NetType, IDNetType);
            // Загрузить Тип Сети
            {ID_NetType := TObject.Create;
            for i := 0 to ComboBox_NetType.Properties.Items.Count - 1 do
              begin
                  ID_NetType := ComboBox_NetType.Properties.Items.Objects[i];
                  if (ID_NetType as TID).ID = IDNetType then
                    begin
                        ComboBox_NetType.ItemIndex := i;
                        ComboBox_NetType.Refresh;
                        Break;
                    end;
              end;}

            //With TF_Main(GForm).DM do
            //  LoadMT(GID_COMPONENT, tkComponIconsED, ComponIconsFields);

            // Загрузить интерфейсы
            with TF_Main(GForm).DM do
            begin
              LoadMT(GIDComponent, tkInterfRelED, InterfFields);
              //MemTable_InterfaceRelEd.LoadFromDataSet(MemTable_InterfaceRel, []);

              // Загрузить портов
              if IsLine = biFalse then
              begin
                //With TF_Main(GForm).DM do
                LoadMT(GIDComponent, tkPortED, PortFields);
                LoadMT(GIDComponent, tkPortInterfRelED, nil);
                DefineAllPortInterfRelNames;
              end;

              // Загрузить свойства
              //With TF_Main(GForm).DM do
              LoadMT(GIDComponent, tkPropertyRelED, PropertFields);
              //MemTable_PropertyEd.LoadFromDataSet(MemTable_Property, []);
              LoadComponIcon(GIDObjectIcon, Image_CompIcons);
              LoadComponIcon(GIDSymbolImage, Image_Symbol);

              // Загрузить комплектующие
              //With TF_Main(GForm).DM do
              LoadMT(GIDComponent,  tkComplectED, ComplectsFields);

              // Загрузить элементы кабельных каналов
              if ComponentType.SysName = ctsnCableChannel then
               //With TF_Main(GForm).DM do
                LoadMT(GIDComponent,  tkCableCanalConnectorsED, CableCanalConnectorsFields);
            end;
            LoadNormsResources;

            // Загрузить цены
            ShowNDSPrice;
            case HASNDS  of
              0:
                begin // В том числе с НДС - да
                  CurrencyEdit_Nds1.Value := Round3(Price);
                  CurrencyEdit_Nds2.Value := Round3(Price *
                                       (TF_Main(GForm).GCurrencyM.Ratio / TF_Main(GForm).GCurrencyS.Ratio));

                  CurrencyEdit_Price1.Value := Round3( PriceWithoutNDS( Price, TF_Main(GForm).GNDS));
                  CurrencyEdit_Price2.Value := Round3( PriceWithoutNDS( Price, TF_Main(GForm).GNDS) *
                                       (TF_Main(GForm).GCurrencyM.Ratio / TF_Main(GForm).GCurrencyS.Ratio));
                end;
              1:
                begin  // В том числе с НДС - Нет
                  CurrencyEdit_Price1.Value := Round3(Price);
                  CurrencyEdit_Price2.Value := Round3(Price *
                                       (TF_Main(GForm).GCurrencyM.Ratio / TF_Main(GForm).GCurrencyS.Ratio));
                end;
            end;

            if TF_Main(GForm).GDBMode = bkProjectManager then
            begin
              GLastPort := TF_Main(GForm).DM.GetComponentLastPort(ID);
              EnableControl(false);
              //Caption := 'Промотр данных комплектующей';
            end
            else
              EnableControl(true);
            SetVisibleByIsLine(ComponentType.IsLine); *)
          end;
      end;

      SetGenLastID(tkCableCanalConnectorsED);
      SetGenLastID(tkCompPropRelED);
      SetGenLastID(tkCrossConnectionED);
      SetGenLastID(tkInterfRelED);
      SetGenLastID(tkPortInterfRelED);
      SetGenLastID(tkNormEd);
      SetGenLastID(tkResourceRelEd);
      //ComboBox_ComponentTypePropertiesChange(ComboBox_ComponentType);

      GWasChanging := false;

      if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        if GIDComponent > 0 then
        begin
          SCSCompon := F_ProjMan.GSCSBase.CurrProject.CurrList.GetComponentFromReferences(GIDComponent);
          if SCSCompon <> nil  then
          begin
            Prop := SCSCompon.GetPropertyBySysName(pnNotUseUgoBounds);
            if Prop <> nil then
              if Prop.Value = '1' then
                cbNotUseUgoBounds.Checked := True;
          end;
          SCSCompon := nil;
        end;
      end;

      EnableButtons;
      SetControls(nil);
    except
      on E: Exception do
        AddExceptionToLog('TF_AddComponent.FormShow' + E.Message);
    end;
  finally
    Screen.Cursor := crDefault;
  end;
end;

// ##### Добавить рисунок #####

procedure TF_AddComponent.Button_OpenPictureClick(Sender: TObject);
//Var Stream: TStream;
    //Bmp: TBitmap;
begin
  if OpenPictureDialog1.Execute then
  begin
    Image.Picture.LoadFromFile(OpenPictureDialog1.FileName);
    {if DBImage.DataSource = nil then
      DBImage.DataSource = TF_Main(GForm).DM.DataSource; }
    GChangedPicture := True;
    GWasChanging := true;
  end;
end;

procedure TF_AddComponent.Button_ClearImageClick(Sender: TObject);
begin
  ClearcxImage(Image);
end;

// ##### Изменен "В том числе НДС" #####

procedure TF_AddComponent.CheckBox_HasNdsPropertiesChange(Sender: TObject);
begin
  ShowNDSPrice;
  DefineSupplyPriceByComponActualPrice;
  GWasChanging := true;
end;

// ##### Выбор типа Сети #####

procedure TF_AddComponent.Button_ChangeNetTypeClick(Sender: TObject);
var
  IDNetType: Integer;
  GUIDNetType: string;
  //Iindex: Integer;
begin
  IDNetType := GetIDFromComboBox(ComboBox_NetType);
  GUIDNetType := GetGUIDFromComboBox(ComboBox_NetType);
  if TF_Main(GForm).GDBMode = bkNormBase then
  begin
    F_NormBase.F_CaseForm.GIDNotDel := IDNetType;
    F_NormBase.F_CaseForm.GIDToLocate := IDNetType;

    if (F_NormBase.F_CaseForm.Execute(vkNetType, fmEdit)) then
    begin
      IDNetType := F_NormBase.DM.DataSet_NET_TYPE.FN(fnID).AsInteger;
      FillComboBox(ComboBox_NetType, F_NormBase, false, tnNetType, fnID, fnName, '', IDNetType);
      GWasChanging := true;
    end
    else
      FillComboBox(ComboBox_NetType, F_NormBase, false, tnNetType, fnID, fnName, '', IDNetType);
  end
  else if TF_Main(GForm).GDBMode = bkProjectManager then
  begin
    if ShowCurrProjectProperties(vkNetType, GUIDNetType) then
      if FProjSpravochnik.LastNetType <> nil then
        GUIDNetType := FProjSpravochnik.LastNetType.GUID;

    //ComboBox_NetType.Properties.OnChange := nil;
    //FProjSpravochnik.LoadNetTypesToStrings(ComboBox_NetType.Properties.Items, false);
    //ComboBox_NetType.Properties.OnChange := ComboBox_NetTypePropertiesChange;
    LoadNetTypesToForm;

    SelectItemByGUIDinCombo(ComboBox_NetType, GUIDNetType);
  end;
end;

// ##### Выбор производителя #####

procedure TF_AddComponent.Button_ProducerClick(Sender: TObject);
var
  ID_Producer: Integer;
  GUIDProducer: string;
begin
  try
    ID_Producer := GetIDFromComboBox(ComboBox_Producer);
    GUIDProducer := GetGUIDFromComboBox(ComboBox_Producer);

    if TF_Main(GForm).GDBMode = bkNormBase then
    begin
      //SearchRecord(F_NormBase.DM.DataSet_PRODUCERS, 'ID', ID_Producer);
      F_NormBase.F_CaseForm.GIDNotDel := ID_Producer;
      F_NormBase.F_CaseForm.GIDToLocate := ID_Producer;
      //F_NormBase.F_CaseForm.GViewKind := vkProducers;

      //if F_NormBase.F_CaseForm.ShowModal = mrOK then
      if F_NormBase.F_CaseForm.Execute(vkProducers, fmEdit) then
      begin
        ID_Producer := F_NormBase.DM.DataSet_PRODUCERS.FN(fnID).AsInteger;
        FillComboBox(ComboBox_Producer, F_NormBase, false, tnProducers, fnID, fnName, '', ID_Producer);
        GWasChanging := true;
      end
      else
        FillComboBox(ComboBox_Producer, F_NormBase, false, tnProducers, fnID, fnName, '', ID_Producer);
    end
    else if TF_Main(GForm).GDBMode = bkProjectManager then
    begin
      if ShowCurrProjectProperties(vkProducers, GUIDProducer) then
        if FProjSpravochnik.LastProducer <> nil then
          GUIDProducer := FProjSpravochnik.LastProducer.GUID;

      //FProjSpravochnik.LoadProducersToStrings(ComboBox_Producer.Properties.Items, true);
      LoadProducersToForm;

      SelectItemByGUIDinCombo(ComboBox_Producer, GUIDProducer);
    end;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.Button_ProducerClick' + E.Message);
  end;
end;

// ##### Выбор типа омпоненты #####

procedure TF_AddComponent.Button_TypeComponentClick(Sender: TObject);
var
  ID_TypeComponent: Integer;
begin
  try
    if TF_Main(GForm).GDBMode = bkNormBase then
    begin
      ID_TypeComponent := GetIDFromComboBox(ComboBox_ComponentType);
      //SearchRecord(F_NormBase.DM.DataSet_COMPONENT_TYPES, 'ID', ID_TypeComponent);
      F_NormBase.F_CaseForm.GIDNotDel := ID_TypeComponent;
      F_NormBase.F_CaseForm.GIDToLocate := ID_TypeComponent;
      //F_NormBase.F_CaseForm.GViewKind := vkComponentType;

      //if F_NormBase.F_CaseForm.ShowModal = mrOK then
      if F_NormBase.F_CaseForm.Execute(vkComponentType, fmEdit) then
      begin
        ID_TypeComponent := F_NormBase.DM.DataSet_COMPONENT_TYPES.FN(fnID).AsInteger;
        FillComboBox(ComboBox_ComponentType, F_NormBase, false, tnComponentTypes, fnID, fnName, '', ID_TypeComponent);

        if ID_TypeComponent <> 0 then
          ComboBox_ComponentTypeExit(ComboBox_ComponentType);
        GWasChanging := true;
      end
      else
        FillComboBox(ComboBox_ComponentType, F_NormBase, false, tnComponentTypes, fnID, fnName, '', ID_TypeComponent);
    end;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.Button_TypeComponentClick' + E.Message);
  end;
end;

// ##### Выбор активного условного обозначения #####

procedure TF_AddComponent.Button_OpenCompIconsClick(Sender: TObject);
begin
  LoadImageFromObjectIcons(GIDObjectIcon, GGUIDObjectIcon, Image_CompIcons);
  {DataSetLocateByID(F_NormBase.DM.DataSet_OBJECT_ICONS, GID_OBJECT_ICON);

  F_NormBase.F_CaseForm.GIDNotDel := GID_OBJECT_ICON;
  F_NormBase.F_CaseForm.GViewKind := vkObjectIcons;
  F_NormBase.F_CaseForm.GFormMode := fmEdit;

  if F_NormBase.F_CaseForm.ShowModal = mrOK then
    begin
        GID_OBJECT_ICON := F_NormBase.DM.DataSet_OBJECT_ICONS.FN('ID').AsInteger;
        LoadComponIcon(GID_OBJECT_ICON, Image_CompIcons);
        GWasChanging := true;
    end; }
end;

procedure TF_AddComponent.btOpenSymbolImageClick(Sender: TObject);
var
  ComponentType: TComponentType;
  DesignParams: TComponDesignWizardParams;
begin
  ComponentType := GetComponentType;
  if (ComponentType.SysName = ctsnCupBoard) and (Not FIsTemplate) then
  begin
    DesignParams.IDDesignIcon := GIDSymbolImage;
    DesignParams.GUIDDesignIcon := GGUIDSymbolImage;
    DesignParams.ObjectSignType := GetSignType;
    DesignParams.Height := GetPropertyBySysNameAsFloat(pnHeight);
    DesignParams.Width := GetPropertyBySysNameAsFloat(pnWidth);
    DesignParams.BottomBound := GetPropertyBySysNameAsFloat(pnBottomBound);
    DesignParams.LeftBound := GetPropertyBySysNameAsFloat(pnLeftBound);
    DesignParams.RightBound := GetPropertyBySysNameAsFloat(pnRightBound);
    DesignParams.TopBound := GetPropertyBySysNameAsFloat(pnTopBound);

    if F_ComponDesignWizard.ExecuteWizard(DesignParams, GForm, FSpravochnik) then
    begin
      GIDSymbolImage := DesignParams.IDDesignIcon;
      GGUIDSymbolImage := DesignParams.GUIDDesignIcon;

      SetPropertyValueBySysNameAsFloat(pnHeight, DesignParams.Height);
      SetPropertyValueBySysNameAsFloat(pnWidth, DesignParams.Width);
      SetPropertyValueBySysNameAsFloat(pnBottomBound, DesignParams.BottomBound);
      SetPropertyValueBySysNameAsFloat(pnLeftBound, DesignParams.LeftBound);
      SetPropertyValueBySysNameAsFloat(pnRightBound, DesignParams.RightBound);
      SetPropertyValueBySysNameAsFloat(pnTopBound, DesignParams.TopBound);

      LoadComponIcon(GIDSymbolImage, GGUIDSymbolImage, Image_Symbol);
      //LoadImageFromObjectIcons(GIDSymbolImage, Image_Symbol);
    end;
  end
  else
    LoadImageFromObjectIcons(GIDSymbolImage, GGUIDSymbolImage, Image_Symbol);
end;

procedure TF_AddComponent.Button_ClearComponIconClick(Sender: TObject);
begin
  ClearcxImage(Image_CompIcons);
  GIDObjectIcon := 0;
  GGUIDObjectIcon := '';
end;

procedure TF_AddComponent.btClearSymbolImageClick(Sender: TObject);
begin
  ClearcxImage(Image_Symbol);
  GIDSymbolImage := 0;
  GGUIDSymbolImage := '';
end;

// ##### Изминение цвета #####

procedure TF_AddComponent.ColorEditChange(Sender: TObject);
//var ID_Property: Integer;
begin
  {with TF_Main(GForm).DM.MemTable_PropertyEd do
    begin
        ID_Property := FieldByName('ID_Property').AsInteger;
        SearchRecordMT(TF_Main(GForm).DM.MemTable_PropertyEd, 'PValue', 'COLOR');
        Edit;
        FieldByName('PValue').AsString := IntToStr(ColorEdit.SelectedColor);
        Post;
        SearchRecordMT(TF_Main(GForm).DM.MemTable_PropertyEd, 'ID_Property', ID_Property);
    end; }
  GWasChanging := true;
end;

// ############################# Кнопки OK Отмена ##############################
// #############################################################################
//
// ##### Нажат OK #####

procedure TF_AddComponent.BitBtn_OKClick(Sender: TObject);
var
  i: Integer;
  //RecCount: Integer;
  CanSave: Boolean;
  MessgError: string;
  Price: Double;
  //PriceCalc: Double;
  //OldPrice: Double;
  //ObjectID: Integer;

  CypherCount: Integer;
  IDComponTemplate: Integer;

  Stream: TStream;
  AllComponents: TSCSComponents;
  ComponentsForApply: TSCSComponents;
  ComponentType: TComponentType;
  ListIDs: TIntList;
  ListIDsWithWholeCompon: TIntList;

  SCSCompon: TSCSComponent;
  PartCompon: TSCSComponent;

  ProjComponent: TSCSComponent;
  WasChangeCompTypeTemplate: Boolean;
  NewIDCompTypeTemplate: Integer;
  OldIDCompTypeTemplate: Integer;
  NBComponentType: TNBComponentType;
  NodeComponTemplate: TTreeNode;
  CanApplyCompon: Boolean;

  Prop: PProperty;
  NBProp: TNBProperty;

  //hFile: Cardinal;

{Procedure SavePicture(Blob: TFIBBlobField);
Var Stream: TStream;
begin
   if GChangedPicture then
     begin
         Stream := TMemoryStream.Create;
         Image.Picture.Bitmap.SaveToStream(Stream);
         Blob.LoadFromStream(Stream);
         Stream.Free;
     end;
end; }

  procedure SaveInterfaces(AIDComponent: Integer; AUpdateMT: Boolean);
  begin
    with TF_Main(GForm).DM do
      SaveMTToDS(AIDComponent, GDeletedInterfRel, tkInterfRelED, AUpdateMT);
  end;

  procedure SavePorts(AIDComponent: Integer; AUpdateMT: Boolean);
  begin
    with TF_Main(GForm).DM do
      SaveMTToDS(AIDComponent, GDeletedPort, tkPortEd, AUpdateMT);
  end;

  procedure SaveComponData(AIDComponent: Integer);
  var
    ComponentType: TComponentType;
    Compon: TSCSComponent;
    Interfaces: TSCSInterfaces;
    Properties: TList;
    NewProperties: TList;
    PropOldIDs: TIntList;
    PropNewIDs: TIntList;
    CableCanalConnectors: TList;
    CrossConnections: TSCSObjectList;
    QueryMode: TQueryMode;
    i, j, k: Integer;

    Interf: TSCSInterface;
    OldInterf: TSCSInterface;
    ptrPortInterfRel: PPortInterfRel;
    ptrProperty: PProperty;
    ptrOldProperty: PProperty;
    ptrCableCanalConnector: PCableCanalConnector;
    ptrOldCableCanalConnector: PCableCanalConnector;
  begin
    try
      QueryMode := GetQueryModeByGDBMode(TF_Main(GForm).GDBMode);
      ComponentType := GetComponentType;

      if QueryMode = qmPhisical then
        with TF_Main(GForm).DM do
        begin
          DeleteRecordsByIDList(tnPortInterfaceRelation, GDeletedPortInterfRels, QueryMode);
          DeleteRecordsByIDList(tnInterfaceRelation, GDeletedInterfRel, QueryMode);
          DeleteRecordsByIDList(tnCompPropRelation, GDeletedPropRel, QueryMode);
          DeleteRecordsByIDList(tnCableCanalConnectors, GDeletedCableCanalConnectors, QueryMode);
          DeleteRecordsByIDList(tnCrossConnection, GDeletedCrossConnections, QueryMode);
        end;

      Interfaces := CreateFormInterfaces;
      Properties := CreateFormProperties;
      CableCanalConnectors := CreateFormCableCanalConnectors;
      CrossConnections := CreateFormCrossConnections;

      Compon := nil;
      if Assigned(ProjComponent) then
      begin
        Compon := ProjComponent;

        //*** порты и интерфейсы

        //*** Удаить связи портов с интерфейсами
        for i := 0 to GDeletedPortInterfRels.Count - 1 do
          for j := 0 to Compon.Interfaces.Count - 1 do
          begin
            Interf := Compon.Interfaces[j];
            for k := 0 to Interf.PortInterfRels.Count - 1 do
            begin
              ptrPortInterfRel := Interf.PortInterfRels[k];
              if ptrPortInterfRel.ID = GDeletedPortInterfRels[i] then
              begin
                Interf.PortInterfRels[k] := nil;
                Interf.PortInterfaces.Remove(ptrPortInterfRel.Interf);
                FreeMem(ptrPortInterfRel);
              end;
            end;
            Interf.PortInterfRels.Pack;
          end;

        //*** Удалить удаленные интерфейсы
        for i := 0 to GDeletedInterfRel.Count - 1 do
        begin
          Interf := Compon.GetInterfaceByID(GDeletedInterfRel[i]);
          if Assigned(Interf) then
          begin
            Compon.Interfaces.Remove(Interf);
            FreeAndNil(Interf);
          end;
        end;

        //*** обновить интерфейсы в объекте
        for i := 0 to Interfaces.Count - 1 do
        begin
          Interf := Interfaces[i];
          if Interf.IsNew or Interf.IsModified then
          begin
            if Interf.IsNew then
            begin
              Compon.Interfaces.Add(Interf);
              Interfaces[i] := nil;
            end
            else if Interf.IsModified and not (Interf.IsNew) then
            begin
              OldInterf := Compon.GetInterfaceByID(Interf.ID);
              if Assigned(OldInterf) then
              begin
                OldInterf.AssignOnlyInterface(Interf);
                //if OldInterf.IsPort = biTrue then  ##ISPORT
                begin
                  OldInterf.PortInterfaces.Clear;
                  ClearList(OldInterf.PortInterfRels);
                  OldInterf.AssignPortInterfRel(Interf.PortInterfRels);
                end;
              end;
            end;
          end;
        end;
        Interfaces.Pack;

        //*** Обновить связи портов с интерфейсами
        Compon.SetPortInterfRelInterfaces;
        //for i := 0 to Compon.Interfaces.Count - 1 do
        //begin
        //  Interf := Compon.Interfaces[i];
        //  if Interf.IsPort = biTrue then
        //    Interf.DefinePortInterfaces;
        //end;

        //*** Свойства

        //*** Удалить свойства
        for i := 0 to GDeletedPropRel.Count - 1 do
        begin
          ptrProperty := Compon.GetPropertyByID(GDeletedPropRel[i]);
          if ptrProperty <> nil then
          begin
            Compon.Properties.Remove(ptrProperty);
            FreeMem(ptrProperty);
          end;
        end;
        //*** Обновить свойства
        for i := 0 to Properties.Count - 1 do
        begin
          ptrProperty := Properties[i];
          if ptrProperty.IsNew then
          begin
            Compon.Properties.Add(ptrProperty);
            if Compon.IsLine = biTrue then
              MakeEditPropertyForWholeComponent(meMake, Compon, ptrProperty);
            Properties[i] := nil;
          end
          else if ptrProperty.IsModified then
          begin
            ptrOldProperty := Compon.GetPropertyByID(ptrProperty.ID);
            if ptrOldProperty <> nil then
              ptrOldProperty^ := ptrProperty^;

            if Compon.IsLine = biTrue then
              MakeEditPropertyForWholeComponent(meEdit, Compon, ptrProperty);
          end;
        end;
        Properties.Pack;

        //*** элесменты каб-каналов
        if ComponentType.SysName = ctsnCableChannel then
        begin
          //*** Удалить удаленные
          for i := 0 to GDeletedCableCanalConnectors.Count - 1 do
          begin
            ptrCableCanalConnector := Compon.GetCableCanalConnectorByID(GDeletedCableCanalConnectors[i]);
            if ptrCableCanalConnector <> nil then
            begin
              Compon.CableCanalConnectors.Remove(ptrCableCanalConnector);
              FreeMem(ptrCableCanalConnector);
            end;
          end;

          //*** Обновить записи
          for i := 0 to CableCanalConnectors.Count - 1 do
          begin
            ptrCableCanalConnector := CableCanalConnectors[i];
            if ptrCableCanalConnector.IsNew then
            begin
              Compon.CableCanalConnectors.Add(ptrCableCanalConnector);
              CableCanalConnectors[i] := nil;
            end
            else if ptrCableCanalConnector.IsModified then
            begin
              ptrOldCableCanalConnector := Compon.GetCableCanalConnectorByID(ptrCableCanalConnector.ID);
              if ptrOldCableCanalConnector <> nil then
                ptrOldCableCanalConnector^ := ptrCableCanalConnector^;
            end;
          end;
          CableCanalConnectors.Pack;
        end;
      end
      else
      begin
        Compon := TSCSComponent.Create(GForm);
        Compon.ID := AIDComponent;
        Compon.AssignOnlyComponent(TF_Main(GForm).GSCSBase.SCSComponent);
        Compon.Interfaces.Assign(Interfaces);
        Compon.AssignProperties(Properties);
        if ComponentType.SysName = ctsnCableChannel then
          Compon.AssignCableCanalConnectors(CableCanalConnectors);
        if ComponentType.SysName = ctsnCupBoard then
          Compon.AssignCrossConnections(CrossConnections);
      end;
      Interfaces.Free;
      FreeAndDisposeList(Properties); //16.10.2007 FreeList(Properties);
      FreeList(CableCanalConnectors);
      FreeAndNil(CrossConnections); //FreeList(CrossConnections);

      // Запоминаем новые свойства и их ID
      NewProperties := TList.Create;
      PropOldIDs := TIntList.Create;
      PropNewIDs := TIntList.Create;
      for i := 0 to Compon.Properties.Count - 1 do
      begin
        ptrProperty := Compon.Properties[i];
        if ptrProperty.IsNew then
        begin
          NewProperties.Add(ptrProperty);
          PropOldIDs.Add(ptrProperty.ID);
        end;
      end;

      Compon.SaveInterfacesByServFields;
      Compon.SavePropertiesByServFields(Compon.ID);
      if ComponentType.SysName = ctsnCableChannel then
        Compon.SaveCableCanalConnectorsByServFields;
      if ComponentType.SysName = ctsnCupBoard then
        Compon.SaveCrossConnectionsByServFields;


      // Запоминаем новые ID свойств
      for i := 0 to NewProperties.Count - 1 do
        PropNewIDs.Add(PProperty(NewProperties[i]).ID);

      SetNewCompPropIDsToNormRes(PropOldIDs, PropNewIDs);

      FreeAndNil(NewProperties);
      FreeAndNil(PropOldIDs);
      FreeAndNil(PropNewIDs);
      if not Assigned(ProjComponent) then
        Compon.Free;
    except
      on E: Exception do AddExceptionToLogEx('TF_AddComponent.SaveComponData', E.Message);
    end;
  end;

  procedure SaveProperties(AIDComponent: Integer; AUpdateMT: Boolean);
    //var
      //Compon: TSCSComponent;
      //Properties: TList;
  begin
    with TF_Main(GForm).DM do
      SaveMTToDS(AIDComponent, GDeletedPropRel, tkCompPropRelED, AUpdateMT);

    {Properties := CreateFormProperties;
    Compon := nil;
    if Assigned(ProjComponent) then
    begin
      Compon := ProjComponent;
    end
    else

      Compon := TSCSComponent.Create(GForm);

    if Assigned(Compon) then
    begin

      if Not Assigned(ProjComponent) then
        Compon.Free;
    end;
    FreeList(Properties);}
  end;

  procedure SaveCableCanalConnectors(AIDComponent: Integer; AUpdateMT: Boolean);
  begin
    with TF_Main(GForm).DM do
      SaveMTToDS(AIDComponent, GDeletedCableCanalConnectors, tkCableCanalConnectorsED, AUpdateMT);
  end;

  {procedure SaveComponIcons(AIDComponent: Integer; AUpdateMT: Boolean);
  begin
      with TF_Main(GForm).DM do
        SaveMTToDS(AIDComponent, GDeletedComponIcons, tkComponIconsED, AUpdateMT);
  end;}

  procedure SaveComplects;
    //var RecNoComp: Integer;
  begin

  end;

  procedure AddErrorMessg(AErrorMessg: string);
  begin
    MessgError := MessgError + AErrorMessg;
    CanSave := false;
  end;

  // Tolik
   Procedure AddNewPropToCompon(aCompon: TSCSComponent; aProp: TNBProperty; aValue: Double);
   var Prop: PProperty;
       i: Integer;
       val: String;
       NBProp: TNBProperty;
   begin
     if aProp <> nil then
     begin
       Prop := aCompon.GetPropertyBySysName(aProp.PropertyData.SysName);
       if Prop = nil then
       begin
          if ACompon.GetPropertyBySysName(aProp.PropertyData.SysName) = nil then
         begin
           // Подтягиваем в справочник проекта из НБ
           Val := FloatTostr(aValue);
           NBProp := F_NormBase.GSCSBase.NBSpravochnik.GetPropertyBySysName(aProp.PropertyData.SysName);
           if NBProp <> nil then
            begin
             ACompon.ProjectOwner.Spravochnik.GetPropertyWithAssign(NBProp.PropertyData.GUID, F_NormBase.GSCSBase.NBSpravochnik);
           end;
           AddPropertyToComponFromSprBySysName(ACompon, ACompon.ProjectOwner.Spravochnik, aProp.PropertyData.SysName, Val);
         end;
       end;
     end;
   end;
 //

begin
  try
    SCSCompon := nil;
    AllComponents := nil;
    ComponentsForApply := nil;
    Stream := nil;
    if GFormMode = fmView then
    begin
      ModalResult := mrCancel;
      Exit; ///// EXIT /////
    end;
    // Tolik 03/07/2017 -- сброс для CashedCompon (чтобы не пришли значения с предидущего проекта)
    if Assigned(F_ProjMan) then
      if TF_Main(F_ProjMan).CashedCompon <> nil then
        TF_Main(F_ProjMan).CashedCompon.Clear;
    if Assigned(F_NormBase) then
      if TF_Main(F_NormBase).CashedCompon <> nil then
        TF_Main(F_NormBase).CashedCompon.Clear;
    //

    // Tolik 05/03/2021 -- обработчик чекбокса(не использовать УГО для границ объекта )
    if TF_Main(GForm).GDBMode = bkProjectManager then
      //SCSCompon := TF_Main(F_ProjMan).GSCSBase.SCSComponent
      SCSCompon := TF_Main(GForm).GSCSBase.CurrProject.GetComponentFromReferences(GIDComponent)
    else
      SCSCompon := TF_Main(F_NormBase).GSCSBase.SCSComponent;

    if SCSCompon <> nil then
    begin
      //SCSCompon.LoadProperties;
      Prop := SCSCompon.GetPropertyBySysName(pnNotUseUgoBounds);
      if cbNotUseUgoBounds.Checked then
      begin
        if Prop = nil then
        begin
          NBProp := TF_Main(F_NormBase).GSCSBase.NBSpravochnik.GetPropertyBySysName(pnNotUseUgoBounds);

          if NBProp <> nil then
          begin
           { Prop := SCSCompon.GetPropertyAsNew;
            Prop.IsDefault := 0;
            Prop.TakeIntoConnect := 0;
            prop.TakeIntoJoin := 0;
            prop.IsTakeJoinforPoint := 0;
            prop.IsCrossControl := 0;
            prop.IsForWholeComponent := 1;
            Prop.Guid := NBProp.PropertyData.GUID;
            Prop.IDDataType := NbProp.PropertyData.IDDataType;
            Prop.Name_ := NBProp.PropertyData.Name;
            Prop.SysName := NBProp.PropertyData.SysName;
            Prop.IDMaster := SCSCompon.ID;
            //Prop.IsModified := True;
            //Prop.IsNew := True;
            Prop.Value := BoolToStr(cbNotUseUgoBounds.Checked, false);
            //SCSCompon.SaveProperty(meMake, Prop);
            //SCSCompon.SaveProperty(meMake, Prop);
            SCSCompon.SaveProperty(meEdit, Prop);
            AddPropertyToComponFromSprBySysName
            }

            if TF_Main(GForm).GDBMode = bkProjectManager then
              AddNewPropToCompon(SCSCompon, NBProp, 1)
            else
              //AddPropertyToComponFromSprBySysName(SCSCompon, TF_Main(F_NormBase).GSCSBase.NBSpravochnik, NBProp.PropertyData.SysName, '1');
             AddPropertyToNBCompon(NBProp, '1');
          end;
        end
        else
        begin
          Prop.Value := '1';
          SCSCompon.SaveProperty(meEdit, Prop);
        end;
      end
      else
      begin
      if Prop <> nil then
        Prop.Value := '0';//BoolToStr(cbNotUseUgoBounds.Checked);
        SCSCompon.SaveProperty(meEdit, Prop);
      end;
    end;

    SCSCompon := nil;
    //

    //if GFormMode = fmDisabled then
    //  Exit;
    //if cePriceSupply.Focused then
    //begin
    //  cePriceSupply.Hide;
    //  DefineParamsBySupply(false);
    //end;

    ProjComponent := nil;
    if TF_Main(GForm).GDBMode = bkProjectmanager then
      ProjComponent := TF_Main(GForm).GSCSBase.CurrProject.GetComponentFromReferences(GIDComponent);

    {if CurrencyEdit_Price1.IsFocused then
      CurrencyEdit_Price1.ValidateEdit(false);
    if CurrencyEdit_Price2.IsFocused then
      CurrencyEdit_Price2.ValidateEdit(false);}

    ValidateActiveFormControl(Self);

    CypherCount := 0;

    CanSave := true;

    MessgError := cNoDefinedParameters + ':' + #13 + #13;
    if Edit_Name.Text = '' then
      AddErrorMessg('- ' + cNamingComponent + ';' + #13);

    //if GFormMode = fmMake then
    if TF_Main(GForm).GDBMode = bkNormBase then
    begin
      if MaskEdit_Cyper.Text <> FComponBeforeEdit.Cypher then
        if not F_NormBase.DM.CheckNBComponentCypher(MaskEdit_Cyper.Text, GIDComponent) then
          AddErrorMessg('- ' + cCypher + ' "' + MaskEdit_Cyper.Text + '" ' + cNowExists + ';' + #13);
    end;

    //if RadioGroup_IsLine.ItemIndex = -1 then
    //  AddErrorMessg('- Тип компоненты;' + #13);
    {if Edit_ArticulDistributor.Text = '' then
      AddErrorMessg('- Артикульный номер дистрибьютора;' + #13);
    if Edit_ArticulDistributor.Text = '' then
      AddErrorMessg('- Артикульный номер производителя;' + #13);}
    if ComboBox_ComponentType.Text = '' then
      AddErrorMessg('- ' + cComponentType + ';' + #13);
    // Tolik 08/06/2021 --
    if GetIDFromComboBox(ComboBox_NetType) = 0 then
      AddErrorMessg('- ' + cNetType + ';' + #13);
    //
    //if ComboBox_NetType.Text = '' then
    //  AddErrorMessg('- ' + cNetType + ';' + #13);
    //if ComboBox_Producer.Text = '' then
    //  AddErrorMessg('- Производитель;' + #13);
    //if RadioGroup_HasNds.ItemIndex = -1 then
    //  AddErrorMessg('- Не известно как будет считаться цена - с НДС, или без НДС;' + #13);

    //if RadioGroup_CanComplect.ItemIndex = -1 then
    //  AddErrorMessg('- Не определено "Может ли компонент быть комплектующей";' + #13);

    //if (RadioGroup_CanComplect.ItemIndex = 0) and

//    if cbCanComplect.Visible and cbCanComplect.Checked and
//      (TF_Main(GForm).DM.MemTable_InterfaceRelEd.RecordCount = 0) and
//      (TF_Main(GForm).DM.MemTable_PortEd.RecordCount = 0) then
//      AddErrorMessg('- ' + cbMessage6);

    // Проверяем не пусты ли обязательные свойства, по которым насыпаются интерфейсы
    if TF_Main(GForm).GDBMode = bkNormBase then
      if GUseLiteFunctional then
      begin
        if Not CheckRequiredProperties then
        begin
          ModalResult := mrNone;
          Exit; ///// EXIT /////
        end;
      end
      else
      if (GFormMode = fmMake) and Not DelRequiredEmptyProps then
      begin
        ModalResult := mrNone;
        Exit; ///// EXIT /////
      end;

    if CanSave then
    begin
      ModalResult := mrOk;
      if TF_Main(GForm).GDBMode = bkProjectmanager then
      begin
        //*** Определить изменяемые компоненты
        ComponentsForApply := TSCSComponents.Create(false);

        if CheckBox_ApplyForProject.Checked then
          AllComponents := TF_Main(GForm).GSCSBase.CurrProject.ComponentReferences
        else if CheckBox_ApplyForList.Checked and CheckBox_ApplyForList.Enabled then
          if Assigned(TF_Main(GForm).GSCSBase.CurrProject.CurrList) then
            AllComponents := TF_Main(GForm).GSCSBase.CurrProject.CurrList.ComponentReferences;
        if Assigned(AllComponents) and (ProjComponent <> nil) then
          for i := 0 to AllComponents.Count - 1 do
          begin
            SCSCompon := AllComponents[i];
            if (SCSCompon.ID <> ProjComponent.ID) and (SCSCompon.GuidNB = ProjComponent.GuidNB) then
            begin
              CanApplyCompon := true;
              if cbApplyForOnlySelected.Checked then
                CanApplyCompon := IsSelectedComponFigure(SCSCompon);
              if CanApplyCompon then
                ComponentsForApply.Add(SCSCompon);
            end;
          end;
        //*** Определить список листов, на которых будут применятся изменения на компонентах
        ListIDs := GetVariousListsIDsByCompons(ComponentsForApply);
        if ProjComponent <> nil then
          if ProjComponent.IsLine = biTrue then
          begin
            ListIDsWithWholeCompon := GetVariousListsIDsByWholeID(ProjComponent.ProjectOwner, ProjComponent.Whole_ID, ListIDs);
            ListIDs.Assign(ListIDsWithWholeCompon, laOr);
            FreeAndNil(ListIDsWithWholeCompon);
          end;
        if ListIDs.IndexOf(ProjComponent.ListID) = -1 then
          ListIDs.Insert(0, ProjComponent.ListID);

        SaveListsToUndoStack(ListIDs); 
        FreeAndNil(ListIDs);
      end;
    end
    else
    begin
      MessageModal(MessgError, Caption, MB_OK or MB_ICONINFORMATION);
      ModalResult := mrNone;
      Exit; ///// EXIT /////
    end;
    MessgError := '';

    if TF_Main(GForm).DM.MemTable_PortEd.RecordCount > 0 then
      if Edit_NameShort.Text = '' then
        if MessageModal('- ' + cbMessage1, ApplicationName, MB_ICONQUESTION or MB_YESNO) <> IDYES then
        begin
          Edit_NameShort.Show;
          Edit_NameShort.SetFocus;

          ModalResult := mrNone;
          Exit; ///// EXIT /////
        end;

    Inc(GBaseBeginUpdateCount);
    Screen.Cursor := crHourGlass;
    BeginProgress;
    try
      //if ProjComponent <> nil then
      //begin
      //  ProjComponent.GUIDComponentType := GetGUIDFromComboBox(ComboBox_ComponentType);
      //  ProjComponent.LoadComponentType;
      //  ComponentType := ProjComponent.ComponentType;
      //end
      //else
      //  ComponentType := TF_Main(GForm).FNormBase.DM.GetComponentType(GetIDFromComboBox(ComboBox_ComponentType));

      ComponentType := GetComponentType;
      with TF_Main(GForm).GSCSBase do
      begin
        //SCSComponent.ClearElements;
        if GFormMode = fmMake then
          SCSComponent.Clear;
        if GFormMode = fmEdit then
          SCSComponent.ID := GIDComponent;
        SCSComponent.Name := Edit_Name.Text;
        SCSComponent.NameShort := Edit_NameShort.Text;
        SCSComponent.MarkID := Trunc(seIndex.Value);
        SCSComponent.MarkStr := '';//Edit_MarkStr.Text;
        SCSComponent.Cypher := MaskEdit_Cyper.Text;
        SCSComponent.Izm := Edit_Izm.Text;
        SCSComponent.Notice := Edit_Notice.Text;
        SCSComponent.ArticulDistributor := Edit_ArticulDistributor.Text;
        SCSComponent.ArticulProducer := Edit_ArticulProducer.Text;
        //28.08.2013 if ComponentType.IsLine = biFalse then
        //28.08.2013   SCSComponent.IsMarkInCaptions := BoolToint(cbIsMarkInCaptions.Checked)
        //28.08.2013 else
        //28.08.2013   SCSComponent.IsMarkInCaptions := biFalse;
        SCSComponent.IsMarkInCaptions := BoolToint(cbIsMarkInCaptions.Checked); //28.08.2013

        if SCSComponent.Description = nil then
          SCSComponent.Description := TMemoryStream.Create;
        SCSComponent.Description.Clear;
        SCSComponent.Description.Position := 0;
        meDescription.Lines.SaveToStream(SCSComponent.Description);

        if SCSComponent.Picture = nil then
          SCSComponent.Picture := TMemoryStream.Create;
        SCSComponent.Picture.Clear;
        SCSComponent.Picture.Position;

        {SCSComponent.Picture := TMemoryStream.Create;
        SCSComponent.Picture.Position := 0;
        Image.Picture.Bitmap.SaveToStream(SCSComponent.Picture);
        SCSComponent.Picture.Position := 0;
        ShowMessage(IntTOStr(SCSComponent.Picture.Size));}
        //hFile := CreateFile(PChar(ComponPictFileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);
        //CloseHandle(hFile);

        try
          Image.Picture.SaveToFile(ComponPictFileName);
          if FileExists(ComponPictFileName) then
          begin
            Stream := TFileStream.Create(ComponPictFileName, fmOpenReadWrite);
            Stream.Position := 0;
            SCSComponent.Picture.Position := 0;
            SCSComponent.Picture.CopyFrom(Stream, 0);
            SCSComponent.Picture.Position := 0;
            FreeAndNil(Stream);
            DeleteFile(PChar(ComponPictFileName));
          end;
        except
          on E: Exception do
            ShowMessage(cAddComponent_Msg5);
        end;

        SCSComponent.ComponentType := ComponentType;
        SCSComponent.IsLine := GetIsLineByComponType(ComponentType);
        SCSComponent.ISComplect := BoolToInt(cbCanComplect.Checked); //1 - RadioGroup_CanComplect.ItemIndex;
        SCSComponent.UserLength := FloatInUOM(SpinEdit_UserLength.Value, TF_Main(GForm).FUOM, umMetr);
        SCSComponent.ObjectIconStep := 0;//SpinEdit_ObjectIconStep.Value;
        SCSComponent.HASNDS := BoolToInt(CheckBox_HasNds.Checked); //1- RadioGroup_HasNds.ItemIndex;
        Price := 0;
        //case RadioGroup_HasNds.ItemIndex of
        //  0: Price  := CurrencyEdit_Price1.Value;
        //  1: Price := PriceWithNDS(CurrencyEdit_Price1.Value, GNDS);
        //end;
        //CurrencyEdit_Price1.
        case CheckBox_HasNds.Checked of
          true: Price := CurrencyEdit_Price1.Value;
          false: Price := PriceWithNDS(CurrencyEdit_Price1.Value, TF_Main(GForm).GNDS);
        end;
        if CheckPriceTransformToUOMByCompType(@FCurrComponentType) then
          Price := FloatInUOM(Price, umMetr, TF_Main(GForm).FUOM);
        case GFormMode of
          fmMake:
            SCSComponent.PRICE_CALC := Price;
          fmEdit:
            SCSComponent.PRICE_CALC := SCSComponent.PRICE_CALC - SCSComponent.PRICE + Price;
        end;
        SCSComponent.Price := Price;
        SCSComponent.PriceSupply := cePriceSupply.Value;
        SCSComponent.ID_CURRENCY := GID_CURRENCY;
        SCSComponent.ID_Producer := GetIDFromComboBox(ComboBox_Producer);
        SCSComponent.ID_ComponentType := GetIDFromComboBox(ComboBox_ComponentType);
        SCSComponent.IDObjectIcon := GIDObjectIcon;
        SCSComponent.IDSymbol := GIDSymbolImage;
        SCSComponent.IDNetType := GetIDFromComboBox(ComboBox_NetType);
        SCSComponent.IDCompSpecification := GetIDFromComboBox(cbSpecification);
        SCSComponent.IDSuppliesKind := GetIDFromComboBox(cbSuppliesKind);
        if SCSComponent.IDSuppliesKind < 0 then
          SCSComponent.IDSuppliesKind := 0;

        SCSComponent.GUIDProducer := GetGUIDFromComboBox(ComboBox_Producer);
        SCSComponent.GUIDNetType := GetGUIDFromComboBox(ComboBox_NetType);
        SCSComponent.GUIDComponentType := ComponentType.GUID;
        SCSComponent.GUIDObjectIcon := GGUIDObjectIcon;
        SCSComponent.GUIDSymbol := GGUIDSymbolImage;
        SCSComponent.GUIDSuppliesKind := GetGUIDFromComboBox(cbSuppliesKind);
        if TF_Main(GForm).GDBMode = bkProjectManager then
        begin
          SCSComponent.NameMark := Edit_NameMark.Text;
          //SCSComponent.IsUserMark := CheckBox_IsUserMark.Checked);
          SCSComponent.IsUserMark := BoolToInt(rbMarkByDefault.Checked);
          SCSComponent.IsDismount := BoolToInt(cbDismount.Checked);
          SCSComponent.IsUseDismounted := BoolToInt(cbUseDismounted.Checked);
        end;

        if GFormMode = fmMake then
        begin
          SCSComponent.KolComplect := 0;
          SCSComponent.GuidNB := CreateGUID;
          SCSComponent.IsTemplate := BoolToInt(FIsTemplate);
          GIDComponent := SCSComponent.SaveComponentAsNew(false, false);
          SCSComponent.ID := GIDComponent;
          if Not FIsTemplate then
            TF_Main(GForm).AppendToCatalRel(TF_Main(GForm).GSCSBase.SCSCatalog.ID, GIDComponent)
          else
            TF_Main(GForm).DM.AppendToTemplateRel(GIDComponent, TF_Main(GForm).FTemplateGrp.FID, biFalse);
          //SaveComponIcons(GID_COMPONENT, true);
        end
        else
        begin
          SCSComponent.SaveComponent;

          if (TF_Main(GForm).GDBMode = bkProjectManager) and (SCSComponent.IsLine = biTrue) then
          begin
            SCSComponent.LoadWholeComponent(false);
            for i := 0 to SCSComponent.WholeComponent.Count - 1 do
              if SCSComponent.WholeComponent[i] <> GIDComponent then
              begin
                PartCompon := TF_Main(GForm).GSCSBase.CurrProject.GetComponentFromReferences(SCSComponent.WholeComponent[i]);
                if Assigned(PartCompon) then
                begin
                  PartCompon.AssignOnlyComponentCommonData(SCSComponent, true);
                  PartCompon.SaveComponent;

                  TF_Main(GForm).OnUpdateComponent(FMakeEdit, nil, PartCompon, GChangedIndex, GChangedNameShort);
                end;
              end;
          end;
        end;
        SaveComponData(GIDComponent);
        SaveNormsResources;

        //*** Шаблок для типа компоненты
        if Not FIsTemplate then
          if TF_Main(GForm).GDBMode = bkNormBase then
          begin
            NewIDCompTypeTemplate := 0;
            //OldIDCompTypeTemplate := ComponentType.IDComponTemplate;
            WasChangeCompTypeTemplate := false;
            if cbComponentIsTemplate.Checked and cbComponentIsTemplate.Enabled and cbComponentIsTemplate.Visible then
            begin
              if ComponentType.IDComponTemplate <> GIDComponent then
              begin
                WasChangeCompTypeTemplate := true;
                NewIDCompTypeTemplate := GIDComponent;
                NodeComponTemplate := TF_Main(GForm).FindTreeNodeByDat(ComponentType.IDComponTemplate, [itComponLine, itComponCon]);

                TF_Main(GForm).DM.RemoveIDComponTemplateFromComponTypes(GIDComponent);
                TF_Main(GForm).DM.UpdateIntTableFieldByID(tnComponentTypes, fnIDComponTemplate, ComponentType.ID, GIDComponent, qmPhisical);

                // Установить новый шаблон
                NBComponentType := NBSpravochnik.GetComponentTypeByGUID(ComponentType.GUID);
                if NBComponentType <> nil then
                  NBComponentType.ComponentType.IDComponTemplate := GIDComponent;

                //*** Обновить иконку шаблона до редактирования, если его ветвь загружена
                if NodeComponTemplate <> nil then
                  TF_Main(GForm).SetNodeState(NodeComponTemplate, -1, TF_Main(GForm).GEditKind);

                // Сбросить старый шаблон
                //if FComponBeforeEdit.ComponentType.GUID <> ComponentType.GUID then
                //begin
                //  NBComponentType := NBSpravochnik.GetComponentTypeByGUID(FComponBeforeEdit.ComponentType.GUID);
                //  if NBComponentType <> nil then
                //    if NBComponentType.ComponentType.IDComponTemplate = GIDComponent then
                //      NBComponentType.ComponentType.IDComponTemplate := 0;
                //end;
              end;
            end
            else
            begin
              //*** Сбросить шаблон
              IDComponTemplate := 0;
              if (ComponentType.IDComponTemplate > 0) and (ComponentType.IDComponTemplate = GIDComponent) then
                IDComponTemplate := ComponentType.ID
              else
              if (FComponBeforeEdit.ComponentType.IDComponTemplate > 0) and
                 (FComponBeforeEdit.ComponentType.IDComponTemplate = GIDComponent) then
                IDComponTemplate := FComponBeforeEdit.ComponentType.ID;
              if IDComponTemplate > 0 then
              begin
                WasChangeCompTypeTemplate := true;
                NewIDCompTypeTemplate := 0;
                TF_Main(GForm).DM.UpdateTableField(tnComponentTypes, fnIDComponTemplate, fnID, IDComponTemplate, null, qmPhisical);

                NBComponentType := NBSpravochnik.GetComponentTypeObjByID(IDComponTemplate);
                if NBComponentType <> nil then
                  NBComponentType.ComponentType.IDComponTemplate := 0;
              end;
            end;
            if WasChangeCompTypeTemplate then
            begin
              SCSComponent.ComponentType.IDComponTemplate := NewIDCompTypeTemplate;
              //NBComponentType := NBSpravochnik.GetComponentTypeByGUID(ComponentType.GUID);
              //if NBComponentType <> nil then
              //  if (NBComponentType.ComponentType.IDComponTemplate = 0) or
              //     (NBComponentType.ComponentType.IDComponTemplate = GIDComponent) then
              //    NBComponentType.ComponentType.IDComponTemplate := NewIDCompTypeTemplate;
              //if (SCSComponent.ComponentType.IDComponTemplate = 0) or
              //   (SCSComponent.ComponentType.IDComponTemplate = GIDComponent) then
              //  SCSComponent.ComponentType.IDComponTemplate := NewIDCompTypeTemplate;

              //if FComponBeforeEdit.ComponentType.GUID <> ComponentType.GUID then
              //begin
              //  NBComponentType := NBSpravochnik.GetComponentTypeByGUID(FComponBeforeEdit.ComponentType.GUID);
              //  if NBComponentType <> nil then
              //    if NBComponentType.ComponentType.IDComponTemplate = GIDComponent then
              //      NBComponentType.ComponentType.IDComponTemplate := 0;
              //end;

              //*** Обновить иконку шаблона до редактирования, если его ветвь загружена
              //NodeComponTemplate := TF_Main(GForm).FindTreeNodeByDat(FComponBeforeEdit.ComponentType.ID, [itComponLine, itComponCon]);
              //if NodeComponTemplate <> nil then
              //  TF_Main(GForm).SetNodeState(NodeComponTemplate, -1, TF_Main(GForm).GEditKind);
            end;
          end;

        if GFormMode = fmEdit then
        begin
          //SCSComponent.LoadOwnerCatalog(false);
          //TF_Main(GForm).F_ChoiceConnectSide.DefineObjectIcon(TSCSCatalog(SCSComponent.OwnerCatalog));
          //RefreshAllLists;

          if Not FIsTemplate then
          begin
            if TF_Main(GForm).GDBMode = bkProjectManager then
            begin
              SCSCompon := TF_Main(GForm).GSCSBase.CurrProject.GetComponentFromReferences(SCSComponent.ID);
              if Assigned(SCSCompon) then
              begin
                SCSCompon.AssignOnlyComponent(SCSComponent);
                //SCSCompon.LoadInterfaces;
                //SCSCompon.LoadProperties;
                //SCSCompon.NormsResources.LoadResources(true);
                //if SCSCompon.ID_ComponentType = ctCableCanal then
                //  SCSCompon.LoadCableCanalConnectors;
                //SCSCompon.RefreshInterfacesJoining;
                TF_Main(GForm).OnUpdateComponent(FMakeEdit, FComponBeforeEdit, SCSCompon, GChangedIndex, GChangedNameShort);
                SCSComponent.NameMark := SCSCompon.NameMark;

                if GChangedUserLength then
                  SCSCompon.RefreshWholeLength;
              end;

              //*** Применить для всех компонентов
              {if CheckBox_ApplyForProject.Checked then
                AllComponents := TF_Main(GForm).GSCSBase.CurrProject.ComponentReferences
              else if CheckBox_ApplyForList.Checked and CheckBox_ApplyForList.Enabled then
                if Assigned(TF_Main(GForm).GSCSBase.CurrProject.CurrList) then
                  AllComponents := TF_Main(GForm).GSCSBase.CurrProject.CurrList.ComponentReferences;
              if Assigned(AllComponents) and (ProjComponent <> nil) then}
              if ComponentsForApply <> nil then 
                for i := 0 to ComponentsForApply.Count - 1 do
                begin
                  SCSCompon := ComponentsForApply[i];
                  if Assigned(SCSCompon) then
                    if SCSCompon.ID <> ProjComponent.ID then
                      if SCSCompon.GuidNB = ProjComponent.GuidNB then
                      begin
                        if cbApplyName.Checked then
                          SCSCompon.Name := ProjComponent.Name;
                        if cbApplyNameShort.Checked then
                          SCSCompon.NameShort := ProjComponent.NameShort;
                        if cbApplyArticulProducer.Checked then
                          SCSCompon.ArticulProducer := ProjComponent.ArticulProducer;
                        if cbApplyArticulDistributor.Checked then
                          SCSCompon.ArticulDistributor := ProjComponent.ArticulDistributor;
                        if cbApplyIzm.Checked then
                          SCSCompon.Izm := ProjComponent.Izm;
                        if cbApplyUserLength.Checked then
                          SCSCompon.UserLength := ProjComponent.UserLength;
                        if cbApplyComponentType.Checked then
                        begin
                          SCSCompon.ID_ComponentType := ProjComponent.ID_ComponentType;
                          SCSCompon.GUIDComponentType := ProjComponent.GUIDComponentType;
                        end;
                        if cbApplyNetType.Checked then
                        begin
                          SCSCompon.IDNetType := ProjComponent.IDNetType;
                          SCSCompon.GUIDNetType := ProjComponent.GUIDNetType;
                        end;
                        if cbApplyProducer.Checked then
                        begin
                          SCSCompon.ID_Producer := ProjComponent.ID_Producer;
                          SCSCompon.GUIDProducer := ProjComponent.GUIDProducer;
                        end;
                        if cbApplyIsMarkInCaptions.Checked then
                          SCSCompon.IsMarkInCaptions := ProjComponent.IsMarkInCaptions;
                        if cbApplyNotice.Checked then
                          SCSCompon.Notice := ProjComponent.Notice;
                        if cbApplyCanComplect.Checked then
                          SCSCompon.ISComplect := ProjComponent.ISComplect;
                        if cbApplyPrice.Checked then
                        begin
                          SCSCompon.IDSuppliesKind := ProjComponent.IDSuppliesKind;
                          SCSCompon.PriceSupply := ProjComponent.PriceSupply;
                          SCSCompon.Price_Calc := SCSCompon.Price_Calc - SCSCompon.Price + ProjComponent.Price;
                          SCSCompon.Price := ProjComponent.Price;
                          SCSCompon.HasNDS := ProjComponent.HasNDS;

                          //*** корректировать единицу измерения
                          if SCSComponent.IDSuppliesKind > 0 then
                            //SCSCompon.Izm := TF_Main(GForm).FNormBase.DM.GetSuppliesKindByID(ProjComponent.IDSuppliesKind).Izm;
                            SCSCompon.Izm := TF_Main(GForm).DM.GetSuppliesKindByID(ProjComponent.IDSuppliesKind,
                                                ProjComponent.GUIDComponentType).Izm;
                        end;
                        if cbApplyImage.Checked then
                          SCSCompon.AssignPicture(ProjComponent.Picture);
                        if cbApplySpecification.Checked then
                          SCSCompon.IDCompSpecification := ProjComponent.IDCompSpecification;
                        if cbApplyComponIcon.Checked then
                        begin
                          SCSCompon.IDObjectIcon := ProjComponent.IDObjectIcon;
                          SCSCompon.GUIDObjectIcon := ProjComponent.GUIDObjectIcon;
                        end;
                        if cbApplySymbol.Checked then
                        begin
                          SCSCompon.IDSymbol := ProjComponent.IDSymbol;
                          SCSCompon.GUIDSymbol := ProjComponent.GUIDSymbol;
                        end;
                        if cbApplyDescription.Checked then
                          SCSCompon.AssignDescription(ProjComponent.Description);

                        //--- Нормы и ресурсы
                        if cbApplyNorms.Checked then
                          SCSCompon.NormsResources.AssignNorms(ProjComponent.NormsResources.Norms); //SCSCompon.NormsResources.Assign(ProjComponent.NormsResources);
                        if cbApplyResources.Checked then
                          SCSCompon.NormsResources.AssignResources(ProjComponent.NormsResources.Resources);

                        if CheckBox_ApplyIncludingMark.Checked then
                        begin
                          SCSCompon.NameMark := ProjComponent.NameMark;
                          SCSCompon.IsUserMark := ProjComponent.IsUserMark;
                        end;

                        SCSCompon.SaveComponent;
                        TF_Main(GForm).OnUpdateComponent(FMakeEdit, nil, SCSCompon, GChangedIndex, GChangedNameShort);
                        //SCSCompon.AssignOnlyComponentCommonData(SCSComponent, CheckBox_ApplyIncludingMark.Checked);
                        //SCSCompon.SaveComponent;
                        //TF_Main(GForm).OnUpdateComponent(SCSCompon, GChangedNameShort);
                      end;
                end;
              RefreshAllLists;
            end
            else
              TF_Main(GForm).OnUpdateComponent(FMakeEdit, FComponBeforeEdit, SCSComponent, GChangedIndex, GChangedNameShort);
          end;

          with TF_Main(GForm) do
          begin
            if GDBMode = bkNormBase then
            begin
              GSCSBase.SCSComponent.LoadInterfaces;
              GSCSBase.SCSComponent.LoadCableCanalConnectors;
            end;
            DM.SelectInterfaces(Tree_Catalog.Selected);
            DM.LocateMTByOtherMT(DM.MemTable_InterfaceRel, DM.MemTable_InterfaceRelEd);
            DM.LocateMTByOtherMT(DM.MemTable_Port, DM.MemTable_PortEd);

            DM.SelectComponProperty(ProjComponent);
            DM.LocateMTByOtherMT(DM.MemTable_Property, DM.MemTable_PropertyEd);

            if ComponentType.SysName = ctsnCableChannel then
            begin
              DM.SelectCableChannelsConnectors(SCSComponent);
              DM.LocateMTByOtherMT(DM.mtCableCanalConnectors, DM.MemTable_CableCanalConnectorsEd);
            end;
            if (GDBMode = bkNormBase) and
              (ComponentType.SysName = ctsnCupBoard) then
            begin
              DM.SelectCrossConnections;
              DM.LocateMTByOtherMT(DM.MemTable_CrossConnection, DM.mtCrossConnectionEd);
            end;
            // Нормы и ресурсы
            if GDBMode = bkNormBase then
            begin
              SCSComponent.NormsResources.LoadNorms(false, true);
              SCSComponent.NormsResources.LoadResources(true);
              DM.SelectNorms(SCSComponent.NormsResources);
            end
            else
              DM.SelectNorms(ProjComponent.NormsResources);
            DM.LocateMTByOtherMT(DM.mtNorms, DM.MemTable_NormsEd);
          end;
        end;

        if Not FIsTemplate then
          with TF_Main(GForm) do
            if cbApplyForCurrentDir.Checked then
            begin
              if GDBMode = bkNormBase then
              begin
                GSCSBase.SCSComponent.LoadComponentByID(GSCSBase.SCSComponent.ID, true);
                DM.ApplyComponentForDir(GSCSBase.SCSComponent, GSCSBase.SCSCatalog.ID, cbIncludingSubFolders.Checked);
              end;
            end;

        //<#MemTableClar#>TF_Main(GForm).DM.CorrectInterfaceAdverseRelation(GIDComponent);

        //if GChangedUserLength then
        //  if TF_Main(GForm).GDBMode = bkProjectManager then
        //    TF_Main(GForm).GSCSBase.SCSComponent.RefreshWholeLength;
        //TF_Main(GForm).GSCSBase.SCSComponent.LoadComponentByID(GID_Component, false);
      end;
    finally
      EndProgress;
      Screen.Cursor := crDefault;
      Dec(GBaseBeginUpdateCount);
    end;

    if ComponentsForApply <> nil then
      FreeAndNil(ComponentsForApply);
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.BitBtn_OKClick: ' + E.Message);
  end;
end;

// ##### Отмена #####

procedure TF_AddComponent.BitBtn_CancelClick(Sender: TObject);
begin
  if ComboBox_ComponentType.DroppedDown then
    ComboBox_ComponentType.DroppedDown := false;

  Close;
  TF_Main(GForm).DM.MemTable_InterfaceRelEd.Active := false;
  TF_Main(GForm).DM.MemTable_PropertyEd.Active := false;
end;

// #############################################################################
// ############################ Подскаска ######################################
//

procedure TF_AddComponent.btCanComplectClick(Sender: TObject);
//var Hint: THintWindowClass;
begin
  TF_Main(GForm).F_AnswerToQuast.GCaption := cAddComponent_Msg6_1;
  TF_Main(GForm).F_AnswerToQuast.GAnswer := cAddComponent_Msg6_2;
  TF_Main(GForm).F_AnswerToQuast.ShowContextHelp(TF_Main(GForm).F_AnswerToQuast.GCaption, TF_Main(GForm).F_AnswerToQuast.GAnswer);
end;

// #############################################################################
// ########################## ActionList_Component #############################
//
// ##### По умолчанию #####

procedure TF_AddComponent.Act_DefaultExecute(Sender: TObject);

  procedure ClearMT(AMemTable: TkbmMemTable; ADeletedList: TIntList; AISInterface: Boolean);
  begin
    if AMemTable.Active = false then
      Exit; //// EXIT ////
    AMemTable.First;
    while not AMemTable.Eof do
    begin
      if (AMemTable.FieldByName('isNew').AsBoolean = false) and
        (not AISInterface or AMemTable.FieldByName(fnIsNative).AsBoolean) then
        ADeletedList.Add(AMemTable.FieldByName(fnID).AsInteger);
      AMemTable.Next;
    end;
    AMemTable.Active := false;
    AMemTable.Active := true;
  end;

begin
  EnableControl(true);

  if Edit_Name.Text = '' then
    Edit_Name.Text := 'Default';
  Edit_Name.SelectAll;
  Edit_Name.SetFocus;

  if Edit_ArticulDistributor.Text = '' then
    Edit_ArticulDistributor.Text := cAddComponent_Msg7;

  if Edit_ArticulProducer.Text = '' then
    Edit_ArticulProducer.Text := cAddComponent_Msg7;

  ComboBox_Producer.ItemIndex := 1;

  //Image.Clear;
  Image.Picture.Bitmap := nil;
  Image_CompIcons.Clear;

  //RadioGroup_CanComplect.ItemIndex := 1;
  cbCanComplect.Checked := true;
  CheckBox_HasNds.Checked := true; //RadioGroup_HasNds.ItemIndex := 0;
  cbIsMarkInCaptions.Checked := false;

  CurrencyEdit_Price1.Value := 0;
  CurrencyEdit_Price2.Value := 0;
  CurrencyEdit_NDS1.Visible := false;
  CurrencyEdit_NDS2.Visible := false;

  GID_Currency := TF_Main(GForm).GCurrencyM.ID;
  ComboBox_NetType.ItemIndex := 0;
  cbSpecification.ItemIndex := 0;

  with TF_Main(GForm).DM do
  begin
    ClearMT(MemTable_InterfaceRelEd, GDeletedInterfRel, true);
    ClearMT(MemTable_PropertyEd, GDeletedPropRel, false);
    //ClearMT(F_NormBase.DM.MemTable_ComponentIcons, GDeletedComponIcons);
    GChangedInterface := true;
    GChangedProperty := true;
    GChangedObjectIcons := true;
    GChangedPicture := true;
  end;

  // Загрузить свойства  По Умолчанию
  if ComboBox_ComponentType.Text = '' then
    ComboBox_ComponentType.ItemIndex := 1;
  ComboBox_ComponentTypePropertiesChange(ComboBox_ComponentType);
end;

// ##### Добавить интерфейс #####

procedure TF_AddComponent.Act_AddInterfaceExecute(Sender: TObject);
//var FieldsNames: TStringList;
    //i: Integer;
    //meInterfaceRel: TmeInterfaceRel;
    //ComponentType: TComponentType;
begin
  AddInterfacePort(biFalse);
  {try
    try
      FieldsNames := nil;
      if (GFormMode = fmView) or (GFormMode = fmDisabled) then
        Exit;

      if ComboBox_ComponentType.Text <> '' then
        ComponentType := TF_Main(GForm).FNormBase.DM.GetComponentType(GetIDFromComboBox(ComboBox_ComponentType))
      else
        ComponentType.IsLine := biFalse;

      meInterfaceRel.IsLineCompon := ComponentType.IsLine;
      F_NormBase.F_CaseForm.GUseMemTable := TF_Main(GForm).DM.MemTable_InterfaceRelEd;
      if TF_Main(GForm).F_AddInterface.GetInterfRel(meInterfaceRel, fmMake) then
        begin
            meInterfaceRel.NAME := TF_Main(GForm).F_AddInterface.ComboBox_Name.Text;
            AddInterfaceToMT(meInterfaceRel);
        end;

      FieldsNames := TStringList.Create;
      FieldsNames.Clear;
      FieldsNames.Add('Name');
      RefreshFields(TF_Main(GForm).DM.MemTable_InterfaceRelEd, 'INTERFACE', 'ID_Interface', 'ID', FieldsNames);
    except
      on E: Exception do AddExceptionToLog('TF_AddComponent.Act_AddInterfaceExecute: : '+E.Message);
    end;
  finally
    if FieldsNames <> nil then
      FieldsNames.Free;
  end; }
end;

// ##### Редактировать интерфейс #####

procedure TF_AddComponent.Act_EditInterfaceExecute(Sender: TObject);
//var FieldsNames: TStringList;
    //meInterfaceRel: TmeInterfaceRel;
    //EditId: Integer;
    //ID_Adverse: Integer;
    //NumPair: Integer;
    //RecNo: Integer;
    //ComponentType: TComponentType;
begin
  EditInterfacePort(biFalse);
  (*try
    try
      FieldsNames := nil;
      EditID := TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('ID').AsInteger;
      NumPair := TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('Num_Pair').AsInteger;
      RecNo := -1;

      if (GFormMode = fmView) or (GFormMode = fmDisabled) then
        Exit; ///// EXIT /////

      if TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('isNew').AsBoolean = false then
        if isUseInterfRel(GForm, TF_Main(GForm).DM.MemTable_InterfaceRelEd, meEdit) then
          Exit; ///// EXIT /////

      if TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('isBusy').AsInteger = biTrue then
        begin
            MessageModal(Self.Handle, 'Интерфейс занят', 'Редактирование интерфейса', MB_ICONINFORMATION or MB_OK);
            Exit; ///// EXIT /////
        end;

      if ComboBox_ComponentType.Text <> '' then
        ComponentType := TF_Main(GForm).FNormBase.DM.GetComponentType(GetIDFromComboBox(ComboBox_ComponentType))
      else
        ComponentType.IsLine := biFalse;

      meInterfaceRel := TF_Main(GForm).DM.GetInterfaceRel(TF_Main(GForm).DM.DataSource_MT_INTERFACERelEd);
      meInterfaceRel.IsLineCompon := ComponentType.IsLine;
      F_NormBase.F_CaseForm.GUseMemTable := TF_Main(GForm).DM.MemTable_InterfaceRelEd;
      if TF_Main(GForm).F_AddInterface.GetInterfRel(meInterfaceRel, fmEdit) then
        begin
            meInterfaceRel.ID_COMPONENT := TF_Main(GForm).GSCSBase.SCSComponent.ID;
            RecNo := TF_Main(GForm).DM.MemTable_InterfaceRelEd.RecNo;
            with TF_Main(GForm).DM.MemTable_InterfaceRelEd do
              begin
                  Edit;
                  FieldByName('Name').AsString := meInterfaceRel.Name;
                  FieldByName('TypeI').AsInteger := meInterfaceRel.Typei;
                  FieldByName('Kind').AsInteger := meInterfaceRel.Kind;
                  FieldByName('Gender').AsInteger := meInterfaceRel.Gender;
                  FieldByName('Multiple').AsInteger := meInterfaceRel.Multiple;
                  FieldByName('ID_Interface').AsInteger := meInterfaceRel.ID_INTERFACE;
                  FieldByName('ValueI').AsFloat := meInterfaceRel.ValueI;
                  FieldByName('Color').AsFloat := meInterfaceRel.Color;
                  FieldByName('isModified').AsBoolean := true;
                  Post;

                  if meInterfaceRel.ID_Adverse <> 0 then
                    if SearchRecordMT(TF_Main(GForm).DM.MemTable_InterfaceRelEd, 'id', meInterfaceRel.ID_Adverse) then
                      begin
                          Edit;
                          FieldByName('Name').AsString := meInterfaceRel.Name;
                          FieldByName('TypeI').AsInteger := meInterfaceRel.Typei;
                          FieldByName('Kind').AsInteger := meInterfaceRel.Kind;
                          FieldByName('Gender').AsInteger := meInterfaceRel.Gender;
                          FieldByName('Multiple').AsInteger := meInterfaceRel.Multiple;
                          FieldByName('ID_Interface').AsInteger := meInterfaceRel.ID_INTERFACE;
                          FieldByName('ValueI').AsFloat := meInterfaceRel.ValueI;
                          FieldByName('Color').AsFloat := meInterfaceRel.Color;
                          FieldByName('isModified').AsBoolean := true;
                          Post;

                          //*** Вернуться назад
                          //SearchRecordMT(TF_Main(GForm).DM.MemTable_InterfaceRelEd, 'id', meInterfaceRel.ID);
                      end;
                  GChangedInterface := true;
              end;
        end;

      {TF_Main(GForm).F_AddInterface.GFormMode := fmEdit;
      TF_Main(GForm).F_AddInterface.GID_Interface := TF_Main(GForm).DM.MemTable_Interface.FieldByName('ID_Interface').AsInteger;
      TF_Main(GForm).F_AddInterface.GKolvo := TF_Main(GForm).DM.MemTable_Interface.FieldByName('Kolvo').AsInteger;
      TF_Main(GForm).F_AddInterface.GTypeInterface := TF_Main(GForm).DM.MemTable_Interface.FieldByName('TypeI').AsInteger;

      with TF_Main(GForm).DM.MemTable_Interface do
        begin
          if TF_Main(GForm).F_AddInterface.ShowModal = mrOK then
            begin
                Edit;
                FieldByName('Name').AsString := TF_Main(GForm).F_AddInterface.ComboBox_Name.Text;
                FieldByName('TypeI').AsInteger := TF_Main(GForm).F_AddInterface.ComboBox_Type_I.ItemIndex;
                FieldByName('Gender').AsInteger := 1 - TF_Main(GForm).F_AddInterface.RadioGroup_Gender.ItemIndex;
                FieldByName('ID_Interface').AsInteger := TF_Main(GForm).F_AddInterface.GID_INTERFACE;
                FieldByName('Kolvo').AsInteger := TF_Main(GForm).F_AddInterface.SpinEdit_Kolvo.Value;
                FieldByName('isModified').AsBoolean := true;
                Post;
            end;

            GChangedInterface := true;
          end;         }
      //GT_Interface.DataController.DataSource := TF_Main(GForm).DM.DataSource_MT_INTERFACE;

      // Обновить данные
      FieldsNames := TStringList.Create;
      FieldsNames.Clear;
      FieldsNames.Add('Name');
      RefreshFields(TF_Main(GForm).DM.MemTable_InterfaceRelEd, 'INTERFACE', 'ID_Interface', 'ID', FieldsNames);

    except
      on E: Exception do AddExceptionToLog('TF_AddComponent.Act_EditInterfaceExecute: : '+E.Message);
    end;
  finally
    if FieldsNames <> nil then
      FieldsNames.Free;
    if RecNo <> -1 then
      begin
          TF_Main(GForm).DM.MemTable_InterfaceRelEd.First;
          TF_Main(GForm).DM.MemTable_InterfaceRelEd.RecNo := RecNo;
      end;
  end; *)
end;

// ##### Удалить интерфейс #####

procedure TF_AddComponent.Act_DelInterfaceExecute(Sender: TObject);
//var InterfName: String;
    //DelID: Integer;
    //ID_Adverse: Integer;
    //NumPair: Integer;
begin
  DelInterfacePort(biFalse);
  (*try
    DelID := TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('ID').AsInteger;
    NumPair := TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('Num_Pair').AsInteger;
    if (GFormMode = fmView) or (GFormMode = fmDisabled) then
      Exit; ///// EXIT /////

    if TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('isNew').AsBoolean = false then
      if isUseInterfRel(GForm, TF_Main(GForm).DM.MemTable_InterfaceRelEd, meDel) then
        Exit; ///// EXIT /////

    if TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('isBusy').AsInteger = biTrue then
      begin
          MessageModal(Self.Handle, 'Интерфейс занят', 'Удаление интерфейса', MB_ICONINFORMATION or MB_OK);
          Exit; ///// EXIT /////
      end;

    InterfName := TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('Name').AsString;
    if MessageModal(Self.Handle, PAnsiChar('Удалить интерфейс "'+ InterfName + '" ?'),
                  'Удаление интерфейса', MB_YESNO or MB_ICONQUESTION) = mrYES then
      begin
          ID_Adverse := TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('id_Adverse').AsInteger;
          NumPair := TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('Num_Pair').AsInteger;

          if TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('isNew').AsBoolean = false then
            GDeletedInterfRel.Add(IntToStr(DelID))
          else
            GGenLastInterfID := GGenLastInterfID - 1;
          TF_Main(GForm).DM.MemTable_InterfaceRelEd.Delete;

          if NumPair <> 0 then
            with TF_Main(GForm).DM do
              begin
                  MemTable_InterfaceRelEd.Last;
                  while Not MemTable_InterfaceRelEd.Bof do
                    begin
                        if MemTable_InterfaceRelEd.FieldByName('Num_Pair').AsInteger = NumPair then
                          begin
                              if MemTable_InterfaceRelEd.FieldByName('isNew').AsBoolean = false then
                                GDeletedInterfRel.Add(IntToStr(MemTable_InterfaceRelEd.FieldByName('ID').AsInteger))
                              else
                                GGenLastInterfID := GGenLastInterfID - 1;
                              TF_Main(GForm).DM.MemTable_InterfaceRelEd.Delete;
                          end
                        else
                          MemTable_InterfaceRelEd.Prior;
                    end;

                  {if SearchRecordMT(TF_Main(GForm).DM.MemTable_InterfaceRelEd, 'id', ID_Adverse) then
                    begin
                        if TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('isNew').AsBoolean = false then
                          GDeletedInterfRel.Add(IntToStr(ID_Adverse))
                        else
                          GGenLastInterfID := GGenLastInterfID - 1;
                        TF_Main(GForm).DM.MemTable_InterfaceRelEd.Delete;
                    end;   }
              end;
          GChangedInterface := true;
          EnableButtons;
      end;
  except
    on E: Exception do AddExceptionToLog('TF_AddComponent.Act_DelInterfaceExecute: : '+E.Message);
  end;      *)
end;

// ##### Добавление порта #####

procedure TF_AddComponent.Act_AddPortExecute(Sender: TObject);
begin
  AddInterfacePort(biTrue);
end;

// ##### Редактирование порта #####

procedure TF_AddComponent.Act_EditPortExecute(Sender: TObject);
begin
  EditInterfacePort(biTrue);
end;

// ##### Удаление порта #####

procedure TF_AddComponent.Act_DelPortExecute(Sender: TObject);
begin
  DelInterfacePort(biTrue);
end;

// ##### Добавить свойство #####

procedure TF_AddComponent.Act_AddPropertyExecute(Sender: TObject);
//var FieldsNames: TStringList;
    //ID_DataType: Integer;
//    ComponentType: TComponentType;
begin
  AddEditProperty(meMake);

  {try
    ComponentType := GetComponentType;

    FieldsNames := nil;
    //F_NormBase.F_CaseForm.GViewKind := vkProperty;
    //F_NormBase.F_CaseForm.GFormMode := fmMake;
    if ComponentType.IsLine = biTrue then
      F_NormBase.F_CaseForm.GItemType := itComponLine
    else
      F_NormBase.F_CaseForm.GItemType := itComponCon;
    F_NormBase.F_CaseForm.GUseMemTable := TF_Main(GForm).DM.MemTable_PropertyEd;
    //if F_NormBase.F_CaseForm.ShowModal = mrOk then
    if F_NormBase.F_CaseForm.Execute(vkProperty, fmMake) then
      with TF_Main(GForm).DM.MemTable_PropertyEd do
        begin
            with TF_Main(GForm) do
              if Not DM.CheckNoRepeatPropertyMT(DM.MemTable_PropertyEd, F_NormBase.DM.DataSet_PROPERTIES.FN('ID').AsInteger, Edit_Name.Text) then
                Exit; ///// EXIT /////

            last;
            Append;
            FieldByName('ID').AsInteger := GenNewID(tkCompPropRelED);
            FieldByName('Name').AsString := F_NormBase.DM.DataSet_PROPERTIES.FN('Name').AsString;
            FieldByName('SysName').AsString := F_NormBase.DM.DataSet_PROPERTIES.FN('SysName').AsString;
            FieldByName('ID_PROPERTY').AsInteger := F_NormBase.DM.DataSet_PROPERTIES.FN('ID').AsInteger;
            FieldByName('PVALUE').AsString := F_NormBase.F_CaseForm.GValue;
            FieldByName('Izm').AsString := F_NormBase.DM.DataSet_PROPERTIES.FN('Izm').AsString;
            FieldByName('TAKE_INTO_CONNECT').AsInteger := F_NormBase.F_CaseForm.GTakeIntoConnect;
            FieldByName('TAKE_INTO_JOIN').AsInteger := F_NormBase.F_CaseForm.GTakeIntoJoin;
            FieldByName('Description').AsString := F_NormBase.DM.DataSet_PROPERTIES.FN('Description').AsString;
            FieldByName('IsStandart').AsInteger := F_NormBase.DM.DataSet_PROPERTIES.FN('IsStandart').AsInteger;
            FieldByName(fnIsDefault).AsInteger := biFalse;
            FieldByName('isNew').AsBoolean := true;
            FieldByName('isModified').AsBoolean := false;
            Post;

            GChangedProperty := true;
            EnableButtons;
        end;

    FieldsNames := TStringList.Create;
    try
      FieldsNames.Clear;
      FieldsNames.Add('Name');
      FieldsNames.Add('SysName');
      FieldsNames.Add('Name');
      FieldsNames.Add('Izm');
      FieldsNames.Add('Description');
      FieldsNames.Add('ID_Data_Type');
      RefreshFields(TF_Main(GForm).DM.MemTable_PropertyEd, 'PROPERTIES', 'ID_Property', 'ID', FieldsNames);
    finally
      FreeAndNil(FieldsNames);
    end;
  except
    on E: Exception do AddExceptionToLog('TF_AddComponent.Act_AddPropertyExecute: '+E.Message);
  end;}
end;

// ##### Редактировать свойство #####

procedure TF_AddComponent.Act_EditPropertyExecute(Sender: TObject);
{var FieldsNames: TStringList;
    ComponentType: TComponentType;

  procedure SendToMT_Prop;
  begin
      with TF_Main(GForm).DM.MemTable_PropertyEd do
       begin
           FieldByName('Name').AsString := F_NormBase.DM.DataSet_PROPERTIES.FN('Name').AsString;
           FieldByName('SysName').AsString := F_NormBase.DM.DataSet_PROPERTIES.FN('SysName').AsString;
           FieldByName('ID_PROPERTY').AsInteger := F_NormBase.DM.DataSet_PROPERTIES.FN('ID').AsInteger;
           FieldByName('Izm').AsString := F_NormBase.DM.DataSet_PROPERTIES.FN('Izm').AsString;
           FieldByName('Description').AsString := F_NormBase.DM.DataSet_PROPERTIES.FN('Description').AsString;
        end;
  end;}

begin
  AddEditProperty(meEdit);
  {try
    Exit; //// EXIT /////

    ComponentType := GetComponentType;

    //GT_Property.DataController.DataSource := nil;
    FieldsNames := nil;
    //F_NormBase.F_CaseForm.GViewKind := vkProperty;
    //F_NormBase.F_CaseForm.GFormMode := fmEdit;
    if ComponentType.IsLine = biTrue then
      F_NormBase.F_CaseForm.GItemType := itComponLine
    else
      F_NormBase.F_CaseForm.GItemType := itComponCon;
    F_NormBase.F_CaseForm.GIDToLocate := TF_Main(GForm).DM.MemTable_PropertyEd.FieldByName('ID_PROPERTY').AsInteger;
    F_NormBase.F_CaseForm.GValue := TF_Main(GForm).DM.MemTable_PropertyEd.FieldByName('PValue').AsString;
    F_NormBase.F_CaseForm.GTakeIntoConnect := TF_Main(GForm).DM.MemTable_PropertyEd.FieldByName('TAKE_INTO_CONNECT').AsInteger;
    F_NormBase.F_CaseForm.GTakeIntoJoin := TF_Main(GForm).DM.MemTable_PropertyEd.FieldByName('TAKE_INTO_JOIN').AsInteger;
    F_NormBase.F_CaseForm.GUseMemTable := TF_Main(GForm).DM.MemTable_PropertyEd;
    with TF_Main(GForm).DM.MemTable_PropertyEd do
      begin
         //if F_NormBase.F_CaseForm.ShowModal = mrOK then
         if F_NormBase.F_CaseForm.Execute(vkProperty, fmEdit) then
           begin
               Edit;
               SendToMT_Prop;
               FieldByName('PVALUE').AsString := F_NormBase.F_CaseForm.GValue;
               FieldByName('TAKE_INTO_CONNECT').AsInteger := F_NormBase.F_CaseForm.GTakeIntoConnect;
               FieldByName('TAKE_INTO_JOIN').AsInteger := F_NormBase.F_CaseForm.GTakeIntoJoin;
               FieldByName('isModified').AsBoolean := true;
               Post;
           end;

         // Загрузить условные обозначения
         if FieldByName('ID_Data_Type').AsInteger = dtCompStateType then
           begin
               LoadComponIcon(GIDObjectIcon, Image_CompIcons); //RefreshCompIcons(StrToInt(F_NormBase.F_CaseForm.GValue));
               LoadComponIcon(GIDSymbolImage, Image_Symbol);
           end;
         GChangedProperty := true;
      end;
     //GT_Property.DataController.DataSource := TF_Main(GForm).DM.DataSource_MT_Property;
     // Обновление полей
     FieldsNames := TStringList.Create;
     try
       FieldsNames.Clear;
       FieldsNames.Add('Name');
       FieldsNames.Add('SysName');
       FieldsNames.Add('Name');
       FieldsNames.Add('Izm');
       FieldsNames.Add('Description');
       FieldsNames.Add('ID_Data_Type');
       RefreshFields(TF_Main(GForm).DM.MemTable_PropertyEd, 'PROPERTIES', 'ID_Property', 'ID', FieldsNames);
     finally
       FreeAndNil(FieldsNames);
     end;
  except
    on E: Exception do AddExceptionToLog('TF_AddComponent.Act_EditPropertyExecute: '+E.Message);
  end;}
end;

// ##### Удалить свойство #####

procedure TF_AddComponent.Act_DelPropertyExecute(Sender: TObject);
var
  PropName: string;
  PropSysName: string;
  DelID: Integer;
  CanDel: Boolean;
begin
  PropName := TF_Main(GForm).DM.MemTable_PropertyEd.FieldByName(fnName).AsString;
  PropSysName := TF_Main(GForm).DM.MemTable_PropertyEd.FieldByName(fnSysName).AsString;

  if TF_Main(GForm).DM.MemTable_PropertyEd.FieldByName(fnIsDefault).AsInteger = biTrue then
  begin
    {$IF Defined (FINAL_SCS)}
      MessageModal(cImpossibleDelProperty + ' "' + PropName + '", ' + cSinceItUse + '.', cDeletingProperty, MB_ICONINFORMATION or MB_OK);
      Exit; //// EXIT ////
    {$ELSE}
      if MessageQuastYN(cImpossibleDelProperty + ' "' + PropName + '", ' + cSinceItUse + '. Delete it ?') <> IDYES then
        Exit; //// EXIT ////
    {$IFEND}
  end;

  ////*** Не дать удалить стандартное свойство
  //if TF_Main(GForm).DM.MemTable_PropertyEd.FieldByName('isStandart').AsInteger = 1 then
  //  begin
  //      MessageModal(Self.Handle, 'Нельзя удалить стандартное свойство.', 'Удаление свойства', MB_ICONINFORMATION or MB_OK);
  //      Exit;
  //  end;

  {//*** Если компонент линейный, то не удалять свойство "Длина"
  if RadioGroup_IsLine.ItemIndex = 0 then
    if PropSysName = 'LENGTH' then
      begin
          MessageModal(Self.Handle, 'Нельзя удалить свойство "Длина" т.к. данный компонент линейного типа.',
                  'Нельзя удалить свойство ', MB_OK or MB_ICONINFORMATION);
          Exit;
      end;}

  if MessageModal(cQuastDelProperty + ' "' + PropName + '" ?', cDeletingProperty,
    MB_YESNO or MB_ICONQUESTION) = mrYES then
  begin
    DelID := TF_Main(GForm).DM.MemTable_PropertyEd.FieldByName(fnID).AsInteger;

      CanDel := true;
      if GetNormResourcesCountByCompPropRelID(DelID) > 0 then
      begin
        case MessageModal(cMain_Msg177, ApplicationName, MB_YESNOCANCEL or MB_ICONQUESTION) of
          IDYES:
            DeleteNormResByIDCompPropRel(DelID);
          IDCANCEL:
            CanDel := false;
        end;
      end;

    if CanDel then
    begin
      if TF_Main(GForm).DM.MemTable_PropertyEd.FieldByName(fnIsNew).AsBoolean = false then
        GDeletedPropRel.Add(DelID);

      TF_Main(GForm).DM.MemTable_PropertyEd.Delete;
      GChangedProperty := true;
      EnableButtons;
    end;
  end;
end;

// ##### Добавить комплектующую #####

procedure TF_AddComponent.Act_AddComplectEdExecute(Sender: TObject);
begin
  {EnableMakeEditCompon(False);
  TF_Main(GForm).AddEditComplect(cmAdd, true);
  EnableMakeEditCompon(True);

  SetCalcPrice;
  ChangedComplect := true;
  EnableButtons; }
  MessageModal(cbMessage2 + ' "' + GetMainformName + '"',
    cAddingComplect, MB_ICONINFORMATION or MB_OK);
end;

// ##### Удалить Комплектующую #####

procedure TF_AddComponent.Act_DelComplectEdExecute(Sender: TObject);
//var ComplectName : String;
    //DelID: Integer;
begin
  MessageModal(cbMessage3 + ' "' + GetMainformName + '"',
    cDeletingComplect, MB_ICONINFORMATION or MB_OK);

  {
  ComplectName := TF_Main(GForm).DM.MemTable_ComplectsEd.FieldByName('Name').AsString;
  if MessageModal(Self.Handle, PAnsiChar('Удалить Комплектуюущую "' + ComplectName +'" ?'),
                'Удаление Комплектуюущей', MB_YESNO or MB_ICONQUESTION) = mrYES then
    begin
        DelID := TF_Main(GForm).DM.MemTable_ComplectsEd.FieldByName('ID').AsInteger;
        GDeletedComplects.Add(IntToStr(DelID));

        TF_Main(GForm).DM.MemTable_ComplectsEd.Delete;
        SetCalcPrice;
        GChangedComplect := true;
        EnableButtons;
    end; }
end;

// ##### Редактировать Комплектующую #####

procedure TF_AddComponent.Act_EditComplectEdExecute(Sender: TObject);
begin
  {EnableMakeEditCompon(False);
  TF_Main(GForm).AddEditComplect(cmEdit, true);
  EnableMakeEditCompon(True);
  SetCalcPrice;
  ChangedComplect := true;
  EnableButtons;}
  MessageModal(cbMessage4 + ' "' + GetMainformName + '"',
    cEditingComplect, MB_ICONINFORMATION or MB_OK);
end;

// ##### Добавить соединитель кабельного калана #####

procedure TF_AddComponent.Act_AddCableCanalConnectorExecute(
  Sender: TObject);
begin
  AddEditCableCanalConnector(meMake);
  EnableButtons;
end;

// ##### Редактировать соединитель кабельного калана #####

procedure TF_AddComponent.Act_EditCableCanalConnectorExecute(
  Sender: TObject);
begin
  AddEditCableCanalConnector(meEdit);
end;

procedure TF_AddComponent.Act_DelCableCanalConnectorExecute(
  Sender: TObject);
var
  DelName: string;
  DelID: Integer;
begin
  with TF_Main(GForm).DM do
  begin
    DelName := MemTable_CableCanalConnectorsEd.FieldByName(fnName).AsString;
    if MessageModal(cQuastDelCableChannelElement + ' "' + DelName + '"?',
      Application.Title, MB_YESNO or MB_ICONQUESTION) = IDYES then
    begin
      if MemTable_CableCanalConnectorsEd.FieldByName(fnIsNew).AsBoolean = false then
      begin
        DelID := MemTable_CableCanalConnectorsEd.FieldByName(fnID).AsInteger;
        GDeletedCableCanalConnectors.Add(DelID);
      end;
      MemTable_CableCanalConnectorsEd.Delete;
    end;
  end;
  EnableButtons;
end;

// ##### Удалить соединитель кабельного калана #####

procedure TF_AddComponent.GT_InterfaceTypeGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: string);
begin
  if AText = '0' then
    AText := cAddComponent_Msg8_1;
  if AText = '1' then
    AText := cAddComponent_Msg8_2;
end;

procedure TF_AddComponent.GT_InterfaceKindGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: string);
begin
  if AText = '0' then
    AText := cAddComponent_Msg9_1;
  if AText = '1' then
    AText := cAddComponent_Msg9_2;
end;

procedure TF_AddComponent.GT_InterfaceValueIGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: string);
begin
  if AText = '0' then
    AText := cAddComponent_Msg10
  else
    AText := GetDisplayTextInFLoatUOMMin2(AText, TF_Main(GForm).FUOM);
end;

procedure TF_AddComponent.GT_InterfaceNumPairsStrGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: string);
begin
  if AText = '0' then
    AText := cAddComponent_Msg10;
end;

procedure TF_AddComponent.GT_InterfaceSideGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: string);
begin
  if AText = '0' then
    AText := cAddComponent_Msg10;
end;

procedure TF_AddComponent.ComboBox_NetTypeKeyPress(Sender: TObject;
  var Key: Char);
begin
  Key := #0;
end;

// ##### Нажатие клавиши в Цену 1 #####

procedure TF_AddComponent.CurrencyEdit_Price1_KeyUp(Sender: TObject;
  var Key: Word; Shift: TShiftState);
var
  NewValue: Double;
  RoundValue: Double;
begin
  try
    NewValue := 0;
    //if StrCanBeFloat(CurrencyEdit_Price1.Text) then
    begin
      NewValue := StrToFloatU(CorrectStrToFloat(CurrencyEdit_Price1.Text));
      DefineComponSecondPrice(NewValue);
      ShowNDSPrice;
      GWasChanging := true;

      DefineSupplyPriceByComponActualPrice; //DefineSupplyPriceByComponPrice(NewValue);
    end;
    {if Key in [188, 190, 191, 110] then
      Exit;
    if CurrencyEdit_Price1.Text <> '' then
      NewValue := StrToFloat_My(CurrencyEdit_Price1.Text)
    else
      NewValue := 0;

    if Not (CurrencyEdit_Price1.Text[Length(CurrencyEdit_Price1.Text)] in ['0', ',', '.']) and
       Not (CurrencyEdit_Price1.Text[1] in ['0', ',', '.']) then
      CurrencyEdit_Price1.Value := NewValue;

    RoundValue := RoundX(NewValue * (TF_Main(GForm).GCurrencyM.Ratio / TF_Main(GForm).GCurrencyS.Ratio),2);
    CurrencyEdit_Price2.Value := RoundValue;
    ShowNDSPrice;
    GWasChanging := true;}
  except
  end;
end;

// ##### Нажатие клавиши в Цену 2 #####

procedure TF_AddComponent.CurrencyEdit_Price2KeyUp(Sender: TObject;
  var Key: Word; Shift: TShiftState);
var
  NewValue: Double;
  RoundValue: Double;
begin
  try
    NewValue := 0;
    //if StrCanBeFloat(CurrencyEdit_Price2.Text) then
    begin
      NewValue := StrToFloatU(CorrectStrToFloat(CurrencyEdit_Price2.Text));
      //RoundValue := Round3(NewValue * (TF_Main(GForm).GLocalCurrencyS.Data.Ratio / TF_Main(GForm).GLocalCurrencyM.Data.Ratio));
      RoundValue := Round3(GetPriceAfterChangeCurrency(NewValue, TF_Main(GForm).GLocalCurrencyS.Data, TF_Main(GForm).GLocalCurrencyM.Data, valEpsilonCurrency));
      CurrencyEdit_Price1.Value := RoundValue;
      ShowNDSPrice;
      GWasChanging := true;

      DefineSupplyPriceByComponActualPrice; //DefineSupplyPriceByComponPrice(RoundValue);
    end;

    {
    if Key in [188, 190, 191, 110] then
      Exit;

    if CurrencyEdit_Price2.Text <> '' then
      NewValue := StrToFloat_My( CurrencyEdit_Price2.Text)
    else
      NewValue := 0;

    if Not(CurrencyEdit_Price2.Text[Length(CurrencyEdit_Price2.Text)] in ['0', ',', '.']) and
       Not(CurrencyEdit_Price2.Text[1] in ['0', ',', '.']) then
      CurrencyEdit_Price2.Value := NewValue;

    RoundValue := RoundX(NewValue * (TF_Main(GForm).GCurrencyS.Ratio / TF_Main(GForm).GCurrencyM.Ratio), 2);
    CurrencyEdit_Price1.Value := RoundValue;
    ShowNDSPrice;
    GWasChanging := true; }
  except
  end;
end;

procedure TF_AddComponent.cePriceSupplyKeyUp(Sender: TObject;
  var Key: Word; Shift: TShiftState);
var
  NewValue: Double;
begin
  NewValue := StrToFloatU(CorrectStrToFloat(cePriceSupply.Text));
  DefineParamsBySupply(NewValue, false);
end;

// ##### Добавить #####

procedure TF_AddComponent.Act_AddExecute(Sender: TObject);
begin
  { if GFormMode = fmView then
     Exit;}
  if ReadOnly then
    Exit; ///// EXIT /////

  case Grid.ActiveLevel.Index of
    liInterface:
      Act_AddInterface.Execute;
    liPort:
      Act_AddPort.Execute;
    liProperty:
      Act_AddProperty.Execute;
    liCableCanalConnectors:
      Act_AddCableCanalConnector.Execute;
    liComplects:
      Act_AddComplectEd.Execute;
    liCrossConnections:
      Act_AddCrossConnection.Execute;
  end;
  GWasChanging := true;
end;

// ##### Удалить #####

procedure TF_AddComponent.Act_DelExecute(Sender: TObject);
begin
  {if GFormMode = fmView then
    Exit;}
  if ReadOnly then
    Exit; ///// EXIT /////

  case Grid.ActiveLevel.Index of
    liInterface:
      Act_DelInterface.Execute;
    liPort:
      Act_DelPort.Execute;
    liProperty:
      Act_DelProperty.Execute;
    liCableCanalConnectors:
      Act_DelCableCanalConnector.Execute;
    liComplects:
      Act_DelComplectEd.Execute;
    liCrossConnections:
      Act_DelCrossConnection.Execute;
  end;
  GWasChanging := true;
end;

// ##### Редактировать #####

procedure TF_AddComponent.Act_EditExecute(Sender: TObject);
begin
  try
    //if TF_Main(GForm).GDBMode = bkProjectManager then
    //  Exit;  ///// EXIT /////

    if ReadOnly then
      Exit; ///// EXIT /////

    case Grid.ActiveLevel.Index of
      liInterface:
        if TF_Main(GForm).DM.MemTable_InterfaceRelEd.RecordCount > 0 then
          Act_EditInterface.Execute;
      liPort:
        if TF_Main(GForm).DM.MemTable_PortEd.RecordCount > 0 then
          Act_EditPort.Execute;
      liProperty:
        if TF_Main(GForm).DM.MemTable_PropertyEd.RecordCount > 0 then
          Act_EditProperty.Execute;
      liCableCanalConnectors:
        if TF_Main(GForm).DM.MemTable_CableCanalConnectorsEd.RecordCount > 0 then
          Act_EditCableCanalConnector.Execute;
      liComplects:
        if TF_Main(GForm).DM.MemTable_ComplectsEd.RecordCount > 0 then
          Act_EditComplectEd.Execute;
      liCrossConnections:
        Act_EditCrossConnection.Execute;
    end;
    GWasChanging := true;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.Act_EditExecute: ' + E.Message);
  end;
end;

// ##### Изменен Tab #####

procedure TF_AddComponent.GridActiveTabChanged(Sender: TcxCustomGrid;
  ALevel: TcxGridLevel);
begin
  EnableButtons;
  DefinecbApplyCompData;
end;

// ##### Подставить Edit-ы в Grid #####

procedure TF_AddComponent.GT_PropertyPValueGetProperties(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AProperties: TcxCustomEditProperties);
begin
  if ARecord.Values[6] <> null then
    with TF_Main(GForm).DM do
    begin
      case ARecord.Values[6] of
        dtBoolean:
          AProperties := EditRepositoryCheckBoxItem.Properties;
        //dtFloat  :   AProperties := EditRepositorySpinItem.Properties;
        //dtInteger:   AProperties := EditRepositorySpinItem.Properties;
        //dtDate:
        //  AProperties := EditRepositoryDateItem.Properties;
        dtCompStateType:
          AProperties := EditRepositoryLookupCompSateType.Properties;
        dtColor:
          AProperties := EditRepositoryColorComboBox.Properties;
        dtCableCanalElementType:
          AProperties := EditRepositoryLookupCableCanalElementType.Properties;
        //dtSectionSide:
        //  AProperties := EditRepositoryMaskItemSectionSide.Properties;
      end;
    end;
end;

procedure TF_AddComponent.GT_PropertyPValueGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
//var
//  CurrFloat: Double;
var DoSetDisplay: boolean; // IGOR 04/07/2019 --
begin
  // IGOR 04/07/2019 --
  DoSetDisplay := True;
  if ARecord.Values[6] <> null then
  begin
    if (ARecord.Values[6] = dtBoolean) or (ARecord.Values[6] = dtCompStateType)
      or (ARecord.Values[6] = dtColor) or (ARecord.Values[6] = dtCableCanalElementType) then
      DoSetDisplay := False;
  end;
  if DoSetDisplay then
  //
    SetDisplayTextToGridTablePropValue(AText, ARecord, 6, 7, TF_Main(GForm).FUOM);
  {if ARecord.Values[6] <> null then
    case ARecord.Values[6] of
      dtFloat:
        try
          CurrFloat := StrToFloatU(AText);
          if GPropSysNameInUOM.IndexOf(ARecord.Values[7]) <> -1 then
            CurrFloat := RoundCP(FloatInUOM(CurrFloat, umMetr, TF_Main(GForm).FUOM));
          AText := FloatToStr(CurrFloat);
        except
        end;
      dtDate:
        try
          AText := DateToStr(StrToDateU(AText));
        except
        end;
    end;}
end;


// ##### Подсчитать стоимость компоненты на основе комплектующих #####

procedure TF_AddComponent.SetCalcPrice;
var
  CurrRecNo: Integer;
  PriceWithNDS: Double; // Цена без НДС в главной валюте

  function GetPriceFromStr(StrPrice: string): Double;
  var
    Str: string;
    Len: Integer;
    i: Integer;
  begin
    Result := 0;
    Str := StrPrice;
    Len := Length(StrPrice);
    for i := 1 to Len do
      if StrPrice[i] = ' ' then
      begin
        SetLength(Str, i);
        Break;
      end;
    Result := Round3(StrToFloatU(Str));
  end;

begin
  if TF_Main(GForm).DM.MemTable_ComplectsEd.RecordCount > 0 then // Tolik 28/12/2019 --
  begin
    with TF_Main(GForm).DM.MemTable_ComplectsEd do
    begin
      CurrRecNo := RecNo;
      PriceWithNDS := 0;
      First;
      while not Eof do
      begin
        PriceWithNDS := PriceWithNDS +
          GetPriceFromStr(FieldByName('Cost1').AsString);
        TF_Main(GForm).DM.MemTable_ComplectsEd.Next;
      end;
      RecNo := CurrRecNo;
    end;
  end;

  //case RadioGroup_HasNds.ItemIndex of
  //  // Втом числе с НДС - Да
  //  0 : CurrencyEdit_Price1.Value := RoundX(PriceWithNDS, 2);
  //  // Втом числе с НДС - Да
  //  1 : CurrencyEdit_Price1.Value := RoundX(
  //                                   PriceWithoutNDS(PriceWithNDS, GNDS), 2);
  //end;

  case CheckBox_HasNds.Checked of
    // Втом числе с НДС - Да
    true: CurrencyEdit_Price1.Value := Round3(PriceWithNDS);
    // Втом числе с НДС - Да
    false: CurrencyEdit_Price1.Value := Round3(PriceWithoutNDS(PriceWithNDS, TF_Main(GForm).GNDS));
  end;
  //CurrencyEdit_Price2.Value := Round3(CurrencyEdit_Price1.Value * (TF_Main(GForm).GLocalCurrencyM.Data.Ratio / TF_Main(GForm).GLocalCurrencyS.Data.Ratio));
  CurrencyEdit_Price2.Value := Round3(GetPriceAfterChangeCurrency(CurrencyEdit_Price1.Value,
    TF_Main(GForm).GLocalCurrencyM.Data, TF_Main(GForm).GLocalCurrencyS.Data));

  //ShowNDSPrice;
end;

procedure TF_AddComponent.RefreshFields(ATarget: TkbmMemTable;
  ASTableName, ATargetKeyName, ASourceKeyName: string; AFieldsNames: TStringList);
var
  TRecNo: Integer;
  FNamesCount: Integer;
  i: Integer;
begin
  try
    if ATarget.Active = false then
      Exit; //// EXIT ////

    if TF_Main(GForm).FNormBase = GForm then
    begin
      FNamesCount := AFieldsNames.Count;
      if ATarget.RecordCount > 0 then // Tolik 28/12/2019 --
      begin
        TRecNo := ATarget.RecNo;
        try
          ATarget.First;
          while not ATarget.Eof do
          begin
            SetSQLToQuery(F_NormBase.DM.scsQ, ' SELECT * FROM ' + ASTableName +
              ' WHERE ' + ASourceKeyName + ' = ' + IntToStr(ATarget.FieldByName(ATargetKeyName).AsInteger));
            ATarget.Edit;
            for i := 0 to FNamesCount - 1 do
              ATarget.FieldByName(AFieldsNames.Strings[i]).Value := F_NormBase.DM.scsQ.GetFNAsVariant(AFieldsNames.Strings[i]);
            ATarget.Post;

            ATarget.Next;
          end;
        finally
          ATarget.RecNo := TRecNo;
          if ATarget.RecNo <> TRecNo then
            ATarget.RecNo := TRecNo;
        end;
      end;
    end;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.RefreshFields: ' + E.Message);
  end;
end;

procedure TF_AddComponent.GridEnter(Sender: TObject);
begin
  //Act_Del.ShortCut := ShortCut(VK_DELETE, []);
end;

procedure TF_AddComponent.GridExit(Sender: TObject);
begin
  //Act_Del.ShortCut := ShortCut(VK_NONAME, []);
end;

procedure TF_AddComponent.FormHide(Sender: TObject);
begin
  // ##### При Следующем вsзове, Отображать эту форму в средине Главной #####
  //Position := poMainFormCenter;
end;

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

function TF_AddComponent.GetMainformName: string;
begin
  case TF_Main(GForm).GDBMode of
    bkNormBase: Result := cAddComponent_Msg11_1;
    bkProjectManager: Result := cAddComponent_Msg11_2;
  end;
end;

procedure TF_AddComponent.GT_InterfaceGenderGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: string);
begin
  if AText = '0' then
    AText := cAddComponent_Msg12_1;

  if AText = '1' then
    AText := cAddComponent_Msg12_2;
end;

procedure TF_AddComponent.EnableControl(AEnable: Boolean);
begin
  {GroupBox_MainData.Enabled := AEnable;
  GroupBox_NetType.Enabled := AEnable;
  GroupBox_Price.Enabled := AEnable;
  RadioGroup_CanComplect.Enabled := AEnable;
  ColorEdit.Enabled := AEnable;
  Label_CanComplect.Enabled := AEnable;}

  {Panel_MainData.Enabled := AEnable;
  ToolBar_OtherData.Enabled := AEnable;
  Label_Default.Visible := AEnable;}

  //Label_ArticulDistributor.Enabled := AEnable;
  //Edit_ArticulDistributor.Enabled := AEnable;
  //Label_ArticulProducer.Enabled := AEnable;
  //Edit_ArticulProducer.Enabled := AEnable;

  //Label_ComponentType.Enabled := AEnable;
  ComboBox_ComponentType.Enabled := AEnable;
  Button_TypeComponent.Enabled := AEnable;

  //Label_Producer.Enabled := AEnable;
  //ComboBox_Producer.Enabled := AEnable;

  //Label_NetType.Enabled := AEnable;
  //ComboBox_NetType.Enabled := AEnable;
  //Button_ChangeNetType.Enabled := AEnable;

  //Button_OpenCompIcons.Enabled := AEnable;

  //RadioGroup_CanComplect.Enabled := AEnable;
  cbCanComplect.Enabled := AEnable;

  //Act_EditProperty.Enabled := AEnable;
  //Act_DelProperty.Enabled := AEnable;
end;

procedure TF_AddComponent.SetVisibleByIsLine(AIsLineType: Integer);
var
  ShowUserLength: Boolean;
begin
  ShowUserLength := false;
  if AIsLineType = biTrue then
    if TF_Main(GForm).GDBMode = bkProjectManager then
      ShowUserLength := true;
  Label_UserLength.Visible := ShowUserLength;
  SpinEdit_UserLength.Visible := ShowUserLength;

  {//14.05.2009
  case AIsLineType of
    biFalse:
      begin
        //Label_ObjectIconStep.Visible := false;
        //SpinEdit_ObjectIconStep.Visible := false;

        GL_PORT.Visible := true;
      end;
    biTrue:
      begin
        //Label_ObjectIconStep.Visible := true;
        //SpinEdit_ObjectIconStep.Visible := true;

        GL_PORT.Visible := false;
      end;
  end;}

  GL_PORT.Visible := (GUseVisibleInterfaces) and (AIsLineType = biFalse);
end;

procedure TF_AddComponent.VisibleInterfaceColumns(AVisible: Boolean);
begin
  //GT_INTERFACEMultiple.Visible := AVisible;
  //GT_InterfaceValueI.Visible := AVisible;
  GT_InterfaceNumPairsStr.Visible := AVisible;
  //GT_InterfaceColor.Visible := AVisible;
  GT_InterfaceSide.Visible := AVisible;
  GT_NORMSExpenseForLength.Visible := AVisible;
  GT_NORMSCountForPoint.Visible := AVisible;
  GT_NORMSStepOfPoint.Visible := AVisible;
  GT_NORMSTotalKolvo.Visible := AVisible;
end;

function TF_AddComponent.GetPropertyBySysName(ASysyName: string): string;
var
  RecNo: Integer;
  i: Integer;
begin
  Result := '';
  // Tolik 28/12/2019 --
  if TF_Main(GForm).DM.MemTable_PropertyEd.RecordCount = 0 then
    exit;
  //
  with TF_Main(GForm).DM do
  begin
    RecNo := MemTable_PropertyEd.RecNo;
    MemTable_PropertyEd.DisableControls;
    try
      for i := 0 to MemTable_PropertyEd.RecordCount - 1 do
      begin
        MemTable_PropertyEd.RecNo := i + 1;
        if MemTable_PropertyEd.FieldByName(fnSysName).AsString = ASysyName then
        begin
          Result := MemTable_PropertyEd.FieldByName(fnPValue).AsString;
          Break; ///// BREAK /////
        end;
      end;
    finally
      MemTable_PropertyEd.RecNo := RecNo;
      MemTable_PropertyEd.EnableControls;
    end;
  end;
end;

function TF_AddComponent.GetPropertyBySysNameAsFloat(ASysyName: string): Double;
var
  StrRes: string;
begin
  Result := 0;
  StrRes := GetPropertyBySysName(ASysyName);
  if StrRes <> '' then
    Result := StrToFloatU(StrRes);
end;

// ##### Прверяет Соединен ли интерфейс с каким то другим интерфейсом #####

function TF_AddComponent.isBusyInterface: Boolean;
begin
  result := false;
  with TF_Main(GForm).DM.MemTable_InterfOfInterf_RelEd do
  begin
    First;
    while not Eof do
    begin
      if FieldByName('isBusy').AsBoolean = true then
      begin
        Result := true;
        First;
        Break;
      end;
      Next;
    end;
  end;
end;

procedure TF_AddComponent.SetPropertyValueBySysName(ASysyName, AValue: string);
var
  RecNo: Integer;
  i: Integer;
begin
  // Tolik 28/12/2019 --
  if TF_Main(GForm).DM.MemTable_PropertyEd.RecordCount = 0 then
    exit;
  //
  with TF_Main(GForm).DM do
  begin
    RecNo := MemTable_PropertyEd.RecNo;
    MemTable_PropertyEd.DisableControls;
    try
      for i := 0 to MemTable_PropertyEd.RecordCount - 1 do
      begin
        MemTable_PropertyEd.RecNo := i + 1;
        if MemTable_PropertyEd.FieldByName(fnSysName).AsString = ASysyName then
        begin
          MemTable_PropertyEd.Edit;
          MemTable_PropertyEd.FieldByName(fnPValue).AsString := AValue;
          MemTable_PropertyEd.FieldByName(fnIsModified).AsBoolean := true;
          MemTable_PropertyEd.Post;
          Break; ///// BREAK /////
        end;
      end;
    finally
      MemTable_PropertyEd.RecNo := RecNo;
      MemTable_PropertyEd.EnableControls;
    end;
  end;
end;

procedure TF_AddComponent.SetPropertyValueBySysNameAsFloat(ASysyName: string; AValue: Double);
begin
  SetPropertyValueBySysName(ASysyName, FloatToStrU(AValue));
end;

//Procedure AddPropertyToNBCompon(aProp: PProperty); // Tolik 05/03/2021 --
Procedure TF_AddComponent.AddPropertyToNBCompon(aProp: TNBProperty; aValue: string); // Tolik 05/03/2021 --
var FieldsNames: TStringList;
    Prop: TProperty;
begin
  //if TF_Main(GForm).GDBMode = bkNormBase then
  ZeroMemory(@Prop, sizeof(TProperty));
  begin
    if F_NormBase.GSCSBase.SCSComponent <> nil then
    begin
      F_NormBase.DM.MemTable_PropertyEd.DisableControls;

      Prop.Guid := aProp.PropertyData.GUID;
      Prop.IDMaster := F_NormBase.GSCSBase.SCSComponent.ID;
      Prop.ID_Property := aProp.PropertyData.ID;
      Prop.IDDataType := aProp.PropertyData.IDDataType;
      Prop.SysName := aProp.PropertyData.SysName;
      Prop.Value := aValue;
      Prop.Name_ := aProp.PropertyData.Name;
      Prop.IsForWholeComponent := 1;
      Prop.IsNew := True;
      F_NormBase.DM.MemTable_PropertyEd.Append;
      Prop.ID := GenNewID(tkCompPropRelED);
      if F_NormBase.DM.MemTable_PropertyEd.State <> dsBrowse then
      begin
        F_NormBase.DM.SetPropertyToTable(F_NormBase.DM.DataSource_MT_PropertyEd, Prop);
        F_NormBase.DM.MemTable_PropertyEd.Post;
      end;

      {F_NormBase.DM.MemTable_PropertyEd.Edit;
      F_NormBase.DM.MemTable_PropertyEd.Last;
      F_NormBase.DM.MemTable_PropertyEd.Append;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIDMaster).AsInteger := F_NormBase.GSCSBase.SCSComponent.ID;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnGuidProperty).AsString := aProp.PropertyData.GUID;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIDProperty).AsInteger := aProp.PropertyData.ID;
      //F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnTakeIntoConnect).AsInteger := aProp.PropertyData.
      //F_NormBase.DM.MemTable_PropertyEdd.FieldByName(fnTakeIntoJoin, ftInteger);
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIDDataType).asinteger := aProp.PropertyData.IDDataType;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnName).AsString := aProp.PropertyData.Name;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnSysName).AsString := aProp.PropertyData.SysName;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnPValue).AsString := aValue;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIzm).AsString := aProp.PropertyData.Izm;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnDescription).AsString := aProp.PropertyData.Description;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnisStandart).AsInteger := aProp.PropertyData.IsStandart;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIsTakeJoinForPoints).AsInteger := 0;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIsCrossControl).AsInteger := 0;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnGuidCrossProperty).AsString := '';
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIDCrossProperty).AsInteger := 0;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIsForWholeComponent).AsInteger := 1;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIsDefault).AsInteger := 0;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnisModified).AsBoolean := False;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnisNew).AsBoolean := False;
      {F_NormBase.DM.MemTable_PropertyEd.DisableControls;
      F_NormBase.DM.MemTable_PropertyEd.Edit;
      F_NormBase.DM.MemTable_PropertyEd.Last;
      F_NormBase.DM.MemTable_PropertyEd.Append;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIDMaster).AsInteger := F_NormBase.GSCSBase.SCSComponent.ID;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnGuidProperty).AsString := aProp.PropertyData.GUID;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIDProperty).AsInteger := aProp.PropertyData.ID;
      //F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnTakeIntoConnect).AsInteger := aProp.PropertyData.
      //F_NormBase.DM.MemTable_PropertyEdd.FieldByName(fnTakeIntoJoin, ftInteger);
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIDDataType).asinteger := aProp.PropertyData.IDDataType;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnName).AsString := aProp.PropertyData.Name;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnSysName).AsString := aProp.PropertyData.SysName;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnPValue).AsString := aValue;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIzm).AsString := aProp.PropertyData.Izm;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnDescription).AsString := aProp.PropertyData.Description;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnisStandart).AsInteger := aProp.PropertyData.IsStandart;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIsTakeJoinForPoints).AsInteger := 0;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIsCrossControl).AsInteger := 0;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnGuidCrossProperty).AsString := '';
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIDCrossProperty).AsInteger := 0;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIsForWholeComponent).AsInteger := 1;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnIsDefault).AsInteger := 0;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnisModified).AsBoolean := False;
      F_NormBase.DM.MemTable_PropertyEd.FieldByName(fnisNew).AsBoolean := False;
      F_NormBase.DM.MemTable_PropertyEd.Post;
      F_NormBase.DM.MemTable_PropertyEd.Refresh;
      }
      FieldsNames := TStringList.Create;
      try
        FieldsNames.Clear;
        FieldsNames.Add(fnName);
        FieldsNames.Add(fnSysName);
        FieldsNames.Add(fnName);
        FieldsNames.Add(fnIzm);
        FieldsNames.Add(fnDescription);
        FieldsNames.Add(fnIDDataType);
        RefreshFields(F_NormBase.DM.MemTable_PropertyEd, tnProperties, fnIDProperty, fnID, FieldsNames);
      finally
        FreeAndNil(FieldsNames);
        F_NormBase.DM.MemTable_PropertyEd.EnableControls;
      end;
    end;
  end;
end;

procedure TF_AddComponent.SdvigNppPortAfterDel(ADelNPPPort: Integer);
var
  RecNo: Integer;
  MemTable_PortED: TkbmMemTable;
  CurrNppPort: Integer;
begin
  try
    MemTable_PortED := nil;
    RecNo := -1;
    if TF_Main(GForm).GDBMode <> bkProjectManager then
      Exit; //// EXIT ////

    MemTable_PortED := TF_Main(GForm).DM.MemTable_PortEd;
    if MemTable_PortED <> nil then
    begin
      RecNo := MemTable_PortED.RecNo;
      MemTable_PortED.DisableControls;
      //GT_PORT.BeginUpdate;
      if MemTable_PortED.RecordCount > 0 then // Tolik 28/12/2019 --
      begin
        try
          MemTable_PortED.First;
          while not MemTable_PortED.Eof do
          begin
            CurrNppPort := MemTable_PortED.FieldByName('Npp_Port').AsInteger;
            if MemTable_PortED.FieldByName('isUser_Port').AsInteger = biFalse then
              //if MemTable_PortED.FieldByName('isNew').AsBoolean = True then
              if CurrNppPort > ADelNPPPort then
              begin
                MemTable_PortED.Edit;
                MemTable_PortED.FieldByName('Npp_Port').AsInteger := CurrNppPort - 1;
                MemTable_PortED.Post;
              end;
            MemTable_PortED.Next;
          end;
        finally
          MemTable_PortED.RecNo := RecNo;
          MemTable_PortED.EnableControls;
          //GT_PORT.EndUpdate;
        end;
      end;
    end;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.SdvigNppPortAfterDel: ' + E.Message);
  end;
end;

// ##### Добавляет интерфейс/порт #####

procedure TF_AddComponent.AddInterfacePort(AIsPort: Integer);
var
  MemTable_InterfOrPort: TkbmMemTable;
  FieldsNames: TStringList;
  //i: Integer;
  meInterfaceRel: TmeInterfaceRel;
  ComponentType: TComponentType;
begin
  try
    FieldsNames := nil;
    MemTable_InterfOrPort := nil;
    if (GFormMode = fmView) or (GFormMode = fmDisabled) then
      Exit; //// EXIT ////

    ZeroMemory(@meInterfaceRel, SizeOf(TmeInterfaceRel));
    case AIsPort of
      biTrue:
        MemTable_InterfOrPort := TF_Main(GForm).DM.MemTable_PortEd;
      biFalse:
        MemTable_InterfOrPort := TF_Main(GForm).DM.MemTable_InterfaceRelEd;
    end;

    if MemTable_InterfOrPort <> nil then
    begin
      //if ComboBox_ComponentType.Text <> '' then
      //  ComponentType := TF_Main(GForm).FNormBase.DM.GetComponentType(GetIDFromComboBox(ComboBox_ComponentType))
      //else
      //  ComponentType.IsLine := biFalse;
      ComponentType := GetComponentType;

      meInterfaceRel.ID := GGenLastInterfID + 1;
      meInterfaceRel.ID_COMPONENT := GIDComponent;
      meInterfaceRel.IsLineCompon := ComponentType.IsLine;
      meInterfaceRel.IsPort := AIsPort;
      //if meInterfaceRel.IsPort = biTrue then
      begin
        meInterfaceRel.mtInterfaces := TF_Main(GForm).DM.MemTable_InterfaceRelEd;
        meInterfaceRel.mtPorts := TF_Main(GForm).DM.MemTable_PortEd;
        meInterfaceRel.mtPortInterfRel := TF_Main(GForm).DM.MemTable_PortInterfRelEd;
        meInterfaceRel.ServiceShowApplyForAllNoRelPorts := true;
      end;
      meInterfaceRel.mtInterfInternalConnect := TF_Main(GForm).DM.mtInterfInternalConnEd;
      F_NormBase.F_CaseForm.GUseMemTable := MemTable_InterfOrPort; //TF_Main(GForm).DM.MemTable_InterfaceRelEd;
      if TF_Main(GForm).CreateFAddInterface.GetInterfRel(meInterfaceRel, fmMake) then
      begin
        meInterfaceRel.NAME := TF_Main(GForm).F_AddInterface.ComboBox_Name.Text;
        AddInterfaceToMT(meInterfaceRel);
        if meInterfaceRel.ServiceApplyForAllNoRelPorts then
          DefineAllPortInterfRelNames;
      end;
      F_NormBase.F_CaseForm.GUseMemTable := nil;

      if (AIsPort = biTrue) and (not meInterfaceRel.ServiceApplyForAllNoRelPorts) then
        DefineCurrPortInterfRelNames(true);

      FieldsNames := TStringList.Create;
      try
        FieldsNames.Clear;
        FieldsNames.Add('Name');

        TF_Main(GForm).DM.MemTable_InterfaceRelEd.DisableControls;
        TF_Main(GForm).DM.MemTable_PortEd.DisableControls;
        try
          RefreshFields(TF_Main(GForm).DM.MemTable_InterfaceRelEd, 'INTERFACE', 'ID_Interface', 'ID', FieldsNames);
          RefreshFields(TF_Main(GForm).DM.MemTable_PortEd, 'INTERFACE', 'ID_Interface', 'ID', FieldsNames);
        finally
          TF_Main(GForm).DM.MemTable_InterfaceRelEd.EnableControls;
          TF_Main(GForm).DM.MemTable_PortEd.EnableControls;
        end;
      finally
        FreeAndNil(FieldsNames);
      end;
    end;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.AddInterfacePort: ' + E.Message);
  end;
end;

// ##### Редактирует интерфейс/порт #####

procedure TF_AddComponent.EditInterfacePort(AIsPort: Integer);
var
  MemTable_InterfOrPort: TkbmMemTable;
  DataSource_InterfOrPort: TDataSource;

  FieldsNames: TStringList;
  meInterfaceRel: TmeInterfaceRel;
  EditId: Integer;
  //ID_Adverse: Integer;
  NumPair: Integer;
  RecNo: Integer;
  //BookmarkStr: String;
  BookmarkStr: TBookMark;
  ComponentType: TComponentType;
  ReadOnlyMode: Boolean;
begin
  try
    FieldsNames := nil;
    MemTable_InterfOrPort := nil;
    DataSource_InterfOrPort := nil;

    case AIsPort of
      biTrue:
        begin
          MemTable_InterfOrPort := TF_Main(GForm).DM.MemTable_PortEd;
          DataSource_InterfOrPort := TF_Main(GForm).DM.DataSource_MT_PortEd;
        end;
      biFalse:
        begin
          MemTable_InterfOrPort := TF_Main(GForm).DM.MemTable_InterfaceRelEd;
          DataSource_InterfOrPort := TF_Main(GForm).DM.DataSource_MT_INTERFACERelEd;
        end;
    end;

    if (MemTable_InterfOrPort <> nil) and (DataSource_InterfOrPort <> nil) then
    begin
      EditID := MemTable_InterfOrPort.FieldByName('ID').AsInteger;
      NumPair := 0;
      if AIsPort = biFalse then
        NumPair := MemTable_InterfOrPort.FieldByName('Num_Pair').AsInteger;
      RecNo := -1;
      //BookmarkStr := '';
      BookmarkStr := nil;

      if (GFormMode = fmView) or (GFormMode = fmDisabled) then
        Exit; ///// EXIT /////

      ReadOnlyMode := false;
      if MemTable_InterfOrPort.FieldByName('isNew').AsBoolean = false then
        if IsUseInterfRelInMemTable(GForm, MemTable_InterfOrPort, meEdit, false) then
          ReadOnlyMode := true; //Exit; ///// EXIT /////
      if MemTable_InterfOrPort.FieldByName('isBusy').AsInteger = biTrue then
      begin
        //MessageModal('Интерфейс занят', 'Редактирование интерфейса', MB_ICONINFORMATION or MB_OK);
        ReadOnlyMode := true; //Exit; ///// EXIT /////
      end;
      //*** Не редаактировать используемый портом интерфейс
      if AIsPort = biFalse then
        if IsUseInterfRelInPortInterfRels(TF_Main(GForm).DM.MemTable_InterfaceRelEd, TF_Main(GForm).DM.MemTable_PortInterfRelEd, meEdit, false) then
          ReadOnlyMode := true; //Exit; ///// EXIT /////

      if ReadOnlyMode then
        MessageModal(CReadOnlyInterface, ApplicationName, MB_ICONINFORMATION or MB_OK);

      //if ComboBox_ComponentType.Text <> '' then
      //  ComponentType := TF_Main(GForm).FNormBase.DM.GetComponentType(GetIDFromComboBox(ComboBox_ComponentType))
      //else
      //  ComponentType.IsLine := biFalse;
      ComponentType := GetComponentType;

      meInterfaceRel := TF_Main(GForm).DM.GetInterfaceRel(DataSource_InterfOrPort, nil);
      meInterfaceRel.IsPort := AIsPort;
      meInterfaceRel.IsLineCompon := ComponentType.IsLine;
      if meInterfaceRel.IsPort = biTrue then
      begin
        meInterfaceRel.mtPorts := TF_Main(GForm).DM.MemTable_PortEd;
        meInterfaceRel.mtPortInterfRel := TF_Main(GForm).DM.MemTable_PortInterfRelEd;
        meInterfaceRel.ServiceShowApplyForAllNoRelPorts := true;
      end;
      meInterfaceRel.mtInterfaces := TF_Main(GForm).DM.MemTable_InterfaceRelEd;
      meInterfaceRel.mtInterfInternalConnect := TF_Main(GForm).DM.mtInterfInternalConnEd;
      F_NormBase.F_CaseForm.GUseMemTable := MemTable_InterfOrPort;
      if TF_Main(GForm).CreateFAddInterface.GetInterfRel(meInterfaceRel, fmEdit, ReadOnlyMode) then
      begin
        meInterfaceRel.ID_COMPONENT := GIDComponent; //TF_Main(GForm).GSCSBase.SCSComponent.ID;
        RecNo := MemTable_InterfOrPort.RecNo;
        //BookmarkStr := MemTable_InterfOrPort.Bookmark;
        BookmarkStr := MemTable_InterfOrPort.GetBookmark;
        with MemTable_InterfOrPort do
        begin
          Edit;
          FieldByName('Name').AsString := meInterfaceRel.Name;
          FieldByName('TypeI').AsInteger := meInterfaceRel.Typei;
          FieldByName('Kind').AsInteger := meInterfaceRel.Kind;
          FieldByName('Gender').AsInteger := meInterfaceRel.Gender;
          FieldByName('Multiple').AsInteger := meInterfaceRel.Multiple;
          FieldByName('ID_Interface').AsInteger := meInterfaceRel.ID_INTERFACE;
          FieldByName(fnGuidInterface).AsString := meInterfaceRel.GUIDInterface;
          FieldByName(fnNpp).AsInteger := meInterfaceRel.Npp;
          if AIsPort = biFalse then
          begin
            FieldByName('ValueI').AsFloat := meInterfaceRel.ValueI;
            if meInterfaceRel.ID_Adverse = 0 then
              FieldByName(fnSide).AsInteger := meInterfaceRel.Side;
          end
          else
          begin
            FieldByName(fnNppPort).AsInteger := meInterfaceRel.NppPort;
            FieldByName(fnIsUserPort).AsInteger := meInterfaceRel.IsUserPort;
          end;
          FieldByName('Color').AsFloat := meInterfaceRel.Color;
          FieldByName(fnNotice).AsString := meInterfaceRel.Notice;
          FieldByName(fnKolvo).AsInteger := meInterfaceRel.Kolvo;
          FieldByName(fnSignType).AsInteger := meInterfaceRel.SignType;
          FieldByName(fnConnToAnyGender).AsInteger := meInterfaceRel.ConnToAnyGender;
          FieldByName(fnSideSection).AsString := meInterfaceRel.SideSection;
          FieldByName('isModified').AsBoolean := true;
          Post;

          if meInterfaceRel.ID_Adverse <> 0 then
            if ComponentType.IsLine = biTrue then
              if SearchRecordMT(MemTable_InterfOrPort, 'id', meInterfaceRel.ID_Adverse) then
              begin
                Edit;
                FieldByName('Name').AsString := meInterfaceRel.Name;
                FieldByName('TypeI').AsInteger := meInterfaceRel.Typei;
                FieldByName('Kind').AsInteger := meInterfaceRel.Kind;
                FieldByName('Gender').AsInteger := meInterfaceRel.Gender;
                FieldByName('Multiple').AsInteger := meInterfaceRel.Multiple;
                FieldByName('ID_Interface').AsInteger := meInterfaceRel.ID_INTERFACE;
                FieldByName(fnGuidInterface).AsString := meInterfaceRel.GUIDInterface;
                FieldByName(fnNpp).AsInteger := meInterfaceRel.Npp;
                FieldByName('ValueI').AsFloat := meInterfaceRel.ValueI;
                if AIsPort = biFalse then
                  if meInterfaceRel.ID_Adverse = 0 then
                    FieldByName(fnSide).AsInteger := meInterfaceRel.Side;
                FieldByName('Color').AsFloat := meInterfaceRel.Color;
                FieldByName(fnNotice).AsString := meInterfaceRel.Notice;
                FieldByName(fnKolvo).AsInteger := meInterfaceRel.Kolvo;
                FieldByName(fnSignType).AsInteger := meInterfaceRel.SignType;
                FieldByName(fnConnToAnyGender).AsInteger := meInterfaceRel.ConnToAnyGender;
                FieldByName(fnSideSection).AsString := meInterfaceRel.SideSection;
                FieldByName('isModified').AsBoolean := true;
                Post;

                //*** Вернуться назад
                //SearchRecordMT(TF_Main(GForm).DM.MemTable_InterfaceRelEd, 'id', meInterfaceRel.ID);
              end;
          GChangedInterface := true;
        end;

        //if AIsPort = biTrue then ##ISPORT
          //GDeletedPortInterfRels.AddStrings(TF_Main(GForm).F_AddInterface.GDeletedPortInterfRels);
        GDeletedPortInterfRels.Assign(TF_Main(GForm).F_AddInterface.GDeletedPortInterfRelIDs, laOR);

        if meInterfaceRel.ServiceApplyForAllNoRelPorts then
          DefineAllPortInterfRelNames;

        if meInterfaceRel.TYPEI = itFunctional then
          ShowMessageAboutCheckCableCanalElemnts(Edit_Name.Text, TF_MAIN(GForm).DM.MemTable_CableCanalConnectorsEd.RecordCount);
      end;
      F_NormBase.F_CaseForm.GUseMemTable := nil;

      if (AIsPort = biTrue) and (meInterfaceRel.ServiceApplyForAllNoRelPorts = false) then
        DefineCurrPortInterfRelNames(true);

      {TF_Main(GForm).F_AddInterface.GFormMode := fmEdit;
      TF_Main(GForm).F_AddInterface.GID_Interface := TF_Main(GForm).DM.MemTable_Interface.FieldByName('ID_Interface').AsInteger;
      TF_Main(GForm).F_AddInterface.GKolvo := TF_Main(GForm).DM.MemTable_Interface.FieldByName('Kolvo').AsInteger;
      TF_Main(GForm).F_AddInterface.GTypeInterface := TF_Main(GForm).DM.MemTable_Interface.FieldByName('TypeI').AsInteger;

      with TF_Main(GForm).DM.MemTable_Interface do
        begin
          if TF_Main(GForm).F_AddInterface.ShowModal = mrOK then
            begin
                Edit;
                FieldByName('Name').AsString := TF_Main(GForm).F_AddInterface.ComboBox_Name.Text;
                FieldByName('TypeI').AsInteger := TF_Main(GForm).F_AddInterface.ComboBox_Type_I.ItemIndex;
                FieldByName('Gender').AsInteger := 1 - TF_Main(GForm).F_AddInterface.RadioGroup_Gender.ItemIndex;
                FieldByName('ID_Interface').AsInteger := TF_Main(GForm).F_AddInterface.GID_INTERFACE;
                FieldByName('Kolvo').AsInteger := TF_Main(GForm).F_AddInterface.SpinEdit_Kolvo.Value;
                FieldByName('isModified').AsBoolean := true;
                Post;
            end;

            GChangedInterface := true;
          end;         }
      //GT_Interface.DataController.DataSource := TF_Main(GForm).DM.DataSource_MT_INTERFACE;

      // Обновить данные
      FieldsNames := TStringList.Create;
      try
        FieldsNames.Clear;
        FieldsNames.Add('Name');
        TF_Main(GForm).DM.MemTable_InterfaceRelEd.DisableControls;
        TF_Main(GForm).DM.MemTable_PortEd.DisableControls;
        try
          RefreshFields(TF_Main(GForm).DM.MemTable_InterfaceRelEd, 'INTERFACE', 'ID_Interface', 'ID', FieldsNames);
          RefreshFields(TF_Main(GForm).DM.MemTable_PortEd, 'INTERFACE', 'ID_Interface', 'ID', FieldsNames);
        finally
          TF_Main(GForm).DM.MemTable_InterfaceRelEd.EnableControls;
          TF_Main(GForm).DM.MemTable_PortEd.EnableControls;
        end;
      finally
        FreeAndNil(FieldsNames);
        //if RecNo <> -1 then
        //begin
        //  MemTable_InterfOrPort.First;
        //  MemTable_InterfOrPort.RecNo := RecNo;
        //end;
        {if BookmarkStr <> '' then
          MemTable_InterfOrPort.Bookmark := BookmarkStr;}
        if BookmarkStr <>nil then
        begin
          MemTable_InterfOrPort.GotoBookmark(BookmarkStr);
          MemTable_InterfOrPort.FreeBookmark(BookmarkStr);
        end;

      end;
    end;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.Act_EditInterfaceExecute: ' + E.Message);
  end;
end;

procedure TF_AddComponent.DelAllInterfacesPorts(AIsPort: Boolean);
var
  MemTable: TkbmMemTable;
  strQuast: String;
begin
  try
    MemTable := nil;
    strQuast := '';
    if AIsPort then
    begin
      MemTable := TF_Main(GForm).DM.MemTable_PortEd;
      strQuast := cAddComponent_Msg19_1;
    end
    else
    begin
      MemTable := TF_Main(GForm).DM.MemTable_InterfaceRelEd;
      strQuast := cAddComponent_Msg19_2;
    end;

    if MessageModal(strQuast, ApplicationName, MB_ICONQUESTION or MB_YESNO) = IDYES then
    begin
      ClearPortInterfaceMemTable(MemTable, AIsPort);
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.DelAllInterfacesPorts', E.Message);
  end;
end;

procedure TF_AddComponent.DelAllProperties;
begin
  try
    if MessageModal(cAddComponent_Msg19_3, ApplicationName, MB_ICONQUESTION or MB_YESNO) = IDYES then
    begin
      //*** Установить Свойства как удаленные
      SetAsDeletedMTRecords(TF_Main(GForm).DM.MemTable_PropertyEd, nil, GDeletedPropRel, nil);

      TF_Main(GForm).DM.MemTable_PropertyEd.Active := false;
      TF_Main(GForm).DM.MemTable_PropertyEd.Active := true;
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.DelAllProperties', E.Message);
  end;
end;

procedure TF_AddComponent.DelAllCableCanalConnectors;
begin
  try
    if MessageModal(cAddComponent_Msg19_4, ApplicationName, MB_ICONQUESTION or MB_YESNO) = IDYES then
    begin
      //*** Установить Свойства как удаленные
      SetAsDeletedMTRecords(TF_Main(GForm).DM.MemTable_CableCanalConnectorsEd, nil, GDeletedCableCanalConnectors, nil);

      TF_Main(GForm).DM.MemTable_CableCanalConnectorsEd.Active := false;
      TF_Main(GForm).DM.MemTable_CableCanalConnectorsEd.Active := true;
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.DelAllCableCanalConnectors', E.Message);
  end;
end;

procedure TF_AddComponent.DelAllCrossConnections;
begin
  try
    if MessageModal(cAddComponent_Msg19_5, ApplicationName, MB_ICONQUESTION or MB_YESNO) = IDYES then
    begin
      //*** Установить Свойства как удаленные
      SetAsDeletedMTRecords(TF_Main(GForm).DM.mtCrossConnectionEd, nil, GDeletedCrossConnections, nil);

      TF_Main(GForm).DM.mtCrossConnectionEd.Active := false;
      TF_Main(GForm).DM.mtCrossConnectionEd.Active := true;
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.DelAllCrossConnections', E.Message);
  end;
end;

// ##### Удаляет интерфейс/порт #####
procedure TF_AddComponent.DelInterfacePort(AIsPort: Integer);
var
  MemTable_InterfOrPort: TkbmMemTable;
  SubstanceName: string;
  //DeletedInterfOrPort: TIntList;

  InterfName: string;
  InterfType: Integer;
  DelID: Integer;
  ID_Adverse: Integer;
  NumPair: Integer;
  NppPort: Integer;
  ComponentType: TComponentType;

  DeletedInterfIDs: TIntList;
  InterfRelIDsForKolvo: TIntList;
  InterfRelKolvosForKolvo: TIntList;
begin
  try
    ComponentType := GetComponentType;
    MemTable_InterfOrPort := nil;
    //DeletedInterfOrPort := nil;

    InterfRelIDsForKolvo := nil;
    InterfRelKolvosForKolvo := nil;

    NppPort := -1;
    case AIsPort of
      biTrue:
        begin
          MemTable_InterfOrPort := TF_Main(GForm).DM.MemTable_PortEd;
          SubstanceName := cNamePort;
          //DeletedInterfOrPort := GDeletedPort;
        end;
      biFalse:
        begin
          MemTable_InterfOrPort := TF_Main(GForm).DM.MemTable_InterfaceRelEd;
          SubstanceName := cNameInterface;
          //DeletedInterfOrPort := GDeletedInterfRel;
        end;
    end;

    if (MemTable_InterfOrPort <> nil) {and (DeletedInterfOrPort <> nil)} then
    begin
      DelID := MemTable_InterfOrPort.FieldByName('ID').AsInteger;
      InterfType := MemTable_InterfOrPort.FieldByName(fnTypeI).AsInteger;

      NumPair := 0;
      if AIsPort = biFalse then
        NumPair := MemTable_InterfOrPort.FieldByName('Num_Pair').AsInteger
      else
        NppPort := MemTable_InterfOrPort.FieldByName('Npp_Port').AsInteger;
      if (GFormMode = fmView) or (GFormMode = fmDisabled) then
        Exit; ///// EXIT /////

      if MemTable_InterfOrPort.FieldByName('isNew').AsBoolean = false then
        if IsUseInterfRelInMemTable(GForm, MemTable_InterfOrPort, meDel, true) then
          Exit; ///// EXIT /////
      //*** Если удаляется интерфейс, то проверить, не используется ли он в связях с портами
      if AIsPort = biFalse then
        if IsUseInterfRelInPortInterfRels(TF_Main(GForm).DM.MemTable_InterfaceRelEd, TF_Main(GForm).DM.MemTable_PortInterfRelEd, meDel, true) then
          Exit; ///// EXIT /////

      if MemTable_InterfOrPort.FieldByName('isBusy').AsInteger = biTrue then
      begin
        MessageModal(SubstanceName + ' ' + cBusy, cDeleting + ' ' + SubstanceName + cSufixA, MB_ICONINFORMATION or MB_OK);
        Exit; ///// EXIT /////
      end;

      InterfName := MemTable_InterfOrPort.FieldByName('Name').AsString;
      if MessageModal(cQuastDel + ' ' + SubstanceName + ' "' + InterfName + '" ?',
        cDeleting + ' ' + SubstanceName + cSufixA, MB_YESNO or MB_ICONQUESTION) = mrYES then
      begin
        DeletedInterfIDs := TIntList.Create;
        if AIsPort = biTrue then
        begin
          InterfRelIDsForKolvo := TIntList.Create;
          InterfRelKolvosForKolvo := TIntList.Create;
          //*** Определить количество интерфейсов от количества на порте
          TF_Main(GForm).DM.DefineInterfRelIDsForKolvo(false, InterfRelIDsForKolvo, InterfRelKolvosForKolvo, TF_Main(GForm).DM.MemTable_PortInterfRelEd);
          TF_Main(GForm).DM.DefineInterfacesKolvoByPortKolvo(0,
            TF_Main(GForm).DM.MemTable_PortInterfRelEd, TF_Main(GForm).DM.MemTable_InterfaceRelEd, InterfRelIDsForKolvo, InterfRelKolvosForKolvo);
        end;
        if AIsPort = biFalse then
        begin
          ID_Adverse := MemTable_InterfOrPort.FieldByName('id_Adverse').AsInteger;
          NumPair := MemTable_InterfOrPort.FieldByName('Num_Pair').AsInteger;
        end;

        if MemTable_InterfOrPort.FieldByName(fnIsNative).AsBoolean = true then
        begin
          DeletedInterfIDs.Add(DelID);
          if MemTable_InterfOrPort.FieldByName(fnIsNew).AsBoolean = false then
            GDeletedInterfRel.Add(DelID);
        end;

        MemTable_InterfOrPort.Delete;

        if TF_Main(GForm).GDBMode = bkProjectManager then
          if NppPort <> -1 then
            SdvigNppPortAfterDel(NppPort);

        if NumPair <> 0 then
          if ComponentType.IsLine = biTrue then
            with TF_Main(GForm).DM do
            begin
              MemTable_InterfOrPort.Last;
              while not MemTable_InterfOrPort.Bof do
              begin
                if MemTable_InterfOrPort.FieldByName(fnNumPair).AsInteger = NumPair then
                begin
                  if MemTable_InterfOrPort.FieldByName(fnIsNative).AsBoolean = true then
                  begin
                    DeletedInterfIDs.Add(MemTable_InterfOrPort.FieldByName(fnID).AsInteger);
                    if MemTable_InterfOrPort.FieldByName(fnisNew).AsBoolean = false then
                      GDeletedInterfRel.Add(MemTable_InterfOrPort.FieldByName(fnID).AsInteger);
                  end;
                  //else
                  //  GGenLastInterfID := GGenLastInterfID - 1;
                  MemTable_InterfOrPort.Delete;
                end
                else
                  MemTable_InterfOrPort.Prior;
              end;
              //*** Переопределить номера пар интерфейсов
              TF_Main(GForm).DM.DefineInterfaceNumPairs(MemTable_InterfOrPort, nil);

              {if SearchRecordMT(TF_Main(GForm).DM.MemTable_InterfaceRelEd, 'id', ID_Adverse) then
                begin
                    if TF_Main(GForm).DM.MemTable_InterfaceRelEd.FieldByName('isNew').AsBoolean = false then
                      GDeletedInterfRel.Add(IntToStr(ID_Adverse))
                    else
                      GGenLastInterfID := GGenLastInterfID - 1;
                    TF_Main(GForm).DM.MemTable_InterfaceRelEd.Delete;
                end;   }
            end;
        //*** Очистить междуинтерфейсную связь
        TF_Main(GForm).DM.DeleteInterfInternalConnFromMTByInterfIDs(TF_Main(GForm).DM.mtInterfInternalConnEd, DeletedInterfIDs);

        GChangedInterface := true;
        EnableButtons;

        if InterfType = itFunctional then
          ShowMessageAboutCheckCableCanalElemnts(Edit_Name.Text, TF_MAIN(GForm).DM.MemTable_CableCanalConnectorsEd.RecordCount);

        FreeAndNil(DeletedInterfIDs);
        if InterfRelIDsForKolvo <> nil then
          FreeAndNil(InterfRelIDsForKolvo);
        if InterfRelKolvosForKolvo <> nil then
          FreeAndNil(InterfRelKolvosForKolvo);
      end;
    end;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.DelInterfacePort: ' + E.Message);
  end;
end;

procedure TF_AddComponent.DelPropsBySysNames(ASysNames: TStringList);
var
  //MemTableBookmark: string;
  MemTableBookmark: TBookMark;
  MemTable: TkbmMemTable;
  i: integer;
begin
  try
    MemTable := TF_Main(GForm).DM.MemTable_PropertyEd;

    //MemTableBookmark := MemTable.Bookmark;
    MemTableBookmark := MemTable.GetBookmark;
    MemTable.DisableControls;
    try
      for i := 0 to ASysNames.Count - 1 do
        if MemTable.Locate(fnSysName, ASysNames[i], []) then
        begin
         // if MemTableBookmark = MemTable.Bookmark then
         //   MemTableBookmark := '';
          if Not MemTable.FieldByName(fnIsNew).AsBoolean then
            GDeletedPropRel.Add(MemTable.FieldByName(fnID).AsInteger);
          MemTable.Delete;
        end;
    finally
      MemTable.EnableControls;
      {if MemTableBookmark <> '' then
        MemTable.Bookmark := MemTableBookmark;}
      if MemTableBookmark <> nil then
      begin
        MemTable.GotoBookmark(MemTableBookmark);
        MemTable.FreeBookmark(MemTableBookmark);
      end;
    end;
  except
    on E: Exception do AddExceptionToLogExt(ClassName, 'DelPropsBySysNames', E.Message);
  end;
end;

procedure TF_AddComponent.DefineAllPortInterfRelNames;
var
  PortRecNo: Integer;
begin
  with TF_Main(GForm).DM do
  begin
    if MemTable_PortEd.RecordCount > 0 then // Tolik 28/12/2019 --
    begin
      MemTable_InterfaceRelEd.DisableControls;
      PortRecNo := MemTable_PortEd.RecNo;
      GT_PORT.BeginUpdate;
      try
        MemTable_PortEd.First;
        while not MemTable_PortEd.Eof do
        begin
          DefineCurrPortInterfRelNames(true);
          MemTable_PortEd.Next;
        end;
        MemTable_PortEd.First;
      finally
        GT_PORT.EndUpdate;
        MemTable_PortEd.RecNo := PortRecNo;
        MemTable_InterfaceRelEd.EnableControls;
      end;
    end;
  end;
end;

// #### Определяет наименования связанных интерфейсов ####

procedure TF_AddComponent.DefineCurrPortInterfRelNames(AAutoEditPost: Boolean);
var
  IDInterfaces: TIntList;
  CountInterfaces: TIntList;
  IndexID: Integer;
  CurrCount: Integer;

  NewInterfRelNames: string;
  IDInterface: Integer;
  InterfKolvo: Integer;
  i: Integer;
  InterfRecNo: Integer;
begin
  if TF_Main(GForm).DM.MemTable_InterfaceRelEd.RecordCount = 0 then // Tolik 28/12/2019 --
    exit;
  IDInterfaces := TIntList.Create;
  CountInterfaces := TIntList.Create;
  InterfRecNo := TF_Main(GForm).DM.MemTable_InterfaceRelEd.RecNo;
  TF_Main(GForm).DM.MemTable_InterfaceRelEd.DisableControls;
  try
    //*** Сгруппировать ссылки на интерфейсы
    with TF_Main(GForm).DM do
    begin
      MemTable_PortInterfRelEd.First;
      while not MemTable_PortInterfRelEd.Eof do
      begin
        IDInterface := GetIDInterfaceByIDInterfRelFromMemTable(
          MemTable_PortInterfRelEd.FieldByName(fnIDInterfRel).AsInteger,
          MemTable_InterfaceRelEd, @InterfKolvo);
        if IDInterface > 0 then
        begin
          IndexID := IDInterfaces.IndexOf(IDInterface);
          if IndexID = -1 then
          begin
            IDInterfaces.Add(IDInterface);
            //CountInterfaces.Add(1);
            CountInterfaces.Add(InterfKolvo);
          end
          else
          begin
            CurrCount := CountInterfaces[IndexID];
            //Inc(CurrCount);
            CurrCount := CurrCount + InterfKolvo;
            CountInterfaces[IndexID] := CurrCount;
          end;
        end;
        MemTable_PortInterfRelEd.Next;
      end;

      //*** Создать строку с именами интерфейсов
      NewInterfRelNames := '';
      for i := 0 to IDInterfaces.Count - 1 do
      begin
        if NewInterfRelNames <> '' then
          NewInterfRelNames := NewInterfRelNames + '; ';

        NewInterfRelNames := NewInterfRelNames + F_NormBase.GSCSBase.NBSpravochnik.GetInterfaceNameByID(IDInterfaces[i]);
        if CountInterfaces[i] > 1 then
          NewInterfRelNames := NewInterfRelNames + ' x' + IntToStr(CountInterfaces[i]);
      end;

      if NewInterfRelNames <> MemTable_PortEd.FieldByName(fnInterfRelNames).AsString then
      begin
        if AAutoEditPost then
          MemTable_PortEd.Edit;
        if MemTable_PortEd.State <> dsBrowse then
        begin
          MemTable_PortEd.FieldByName(fnInterfRelNames).AsString := NewInterfRelNames;
          if AAutoEditPost then
            MemTable_PortEd.Post;
        end;
      end;
    end;
  finally
    TF_Main(GForm).DM.MemTable_InterfaceRelEd.RecNo := InterfRecNo;
    TF_Main(GForm).DM.MemTable_InterfaceRelEd.EnableControls;
    IDInterfaces.Free;
    CountInterfaces.Free;
  end;
end;

function TF_AddComponent.GetInterfPortMemTable: TkbmMemTable;
begin
  Result := nil;
  case Grid.ActiveLevel.Index of
    liInterface:
      Result := TF_Main(GForm).DM.MemTable_InterfaceRelEd;
    liPort:
      Result := TF_Main(GForm).DM.MemTable_PortEd;
  end;
end;

procedure TF_AddComponent.AddEditCableCanalConnector(AMakeEdit: TMakeEdit);
var
  FormComponent: TSCSComponent;
  NBComponent: TSCSComponent;
  //InterfCount: Integer;
  ConnectorType: Integer;

  IDCurrConnector: Integer;
begin
  FormComponent := CreateFormComponent;
  if Assigned(FormComponent) then
  begin
    //if FormComponent.ID_Producer < 1 then
    //  ShowMessageByType(Self.Handle, smtDisplay, 'Не задан производитель', Application.Title, MB_OK or MB_ICONINFORMATION)
    //else
    begin
      IDCurrConnector := 0;
      if AMakeEdit = meEdit then
        IDCurrConnector := TF_Main(GForm).DM.MemTable_CableCanalConnectorsEd.FieldByName(fnIDNBConnector).AsInteger;

      NBComponent := TF_Main(GForm).CreateFConnectComplWith.DefineCableCanalConnector(FormComponent, IDCurrConnector);
      if Assigned(NBComponent) then
        with TF_Main(GForm).DM do
        begin
          ConnectorType := -1;
          //InterfCount := NBComponent.GetInterfcesCountByTypeIsBusySide(itFunctional, biFalse, biNone);
          //if InterfCount = 1 then
          //  ConnectorType := contCork;
          //if InterfCount = 2 then
          //  ConnectorType := contAnglePlane;
          //if InterfCount = 3 then
          //  ConnectorType := contTjoin;

          if NBComponent.Properties.Count = 0 then
            NBComponent.LoadProperties;
          ConnectorType := NBComponent.GetPropertyValueAsInteger(pnCableCanalElemetType);
          if ConnectorType <> -1 then
          begin
            if AMakeEdit = meMake then
            begin
              MemTable_CableCanalConnectorsEd.Append;
              MemTable_CableCanalConnectorsEd.FieldByName(fnID).AsInteger := GenNewID(tkCableCanalConnectorsED);
              MemTable_CableCanalConnectorsEd.FieldByName(fnIsNew).AsBoolean := true;
              MemTable_CableCanalConnectorsEd.FieldByName(fnIsModified).AsBoolean := false;
            end;
            if AMakeEdit = meEdit then
            begin
              MemTable_CableCanalConnectorsEd.Edit;
              MemTable_CableCanalConnectorsEd.FieldByName(fnIsModified).AsBoolean := true;
            end;

            MemTable_CableCanalConnectorsEd.FieldByName(fnIDComponent).AsInteger := GIDComponent;
            MemTable_CableCanalConnectorsEd.FieldByName(fnIDNBConnector).AsInteger := NBComponent.ID;
            MemTable_CableCanalConnectorsEd.FieldByName(fnGuidNBConnector).AsString := NBComponent.GuidNB;
            MemTable_CableCanalConnectorsEd.FieldByName(fnConnectorType).AsInteger := ConnectorType;
            MemTable_CableCanalConnectorsEd.FieldByName(fnName).AsString := NBComponent.Name;

            MemTable_CableCanalConnectorsEd.Post;

            FreeAndNil(NBComponent);
          end;
        end;
    end;
    FreeAndNil(FormComponent);
  end;
end;

procedure TF_AddComponent.AddEditCrossConnection(AMakeEdit: TMakeEdit);
var
  CrossConnection: TSCSCrossConnection;
  FormComponent: TSCSComponent;
  MemTable: TkbmMemTable;
begin
  try
    MemTable := TF_Main(GForm).DM.mtCrossConnectionEd;
    CrossConnection := nil;
    if AMakeEdit = meMake then
      CrossConnection := TSCSCrossConnection.Create(GForm) //ZeroMemory(@CrossConnection, SizeOf(TCrossConnection))
    else
    begin
      CrossConnection := TSCSCrossConnection.Create(GForm);
      TF_Main(GForm).DM.LoadCrossConnectionFromMemTable(MemTable, CrossConnection);
    end;
    CrossConnection.IDComponent := GIDComponent;

    FormComponent := CreateFormComponent;
    FormComponent.LoadChildComplectsQuick(true, true, true);
    if TF_Main(GForm).CreateFMakeEditCrossConnection.Execute(AMakeEdit, FormComponent, CrossConnection) then
    begin
      TF_Main(GForm).DM.LoadCrossConnectionToMemTable(AMakeEdit, MemTable, CrossConnection);
    end;
    FreeAndNil(FormComponent);
    FreeAndNil(CrossConnection);
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.AddEditCrossConnection: ' + E.Message);
  end;
end;

procedure TF_AddComponent.AddEditProperty(AMakeEdit: TMakeEdit);
var
  OldValue: String;
  PropFromMT, OldPropFromMT: TProperty;
  FieldsNames: TStringList;
  ComponentType: TComponentType;
  ItemType: Integer;
begin
  ZeroMemory(@PropFromMT, sizeof(TProperty));
  ComponentType := GetComponentType;
  ItemType := itNone;
  ItemType := GetItemTypeByIsLine(GetIsLineByComponType(ComponentType));

  with TF_Main(GForm) do
  begin
    if AMakeEDit = meEdit then
    begin
      PropFromMT := DM.GetPropertyFromTable(DM.DataSource_MT_PropertyEd);
      if GDBMode = bkProjectManager then
        //if not DM.CanEditProperty(DM.MemTable_PropertyEd) then
        //begin
        //  MessageModal(cImpossibleChangeProperty + ' "' + PropFromMT.Name_ + '" ' + cBecauseItUse,
        //    ApplicationName, MB_ICONINFORMATION or MB_OK);
        //  Exit; ///// EXIT /////
        //end;
        if IsReadOnlyProp(ItemType, @PropFromMT) then
        begin
          MessageInfo(cMain_Msg182);
          Exit; ///// EXIT /////
        end;
    end;

    OldValue := PropFromMT.Value;
    OldPropFromMT := PropFromMT;
    if CreateFMakeEditPropRel.Execute(AMakeEdit, tkComponent, @PropFromMT, DM.MemTable_PropertyEd, ItemType, nil, FSpravochnik, TF_Main(GForm).OnCheckPropRelFormValue) then
    begin
      case AMakeEdit of
        meMake:
          begin
            DM.MemTable_PropertyEd.Append;
            PropFromMT.ID := GenNewID(tkCompPropRelED);
            PropFromMT.IsNew := True;
          end;
        meEdit:
          begin
            DM.MemTable_PropertyEd.Edit;
            PropFromMT.IsModified := True;
          end;
      end;
      DM.MemTable_PropertyEd.DisableControls;
      if DM.MemTable_PropertyEd.State <> dsBrowse then
      begin
        DM.SetPropertyToTable(DM.DataSource_MT_PropertyEd, PropFromMT);
        DM.MemTable_PropertyEd.Post;
      end;

      // Загрузить условные обозначения
      //if AMakeEdit = meEdit then
      if DM.MemTable_PropertyEd.FieldByName(fnIDDataType).AsInteger = dtCompStateType then
      begin
        LoadComponIcon(GIDObjectIcon, GGUIDObjectIcon, Image_CompIcons); //RefreshCompIcons(StrToInt(F_NormBase.F_CaseForm.GValue));
        LoadComponIcon(GIDSymbolImage, GGUIDSymbolImage, Image_Symbol);
      end;
      if OldValue <> PropFromMT.Value then
        DefineNormResByProperty(@PropFromMT);
      GChangedProperty := true;

      if GUseLiteFunctional then
        if AMakeEdit = meEdit then
          Self.DefineUniversalInterfacesByProperty(@PropFromMT, ComponentType.SysName); //Self.DefineUniversalInterfacesByProperty(@PropFromMT, '');

      Self.OnSetComponPropertyVal(AMakeEdit, @PropFromMT, @OldPropFromMT);

      FieldsNames := TStringList.Create;
      try
        FieldsNames.Clear;
        FieldsNames.Add(fnName);
        FieldsNames.Add(fnSysName);
        FieldsNames.Add(fnName);
        FieldsNames.Add(fnIzm);
        FieldsNames.Add(fnDescription);
        FieldsNames.Add(fnIDDataType);
        RefreshFields(TF_Main(GForm).DM.MemTable_PropertyEd, tnProperties, fnIDProperty, fnID, FieldsNames);
      finally
        FreeAndNil(FieldsNames);
        DM.MemTable_PropertyEd.EnableControls;
      end;
    end;
  end;
end;

// ##### Подгрузить иконку #####

procedure TF_AddComponent.LoadComponIcon(AIDObjectIcon: Integer; AGUIDObjectIcon: string; ATrgImage: TcxImage);
var
  Stream: TMemoryStream;
  IconType: Integer;
 // RecNo: Integer;
begin
  Stream := nil;
  if not Assigned(ATrgImage) then
    Exit; ///// EXIT /////

  ClearcxImage(ATrgImage);
  
  if (AIDObjectIcon < 1) and (AGUIDObjectIcon = '') then
    Exit; ///// EXIT /////
  try
    //*** Найти Свойство "Тип условного обозначения"
    IconType := GetSignType;

    if TF_Main(GForm).GDBMode = bkNormBase then
      Stream := F_NormBase.DM.GetComponIconByIconType(AIDObjectIcon, IconType, ieBMP)
    else
      Stream := FSpravochnik.GetObjectIconByIconType(AGUIDObjectIcon, IconType, ieBMP);
    if Assigned(Stream) then
    begin
      Stream.Position := 0;
      ATrgImage.Picture.Bitmap.LoadFromStream(Stream);
      FreeAndNil(Stream);
    end;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.LoadComponIcon: ' + E.Message);
  end;
end;

procedure TF_AddComponent.LoadImageFromObjectIcons(var AIDIcon: Integer; var AGUIDObjectIcon: string; AImage: TcxImage);
begin
  try
    //DataSetLocateByID(F_NormBase.DM.DataSet_OBJECT_ICONS, AIDIcon);
    if TF_Main(GForm).GDBMode = bkNormBase then
    begin
      F_NormBase.F_CaseForm.GIDNotDel := AIDIcon;
      F_NormBase.F_CaseForm.GIDToLocate := AIDIcon;
      //F_NormBase.F_CaseForm.GViewKind := vkObjectIcons;
      //F_NormBase.F_CaseForm.GFormMode := fmEdit;

      //if F_NormBase.F_CaseForm.ShowModal = mrOK then
      if F_NormBase.F_CaseForm.Execute(vkObjectIcons, fmEdit) then
      begin
        AIDIcon := F_NormBase.DM.DataSet_OBJECT_ICONS.FN('ID').AsInteger;
        AGUIDObjectIcon := F_NormBase.DM.DataSet_OBJECT_ICONS.FN(fnGUID).AsString;
        LoadComponIcon(AIDIcon, AGUIDObjectIcon, AImage);
        GWasChanging := true;
      end;
    end
    else if TF_Main(GForm).GDBMode = bkProjectManager then
    begin
      if ShowCurrProjectProperties(vkObjectIcons, AGUIDObjectIcon) then
        if FProjSpravochnik.LastObjectIcon <> nil then
        begin
          AIDIcon := FProjSpravochnik.LastObjectIcon.ID;
          AGUIDObjectIcon := FProjSpravochnik.LastObjectIcon.GUID;
          LoadComponIcon(FProjSpravochnik.LastObjectIcon.ID, FProjSpravochnik.LastObjectIcon.GUID, AImage);
          GWasChanging := true;
        end;
    end;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.LoadImageFromObjectIcons: ' + E.Message);
  end;
end;

procedure TF_AddComponent.RefreshCompIcons(AID_CompStateType: Integer);
//var NPP_ID: Integer;
begin
  {with F_NormBase.DM do
    if MemTable_ComponentIcons.RecordCount > 0 then
      begin
          NPP_ID := MemTable_ComponentIcons.FieldByName('NPP_ID_OBJECT_ICON').AsInteger;
          SelectCompIconsByNPP(NPP_ID);
          SearchRecordMT(MemTable_ComponentIcons, 'ID_COMP_STATE_TYPE', AID_CompStateType);
          LoadComponIcon;
      end;       }
end;

procedure TF_AddComponent.AddInterfaceToMT(AmeInterfaceRel: TmeInterfaceRel);
var
  IsPort: Integer;
  MemTable_InterfOrPort: TkbmMemTable;

  i: Integer;
  NewIDList: TList;
  NumPair: Integer;
  Side: Integer;
  ptrNewID: ^Integer;
  ID1: Integer;
  ID2: Integer;

  Npp: Integer;
  NppPort: Integer;

  {function GetMaxNumPair: Integer;
  var
    CurrMaxNumPair: Integer;
  begin
    Result := 0;
    CurrMaxNumPair := 0;
    with MemTable_InterfOrPort do
    begin
      First;
      while Not Eof do
      begin
        if FieldByName('num_pair').AsInteger > CurrMaxNumPair then
          CurrMaxNumPair := FieldByName('num_pair').AsInteger;
        Next;
      end;
    end;
    result := CurrMaxNumPair;
  end;}

  function GetInterfCountByNumPair(ANumPair: Integer): Integer;
  var
    CurrCount: Integer;
  begin
    Result := 0;
    CurrCount := 0;
    with MemTable_InterfOrPort do
    begin
      First;
      while not Eof do
      begin
        if FieldByName('num_pair').AsInteger = ANumPair then
          CurrCount := CurrCount + 1;
        Next;
      end;
    end;
    Result := CurrCount;
  end;

  function GetNewNumPair: Integer;
  var
    LastNumPair: Integer;
    CountInterfPair: Integer;
    i: Integer;
  begin
    {Result := 0;
    with MemTable_InterfOrPort do
    begin
      //*** Найти максимальный номер пары
      LastNumPair := GetMaxNumPair(MemTable_InterfOrPort);
      if LastNumPair > 0 then
      begin
        for i := 0 to LastNumPair - 1 do
        begin
          CountInterfPair := GetInterfCountByNumPair(i+1);
          if (CountInterfPair mod 2 <> 0) or (CountInterfPair = 0) then
          begin
            Result := i+1;
            Exit; ///// EXIT /////
          end;
        end;
        Result := LastNumPair + 1;
      end
      else
        Result := 1;
    end;}
    Result := TF_Main(GForm).DM.GetInterfaceNewNumPairFromMT(MemTable_InterfOrPort);
  end;

  function GetMaxInterfNppFromMT(AMemTable: TkbmmemTable): Integer;
  var
    i: Integer;
    RecordNo: Integer;
    MaxNpp: Integer;
  begin
    Result := 0;
    RecordNo := AMemTable.RecNo;
    MaxNpp := 0;
    if AMemTable.RecordCount > 0 then // Tolik 28/12/2019 --
    begin
      try
        for i := 0 to AMemTable.RecordCount - 1 do
        begin
          AMemTable.RecNo := i + 1;
          if AMemTable.FieldByName(fnNpp).AsInteger > MaxNpp then
            if AMemTable.FieldByName(fnIDInterface).AsInteger = AmeInterfaceRel.ID_INTERFACE then
              MaxNpp := AMemTable.FieldByName(fnNpp).AsInteger;
        end;
        Result := MaxNpp;
      finally
        AMemTable.RecNo := RecordNo;
      end;
    end;
  end;

  function GetLastNpp: Integer;
  var //i: Integer;
    //    RecordNo: Integer;
    MaxNpp: Integer;
  begin
    Result := 0;
    MaxNpp := GetMaxInterfNppFromMT(TF_Main(GForm).DM.MemTable_InterfaceRelEd);
    Result := MaxNpp;
    MaxNpp := GetMaxInterfNppFromMT(TF_Main(GForm).DM.MemTable_PortEd);
    if MaxNpp > Result then
      Result := MaxNpp;

    {MaxNpp := 0;
    with TF_Main(GForm).DM.MemTable_InterfaceRelEd do
      try
        RecordNo := RecNo;
        for i := 0 to RecordCount - 1 do
        begin
          RecNo := i+1;
          if FieldByName(fnNpp).AsInteger > MaxNpp then
            MaxNpp := FieldByName(fnNpp).AsInteger;
        end;
      finally
        RecNo := RecordNo;
      end;
    with TF_Main(GForm).DM.MemTable_PortEd do
      try
        RecordNo := RecNo;
        for i := 0 to RecordCount - 1 do
        begin
          RecNo := i+1;
          if FieldByName(fnNpp).AsInteger > MaxNpp then
            MaxNpp := FieldByName(fnNpp).AsInteger;
        end;
      finally
        RecNo := RecordNo;
      end;
    Result := MaxNpp;}
  end;

  procedure SetIDAdverse(AIDInterface, AIDAdverse: Integer);
  begin
    with MemTable_InterfOrPort do
      if SearchRecordMT(MemTable_InterfOrPort, 'ID', AIDInterface) then
      begin
        Edit;
        FieldByName('id_adverse').AsInteger := AIDAdverse;
        Post;
      end;
  end;

begin
  NewIDList := nil;
  MemTable_InterfOrPort := nil;
  Side := 0;
  try
    try
      //GT_Interface.BeginUpdate;
      Npp := 0;
      NppPort := 0;

      IsPort := AmeInterfaceRel.IsPort;
      case IsPort of
        biTrue:
          MemTable_InterfOrPort := TF_Main(GForm).DM.MemTable_PortEd;
        biFalse:
          begin
            MemTable_InterfOrPort := TF_Main(GForm).DM.MemTable_InterfaceRelEd;
            NppPort := 0;
          end;
      end;

      if Assigned(MemTable_InterfOrPort) then
      begin
        MemTable_InterfOrPort.DisableControls;
        try
          if TF_Main(GForm).GDBMode = bkProjectManager then
            NppPort := GLastPort;

          if (AmeInterfaceRel.IsLineCompon = biTrue) and
            (AmeInterfaceRel.TYPEI = itFunctional) and
            (AmeInterfaceRel.ServiceIsPair = true) then
          begin
            NewIDList := TList.Create;
            NumPair := 1;
          end
          else
            NumPair := 0;

          //if AmeInterfaceRel.TYPEI = itFunctional then
          Npp := GetLastNpp;

          with MemTable_InterfOrPort do
          begin
            for i := 0 to AmeInterfaceRel.Count - 1 do
            begin
              if (AmeInterfaceRel.IsLineCompon = biTrue) and
                (AmeInterfaceRel.TYPEI = itFunctional) and
                (AmeInterfaceRel.ServiceIsPair = true) then
              begin
                //NumPair := GetNewNumPair;
                Side := (i mod 2) + 1;
                if i mod 2 = 0 then
                begin
                  Npp := Npp + 1;
                  NumPair := GetNewNumPair;
                end;
              end
              else
              begin
                Npp := Npp + 1;
                if AmeInterfaceRel.TYPEI = itFunctional then
                begin
                  if AmeInterfaceRel.IsLineCompon = biTrue then
                    Side := AmeInterfaceRel.Side;
                end
                else
                  Side := stNoneSide;
                NumPair := 0;
              end;
              Last;
              Append;
              FieldByName('id').AsInteger := GenNewID(tkInterfRelED);
              FieldByName(fnIDComponent).AsInteger := GIDComponent;
              FieldByName(fnNpp).AsInteger := Npp;
              FieldByName('Name').AsString := AmeInterfaceRel.Name;
              FieldByName('TypeI').AsInteger := AmeInterfaceRel.TYPEI;
              FieldByName('Kind').AsInteger := AmeInterfaceRel.Kind;
              FieldByName('IsPort').AsInteger := AmeInterfaceRel.IsPort;
              FieldByName('Gender').AsInteger := AmeInterfaceRel.GENDER;
              FieldByName('ID_Interface').AsInteger := AmeInterfaceRel.ID_INTERFACE;
              FieldByName(fnGuidInterface).AsString := AmeInterfaceRel.GUIDInterface;
              FieldByName('Multiple').AsInteger := AmeInterfaceRel.Multiple;
              FieldByName('IsBusy').AsInteger := 0;
              FieldByName('Color').AsInteger := AmeInterfaceRel.Color;
              FieldByName(fnNotice).AsString := AmeInterfaceRel.Notice;
              FieldByName(fnKolvo).AsInteger := AmeInterfaceRel.Kolvo;
              FieldByName(fnKolvoBusy).AsInteger := 0;
              FieldByName(fnSignType).AsInteger := AmeInterfaceRel.SignType;
              FieldByName(fnConnToAnyGender).AsInteger := AmeInterfaceRel.ConnToAnyGender;
              FieldByName(fnSideSection).AsString := AmeInterfaceRel.SideSection;
              FieldByName('isNative').AsBoolean := True;

              case IsPort of
                biTrue:
                  if TF_Main(GForm).GDBMode = bkProjectManager then
                  begin
                    //NppPort := NppPort + 1;
                    //GLastPort := GLastPort + 1;
                    NppPort := NppPort + 1;
                    FieldByName('npp_port').AsInteger := NppPort;

                    NppPort := NppPort + AmeInterfaceRel.Kolvo - 1;
                    GLastPort := NppPort;
                  end;
                biFalse:
                  begin
                    FieldByName('ValueI').AsFloat := AmeInterfaceRel.ValueI;
                    FieldByName('Num_Pair').AsInteger := NumPair;
                    FieldByName('Side').AsInteger := Side;
                    TF_Main(GForm).DM.DefineInterfaceNumPairsStr(MemTable_InterfOrPort, NumPair, AmeInterfaceRel.Kolvo);
                  end;
              end;

              FieldByName('isNew').AsBoolean := true;
              FieldByName('isModified').AsBoolean := false;
              Post;

              if FieldByName('ID').AsInteger <= 1 then
                with TF_Main(GForm).DM do
                begin
                  //SetSQLToQuery(scsQSelect, ' select * from GET_LAST_INTERF_REL_ID ');
                  //Edit;
                  //FieldByName('ID').AsInteger := scsQSelect.GetFNAsInteger('LASTID') + 1;
                  //Post;
                  Edit;
                  FieldByName('ID').AsInteger := GetLastInterfRelID(TF_Main(GForm).GDBMode) + 1;
                  Post;
                end;

              if NewIDList <> nil then
              begin
                New(ptrNewID);
                ptrNewID^ := FieldByName('ID').AsInteger;
                NewIDList.Add(ptrNewID);
              end;

              GChangedInterface := true;
              EnableButtons;
            end;

            if NewIDList <> nil then
            begin
              i := 0;
              while i < NewIDList.Count do
              begin
                ID1 := Integer(NewIDList.Items[i]^);
                ID2 := Integer(NewIDList.Items[i + 1]^);
                SetIDAdverse(ID1, ID2);
                SetIDAdverse(ID2, ID1);
                i := i + 2;
              end;
            end;
          end;
        finally
          MemTable_InterfOrPort.EnableControls;
        end;
      end;
    except
      on E: Exception do
        AddExceptionToLog('TF_AddComponent.AddInterfaceToMT: ' + E.Message);
    end;
  finally
    //GT_Interface.EndUpdate;
    if NewIDList <> nil then
    // Tolik 03/10/2017 --
    //  FreeAndNil(NewIDList);
    FreeAndDisposeList(NewIDList); // нужно освободить память за собой
    //
  end;
end;

procedure TF_AddComponent.CalcNormCost;
var
  SCSNorm: TSCSNorm;
  ResourceRel: TSCSResourceRel;
  RecNoResource: Integer;
  i: Integer;
begin
  with TF_Main(GForm).DM do
  begin
    RecNoResource := MemTable_ResourcesRelEd.RecNo;
    SCSNorm := TSCSNorm.Create(GForm, ntProj);

    SCSNorm.Kolvo := -1;
    SCSNorm.Price := -1;
    try
      try
        RecNoResource := MemTable_ResourcesRelEd.RecNo;
        //GT_Resources.DataController.BeginUpdate;
        if MemTable_NormsEd.RecordCount > 0 then // Tolik 28/12/2019 --
        begin
          SCSNorm.Kolvo := MemTable_NormsEd.FieldByName(fnKolvo).AsFloat;
          SCSNorm.Price := MemTable_NormsEd.FieldByName(fnPrice).AsFloat;
        end;
        {MemTable_ResourcesRelEd.First;
        while Not MemTable_ResourcesRelEd.Eof do
          begin
              if MemTable_ResourcesRelEd.FieldByName('IsOn').AsInteger = biTrue then
                begin
                    New(ptrResource);
                    ptrResource.IsOn := MemTable_ResourcesRelEd.FieldByName('IsOn').AsInteger;
                    ptrResource.Cost := MemTable_ResourcesRelEd.FieldByName('Cost').AsFloat;
                    SCSNorm.Resources.Add(ptrResource);
                end;
              MemTable_ResourcesRelEd.Next;
          end; }

        if GT_Resources.DataController.RecordCount > 0 then // Tolik 28/12/2019 --
        begin
          for i := 0 to GT_Resources.DataController.RecordCount - 1 do
          begin
            if GT_Resources.DataController.Values[i, fiResourceIsOn] = biTrue then
            begin
              ResourceRel := TSCSResourceRel.Create(GForm, ntProj);
              ResourceRel.IsOn := GT_Resources.DataController.Values[i, fiResourceIsOn];
              ResourceRel.Price := GT_Resources.DataController.Values[i, fiResourcePrice];
              ResourceRel.AdditionalPrice := GT_Resources.DataController.Values[i, fiResourceAdditionalPrice];
              ResourceRel.Kolvo := GT_Resources.DataController.Values[i, fiResourceKolvo];
              ResourceRel.Cost := GT_Resources.DataController.Values[i, fiResourceCost];
              SCSNorm.Resources.Add(ResourceRel);
            end;
          end;
        end;
        if SCSNorm.Kolvo > 0 then  // Tolik 28/12/2019 --
        begin
          SCSNorm.CalcTotalCost(true);
          MemTable_NormsEd.Edit;
          MemTable_NormsEd.FieldByName(fnCost).AsFloat := SCSNorm.Cost;
          MemTable_NormsEd.FieldByName('total_cost').AsFloat := SCSNorm.TotalCost;
          MemTable_NormsEd.FieldByName('isModified').AsBoolean := true;
          MemTable_NormsEd.Post;
        end;
          CalcWorkCost;
      except
        on E: Exception do
          AddExceptionToLog('TF_AddComponent.CalcNormCost: ' + E.Message);
      end;
    finally
      SCSNorm.Free;
      if RecNoResource > -1 then // Tolik 28/12/2019 --
        MemTable_ResourcesRelEd.RecNo := RecNoResource;
      //GT_Resources.DataController.EndUpdate;
    end;
  end;
end;

procedure TF_AddComponent.CalcWorkCost;
var
  SCSNorms: TSCSNormsResources;
  SCSNorm: TSCSNorm;
  i: Integer;
begin
  SCSNorms := TSCSNormsResources.Create(GForm, ctkComponent {GMasterTableKind});
  try
    try
      SCSNorms.IDMaster := GIDComponent; //FIDMaster;
      if GT_NORMS.DataController.RecordCount > 0 then // Tolik 28/12/2019 --
      begin
        for i := 0 to GT_NORMS.DataController.RecordCount - 1 do
        begin
          if GT_NORMS.DataController.Values[i, 1] = biTrue then //*** поле "Включен"
          begin
            SCSNorm := TSCSNorm.Create(GForm, ntProj);
            SCSNorm.IsOn := GT_NORMS.DataController.Values[i, fiNormIsOn];
            SCSNorm.TotalCost := GT_NORMS.DataController.Values[i, fiNormTotalCost];
            SCSNorms.Norms.Add(SCSNorm);
          end;
        end;
      end;

      SCSNorms.CalcResourcesCost(false, false);
      CurrencyEdit_ResourcesCost.Value := SCSNorms.TotalCost;

    except
      on E: Exception do
        AddExceptionToLog('TF_AddComponent.CalcWorkCost: ' + E.Message);
    end;
  finally
    SCSNorms.Free;
  end;
end;

procedure TF_AddComponent.ApplyChangedComponentType;
const
  IDConstrInterf = 97;
var //*** Для свойств
  MemTable_Prop: TkbmMemTable;
  PrevComponType: TComponentType;
  NewComponentType: TComponentType;
  KeepIDList: TList;
  IDComponType: Integer;
  IDProperty: Integer;
  IDCompPropRel: Integer;
  ptrID: ^Integer;

  ComponTypePropCount: Integer;

  //*** для интерфейсов
  HaveConstructive: Boolean;
  HaveIDConstrInterf: Boolean;
  RecNomber: Integer;
  meInterfaceRel: TmeInterfaceRel;

  TemplateComponent: TSCSComponent;
  LoadedFromTemplate: Boolean;
begin
  try
    IDComponType := GetIDFromComboBox(ComboBox_ComponentType);
    if IDComponType < 1 then
      Exit; ///// EXIT /////

    LoadedFromTemplate := false;
    PrevComponType := FCurrComponentType;
    NewComponentType := TF_Main(GForm).FNormBase.DM.GetComponentType(IDComponType);

    if FCurrComponentType.GUID <> NewComponentType.GUID then
    begin
      if Edit_Name.Text = '' then
        Edit_Name.Text := NewComponentType.Name;

      //18.04.2013 if (GUseLiteFunctional or (GUseComponTemplates and cbImportFromTemplate.Checked)) and
      if (GLiteVersion or (GUseComponTemplates and cbImportFromTemplate.Checked)) and
        (TF_Main(GForm).GDBMode = bkNormBase) then
      begin
        ProcessMessagesEx;
        TemplateComponent := TSCSComponent.Create(GForm);
        try
          if GUseComponTemplates and (NewComponentType.IDComponTemplate > 0) and cbImportFromTemplate.Checked then
          begin
            {//*** Установить записи как удаленные
            with TF_Main(GForm).DM do
            begin
              //*** Порты/Интерфейсы
              RemoveNoNativeInterfacesFromMemTable(MemTable_PortEd);
              RemoveNoNativeInterfacesFromMemTable(MemTable_InterfaceRelEd);
              SetAsDeletedMTRecords(MemTable_PortEd, MemTable_PortInterfRelEd, GDeletedInterfRel, GDeletedPortInterfRels);
              SetAsDeletedMTRecords(MemTable_InterfaceRelEd, nil, GDeletedInterfRel, nil);
              //*** Элементы каб. каналов
              SetAsDeletedMTRecords(MemTable_CableCanalConnectorsEd, nil, GDeletedCableCanalConnectors, nil);
              //*** Кросс-соединения
              SetAsDeletedMTRecords(mtCrossConnectionEd, nil, GDeletedCrossConnections, nil);
            end;

            TemplateComponent.LoadComponentByID(NewComponentType.IDComponTemplate, false);
            TemplateComponent.LoadComponentData([cdCableCanalConnectors,
              //cdConections,
              cdCrossConnections,
                cdProperties,
                cdInterfaces,
                cdComponentType,
                cdNorms,
                cdResources]);
            TemplateComponent.SetPortInterfRelInterfaces;
            TemplateComponent.SetInterfacesParallel;

            SendComponentToForm(TemplateComponent, true);
            LoadedFromTemplate := true;                  }

            ImportComponentByID(NewComponentType.IDComponTemplate);
            LoadedFromTemplate := true;
          end
          else
          begin
            //*** Установить Свойства как удаленные
            with TF_Main(GForm).DM do
              SetAsDeletedMTRecords(MemTable_PropertyEd, nil, GDeletedPropRel, nil);

            TemplateComponent.ComponentType := NewComponentType;
            TemplateComponent.ID_ComponentType := NewComponentType.ID;
            TemplateComponent.GUIDComponentType := NewComponentType.GUID;
            TemplateComponent.LoadPropertyesFromComponentType;
            TF_Main(GForm).DM.FillMemTablePropFromList(TF_Main(GForm).DM.MemTable_PropertyEd, TemplateComponent.Properties, true);
            if NewComponentType.IDDesignIcon > 0 then
            begin
              GIDObjectIcon := NewComponentType.IDDesignIcon;
              LoadComponIcon(NewComponentType.IDDesignIcon, '', Image_CompIcons);
            end;

            // Подгрузить интерфейсы для типа
            if GUseLiteFunctional then
            begin
              DeleteAllPortsAndInterf;
              // Подгрузить интерфейсы для типа
              DefineUniversalInterfacesByProperty(nil, NewComponentType.SysName);
            end;
          end;
        finally
          TemplateComponent.Free;
        end;
      end
      else
      begin
        //GT_NORMSExpenseForLength.Visible := NewComponentType.IsLine = biTrue;
        //VisibleInterfaceColumns(NewComponentType.IsLine = biTrue);
        //SetVisibleByIsLine(NewComponentType.IsLine);
      end;
      if not LoadedFromTemplate then
      begin
        //*** Смена с точ-го на линейный - очистить все что кас-ся точ-х
        if (NewComponentType.IsLine = biTrue) and (FCurrComponentType.IsLine = biFalse) then
        begin
          //*** Порты
          TF_Main(GForm).DM.RemoveNoNativeInterfacesFromMemTable(TF_Main(GForm).DM.MemTable_PortEd);
          SetAsDeletedMTRecords(TF_Main(GForm).DM.MemTable_PortEd, TF_Main(GForm).DM.MemTable_PortInterfRelEd, GDeletedInterfRel, GDeletedPortInterfRels);
          TF_Main(GForm).DM.MemTable_PortEd.Active := false;
          TF_Main(GForm).DM.MemTable_PortEd.Active := True;
          TF_Main(GForm).DM.MemTable_PortInterfRelEd.Active := false;
          TF_Main(GForm).DM.MemTable_PortInterfRelEd.Active := True;
          //*** Кросс-соединения
          SetAsDeletedMTRecords(TF_Main(GForm).DM.mtCrossConnectionEd, nil, GDeletedCrossConnections, nil);
          TF_Main(GForm).DM.mtCrossConnectionEd.Active := false;
          TF_Main(GForm).DM.mtCrossConnectionEd.Active := True;
        end;
        // смена с каб канала на не каб канал - очистить элементы каб каналов
        if (NewComponentType.SysName <> ctsnCableChannel) and (FCurrComponentType.SysName = ctsnCableChannel) then
        begin
          SetAsDeletedMTRecords(TF_Main(GForm).DM.MemTable_CableCanalConnectorsEd, nil, GDeletedCableCanalConnectors, nil);
          TF_Main(GForm).DM.MemTable_CableCanalConnectorsEd.Active := false;
          TF_Main(GForm).DM.MemTable_CableCanalConnectorsEd.Active := true;
        end;

        VisibleInterfaceColumns(NewComponentType.IsLine = biTrue);
        SetVisibleByIsLine(NewComponentType.IsLine);
      end;
      FCurrComponentType := NewComponentType;
      DefineSupplyPriceByComponActualPrice;

      //21.08.2012 - если отмечено для группового применения, то обновить видимость флажков
      if pcApplyForAll.ActivePage = tsApplyInNB then
      begin
        if cbApplyForCurrentDir.Checked then
          cbApplyForCurrentDirPropertiesChange(cbApplyForCurrentDir);
      end
      else
      if pcApplyForAll.ActivePage = tsApplyInPM then
      begin
        if CheckBox_ApplyForProject.Checked then
          CheckBox_ApplyForProjectPropertiesChange(CheckBox_ApplyForProject)
        else
        if CheckBox_ApplyForList.Checked then
          CheckBox_ApplyForListPropertiesChange(CheckBox_ApplyForList);
      end;

      EnableButtons;
      SetControls(@PrevComponType);
    end;

    (*
    IDComponType := GetIDFromComboBox(ComboBox_ComponentType);
    if IDComponType < 1 then
      Exit; ///// EXIT /////

    NewComponentType := TF_Main(GForm).FNormBase.DM.GetComponentType(IDComponType);
    if Edit_Name.Text = '' then
      Edit_Name.Text := NewComponentType.NAME;

    //GT_NORMSExpenseForLength.Visible := NewComponentType.IsLine = biTrue;
    VisibleInterfaceColumns(NewComponentType.IsLine = biTrue);

    //*** Удалить свойства, которые не пренадлежат новому типу компоненты
    KeepIDList := TList.Create;
    TF_Main(GForm).DM.MemTable_PropertyEd.DisableControls;
    try
      with TF_Main(GForm).DM do
        begin
            MemTable_PropertyEd.Last;
            while Not MemTable_PropertyEd.Bof do
              begin
                  IDProperty := MemTable_PropertyEd.FieldByName('ID_PROPERTY').AsInteger;
                  IDCompPropRel := MemTable_PropertyEd.FieldByName('ID').AsInteger;
                  ComponTypePropCount := 0;
                  with TF_Main(GForm).FNormBase.DM do
                    begin
                        SetSQLToQuery(scsQSelect, ' select count(id) from comp_type_prop_relation '+
                                                    ' where (id_component_type = '''+IntToStr(IDComponType)+''') and '+
                                                          ' (id_property = '''+IntToStr(IDProperty)+''') ');
                        ComponTypePropCount := scsQSelect.GetFNAsInteger('count');
                    end;

                  if ComponTypePropCount = 0 then
                    begin
                        if MemTable_PropertyEd.FieldByName(fnIsNew).AsBoolean = false then
                          GDeletedPropRel.Add(IntToStr(MemTable_PropertyEd.FieldByName('ID').AsInteger));
                        MemTable_PropertyEd.Delete;
                    end
                  else
                    begin
                        New(ptrID);
                        ptrID^ := IDProperty;
                        KeepIDList.Add(ptrID);
                        MemTable_PropertyEd.Prior;
                    end;
              end;
            MemTable_Prop := MemTable_PropertyEd;
        end;

      //*** Отобрать свойства нового типа компоненты
      with TF_Main(GForm).FNormBase.DM do
        begin
            SetSQLToQuery(scsQSelect, ' SELECT ID_PROPERTY, PVALUE, TAKE_INTO_CONNECT, TAKE_INTO_JOIN, '+
                                               ' NAME, SYSNAME, IZM, DESCRIPTION, ID_DATA_TYPE '+
                                        ' FROM COMP_TYPE_PROP_RELATION, PROPERTIES '+
                                        ' WHERE (ID_COMPONENT_TYPE = '''+IntToStr(IDComponType)+''') AND (PROPERTIES.ID = ID_PROPERTY) ');
            while Not scsQSelect.Eof do
            begin
              if CheckNoIDinList(scsQSelect.GetFNAsInteger('ID_PROPERTY'), KeepIDList) then
              begin
                MemTable_Prop.Append;
                MemTable_Prop.FieldByName('Name').AsString := scsQSelect.GetFNAsString('Name');
                MemTable_Prop.FieldByName('SysName').AsString := scsQSelect.GetFNAsString('SysName');
                MemTable_Prop.FieldByName('ID_PROPERTY').AsInteger := scsQSelect.GetFNAsInteger('ID_PROPERTY');
                MemTable_Prop.FieldByName('PVALUE').AsString := scsQSelect.GetFNAsString('PVALUE');
                MemTable_Prop.FieldByName('Izm').AsString := scsQSelect.GetFNAsString('Izm');
                MemTable_Prop.FieldByName('TAKE_INTO_CONNECT').AsInteger := scsQSelect.GetFNAsInteger('TAKE_INTO_CONNECT');
                MemTable_Prop.FieldByName('TAKE_INTO_JOIN').AsInteger := scsQSelect.GetFNAsInteger('TAKE_INTO_JOIN');
                MemTable_Prop.FieldByName('Description').AsString := scsQSelect.GetFNAsString('Description');
                MemTable_Prop.FieldByName('ID_Data_Type').AsInteger := scsQSelect.GetFNAsInteger('ID_Data_Type');
                MemTable_Prop.FieldByName(fnIsDefault).AsInteger := biTrue;
                MemTable_Prop.FieldByName('IsNew').AsBoolean := True;
                MemTable_Prop.Post;
              end;
              scsQSelect.Next;
            end;
            MemTable_Prop.First;
        end;

      //*** Определить интерфейс
      HaveIDConstrInterf := false;
      HaveConstructive := false;
      with TF_Main(GForm).DM do
        begin
            //*** Проверить есть ли конструктивный интерфейс
            RecNomber := MemTable_InterfaceRelEd.RecNo;
            MemTable_InterfaceRelEd.Last;
            while Not MemTable_InterfaceRelEd.Bof do
              begin
                  if (NewComponentType.IsLine = biFalse) and
                     (MemTable_InterfaceRelEd.FieldByName('ID_INTERFACE').AsInteger = IDConstrInterf) then
                    begin
                        if MemTable_InterfaceRelEd.FieldByName('isNew').AsBoolean = false then
                          GDeletedInterfRel.Add(IntToStr(MemTable_InterfaceRelEd.FieldByName('ID').AsInteger));
                        MemTable_InterfaceRelEd.Delete;
                        Break;
                    end
                  else
                    begin
                        if NewComponentType.IsLine = biTrue then
                          if MemTable_InterfaceRelEd.FieldByName('TypeI').AsInteger = itConstructive then
                            begin
                                HaveConstructive := true;
                                Break;
                            end;
                        MemTable_InterfaceRelEd.Prior;
                    end;
              end;
            MemTable_InterfaceRelEd.RecNo := RecNomber;

            if (NewComponentType.IsLine = biTrue) and Not(HaveConstructive) then
              begin
                  with F_NormBase.DM do
                    begin
                        SetSQLToQuery(scsQSelect, ' select name from interface where id = '''+IntToStr(IDConstrInterf)+''' ');
                        meInterfaceRel.NAME := scsQSelect.GetFNAsString('name');
                    end;
                  if meInterfaceRel.NAME <> '' then
                    begin
                        meInterfaceRel.IsLineCompon := biTrue;
                        meInterfaceRel.TypeI := itConstructive;
                        meInterfaceRel.Gender := gtMale;
                        meInterfaceRel.ID_Interface := IDConstrInterf;
                        meInterfaceRel.Kolvo := 1;
                        meInterfaceRel.Multiple := biFalse;
                        meInterfaceRel.IsBusy := biFalse;
                        meInterfaceRel.ValueI := 10;
                        AddInterfaceToMT(meInterfaceRel);
                    end;
              end;
        end;

      //*** Определить изображение
      LoadComponIcon(NewComponentType.IDDesignIcon, Image_Symbol);
      GIDSymbolImage := NewComponentType.IDDesignIcon;

      SetControls;
      SetVisibleByIsLine(NewComponentType.IsLine);
      {case NewComponentType.IsLine of
        biFalse:
            begin
                Label_MaxLength.Visible := false;
                SpinEdit_MaxLength.Visible := false;

                Label_UserLength.Visible := False;
                SpinEdit_UserLength.Visible := false;
            end;
        biTrue:
            begin
                Label_MaxLength.Visible := true;
                SpinEdit_MaxLength.Visible := true;

                Label_UserLength.Visible := True;
                SpinEdit_UserLength.Visible := True;
            end;
      end;}

      EnableButtons;
      GWasChanging := true;
    finally
      TF_Main(GForm).DM.MemTable_PropertyEd.EnableControls;
      FreeList(KeepIDList);
      //GT_Property.EndUpdate;
    end; *)
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.ApplyChangedComponentType: ' + E.Message);
  end;
end;

function TF_AddComponent.ReadOnly: Boolean;
begin
  Result := false;
  if GFormMode = fmView then
  begin
    Result := true;
    MessageModal(cAddComponent_Msg21, ApplicationName, MB_OK or MB_ICONINFORMATION);
  end;
end;

procedure TF_AddComponent.LoadNormsResources(AAsNew: Boolean);
var //qSQL: String;
  SCSComponent: TSCSComponent;
  OutNormsResources: TSCSNormsResources;
  NormsResources: TSCSNormsResources;
  //ObjectLength: Double;
  //LevelCatalogID: Integer;
  ptrObjectCurrency: PObjectCurrencyRel;

  i, j: Integer;
  SCSNorm: TSCSNorm;
  ResourceRel: TSCSResourceRel;
  RecCount: Integer;
  NppFinded: Boolean;
  //SavedMasterSource: TDataSource;
begin
  DefineComponCurrencies;

  //if TF_MAIN(GForm).GDBMode = bkNormBase then
  //begin
  //  IDCatalog := 0;
  //  if GFormMode = fmMake then
  //    IDCatalog := TF_Main(GForm).GSCSBase.SCSCatalog.ID
  //  else
  //    IDCatalog := TF_Main(GForm).DM.GetComponCatalogOwnerID(GIDComponent);
  //  FNBCurrency := TF_Main(GForm).FNormBase.GCurrencyM;
  //  //LevelCatalogID := TF_Main(GForm).DM.GetParentCatalogIDByLevel(IDCatalog, dirCurrencyLevel);
  //  //ptrObjectCurrency := TF_Main(GForm).DM.GetObjectCurrencyByIDCurrency(LevelCatalogID, FNBCurrency.ID);
  //  ptrObjectCurrency := TF_Main(GForm).DM.GetCatalogCurrencyByCurrencyID(IDCatalog, TF_Main(GForm).FNormBase.GCurrencyM.ID);
  //  if ptrObjectCurrency <> nil then
  //  begin
  //    FNBCurrency := ptrObjectCurrency.Data;
  //    FreeMem(ptrObjectCurrency);
  //  end;
  //  //FNBCurrency := TF_Main(GForm).FNormBase.DM.get GCurrencyM;
  //end
  //else
  //// Ресурс добавляется в проект из нормативной базы, то валюту берем по норм. базе.
  //if TF_MAIN(GForm).GDBMode = bkProjectManager then
  //  FNBCurrency := TF_Main(GForm).FNormBase.GCurrencyM;

  OutNormsResources := nil;
  SCSComponent := nil;

  if TF_Main(GForm).GDBMode = bkProjectManager then
  begin
    SCSComponent := TF_Main(GForm).GSCSBase.CurrProject.GetComponentFromReferences(GIDComponent);
    if Assigned(SCSComponent) then
      OutNormsResources := SCSComponent.NormsResources;
  end;

  GT_NORMS.OnFocusedRecordChanged := nil;
  with TF_Main(GForm).DM do
  begin
    //*** Загрузить форматы валют
    //GT_NORMSCost.Properties.
    {
    SavedMasterSource := MemTable_ResourcesRelEd.MasterSource;
    MemTable_ResourcesRelEd.MasterSource := nil;
    MemTable_ResourcesRelEd.Active := false;
    MemTable_ResourcesRelEd.Active := true;

    MemTable_NormsEd.Active := false;
    MemTable_NormsEd.Active := true;
    MemTable_ResourcesRelEd.MasterSource := SavedMasterSource;
    }

    {MemTable_NormsEd.Active := false;
    MemTable_NormsEd.Active := true;
    MemTable_ResourcesRelEd.Active := false;
    MemTable_ResourcesRelEd.Active := true;}

    MemTable_ResourcesRelEd.Active := false;
    MemTable_NormsEd.Active := false;
    MemTable_NormsEd.Active := true;
    MemTable_ResourcesRelEd.Active := true;

    //*** Отобрать нормы
    NormsResources := nil;
    FOutNormsResources := OutNormsResources;
    if not Assigned(OutNormsResources) then
    begin
      NormsResources := TSCSNormsResources.Create(GForm, ctkComponent);
      NormsResources.IDMaster := GIDComponent;
      NormsResources.LoadNorms(true, true);
      NormsResources.LoadResources(True);
    end
    else
      NormsResources := OutNormsResources;
          
    if Assigned(NormsResources) then
    begin
      NormsResources.IDMaster := GIDComponent;
      //NormsResources.Length := ObjectLength;

      NormsResources.CalcResourcesCost(true, true);  

      {MemTable_NormsEd.Active := false;
      MemTable_NormsEd.Active := true;
      MemTable_ResourcesRelEd.Active := false;
      MemTable_ResourcesRelEd.Active := true; }

      for j := 0 to NormsResources.Norms.Count - 1 do
      begin
        SCSNorm := NormsResources.Norms.Items[j];
        SCSNorm.IsNew := AAsNew;
        LoadFromNormToMT(SCSNorm, MemTable_NormsEd, meNone, -1, FTraccaLength, nil); //Self.LoadFromNormToMT(SCSNorm, meNone, -1);
      end;
      for j := 0 to NormsResources.Resources.Count - 1 do
      begin
        ResourceRel := NormsResources.Resources.Items[j];
        ResourceRel.IsNew := AAsNew;
        LoadFromResourceToMT(ResourceRel, MemTable_NormsEd, meNone, tkNormEd, FTraccaLength, nil); //Self.LoadFromResourceToMT(ResourceRel, meNone, tkNormEd);
      end;

      {RecCount := NormsResources.Norms.Count + NormsResources.Resources.Count;
      for i := 0 to RecCount - 1 do
      begin
        NppFinded := false;
        for j := 0 to NormsResources.Norms.Count - 1 do
        begin
          SCSNorm := NormsResources.Norms.Items[j];
          //if SCSNorm.NPP = i + 1 then
          begin
            LoadFromNormToMT(SCSNorm, meNone, -1);
            NppFinded := true;
            Break;
          end;
        end;

        if Not NppFinded then
          for j := 0 to NormsResources.Resources.Count - 1 do
          begin
            ResourceRel := NormsResources.Resources.Items[j];
            //if ResourceRel.NPP = i + 1 then
            begin
              LoadFromResourceToMT(ResourceRel, meNone, tkNormEd);
              Break;
            end;
          end;
      end;}

      //*** Запомнить цену компоненты
      //GComponPrice := 0;
      //if NormsResources.Resources.Count > 0 then
      //  GComponPrice := TSCSResourceRel(NormsResources.Resources[0]).Price;

      //MemTable_NormsEd.First;
      if not Assigned(OutNormsResources) then
        NormsResources.Free;
    end;
    CalcWorkCost;
  end;
  GT_NORMS.OnFocusedRecordChanged := GT_NORMSFocusedRecordChanged;
  TF_Main(GForm).DM.MemTable_NormsEd.First;

  EnableEditDelNorm;
  GDeletedNormID.Clear;
  GDeletedResourceID.Clear;
end;

procedure TF_AddComponent.SaveNormsResources;
var
  i: Integer;
  //qSQL: String;
  //MakeEdit: TMakeEdit;
  //NormsFields: TStringList;
  //ResourcesFields: TStringList;
  //NormResourceRelFields: TStringList;

  //CurrIDNorm: Integer;
  //CurrIDResource: Integer;

  NormResources: TSCSNormsResources;
  SCSNorm: TSCSNorm;
  ResourceRel: TSCSResourceRel;
  //SCSComponent: TSCSComponent;
begin
  with TF_Main(GForm).DM do
  begin
    //*** Удалить удаленные связей с удаленными ресурсами
    for i := 0 to GDeletedResourceID.Count - 1 do
    begin
      if TF_Main(GForm).GDBMode = bkNormBase then
        DelResourceRelByID(GDeletedResourceID[i]);
      if Assigned(FOutNormsResources) then
      begin
        ResourceRel := FOutNormsResources.Resources.GetResourceByID(GDeletedResourceID[i]);
        if Assigned(ResourceRel) then
        begin
          FOutNormsResources.Resources.Remove(ResourceRel);
          FreeAndNil(ResourceRel);
        end;
      end;
    end;

    //*** Удалить удаленные нормы
    for i := 0 to GDeletedNormID.Count - 1 do
    begin
      if TF_Main(GForm).GDBMode = bkNormBase then
        DelNormByID(GDeletedNormID[i]);
      if Assigned(FOutNormsResources) then
      begin
        SCSNorm := FOutNormsResources.Norms.GetNormByID(GDeletedNormID[i]);
        if Assigned(SCSNorm) then
        begin
          FOutNormsResources.Norms.Remove(SCSNorm);
          FreeAndNil(SCSNorm);
        end;
      end;
    end;

    //*** Перемещение данных в объект
    NormResources := nil;
    if not Assigned(FOutNormsResources) then
      NormResources := TSCSNormsResources.Create(GForm, ctkComponent)
    else
    begin
      NormResources := FOutNormsResources;
      NormResources.Norms.Clear;
      NormResources.Resources.Clear;
    end;
    if Assigned(NormResources) then
    begin
      MemTable_NormsEd.First;
      while not MemTable_NormsEd.Eof do
      begin
        case TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnIsResource).AsBoolean of
          true: // Внести ресурс
            begin
              ResourceRel := TSCSResourceRel.Create(GForm, ntProj);
              LoadFromMTToResource(TF_Main(GForm).DM.MemTable_NormsEd, ResourceRel, tkNormEd); //LoadFromMTToResource(tkNormEd, ResourceRel);
              NormResources.IDMaster := GIDComponent;
              NormResources.Resources.Add(ResourceRel);
            end;
          false: // Внести Норму
            begin
              SCSNorm := TSCSNorm.Create(GForm, ntProj);
              LoadFromMTToNorm(TF_Main(GForm).DM.MemTable_NormsEd, SCSNorm); //LoadFromMTToNorm(SCSNorm);
              NormResources.Norms.Add(SCSNorm);
              SCSNorm.IDMaster := GIDComponent;

              // Внести в норму ее ресурсы
              MemTable_ResourcesRelEd.First;
              while not MemTable_ResourcesRelEd.Eof do
              begin
                ResourceRel := TSCSResourceRel.Create(GForm, ntProj);
                LoadFromMTToResource(MemTable_ResourcesRelEd, ResourceRel, tkResourceRelEd); //LoadFromMTToResource(tkResourceRelEd, ResourceRel);
                SCSNorm.Resources.Add(ResourceRel);
                MemTable_ResourcesRelEd.Next;
              end;
            end;
        end;
        MemTable_NormsEd.Next;
      end;
      NormResources.SaveByServiceFields(GIDComponent);
      if not Assigned(FOutNormsResources) then
        NormResources.Free;
    end;
  end;
end;

procedure TF_AddComponent.DelResourcesFromCurrNorm;
var
  IDResource: Integer;
begin
  with TF_Main(GForm).DM do
  begin
    MemTable_ResourcesRelEd.Last;
    while not MemTable_ResourcesRelEd.Bof do
    begin
      IDResource := MemTable_ResourcesRelEd.FieldByName('id').AsInteger;
      if MemTable_ResourcesRelEd.FieldByName('isNew').AsBoolean = false then
        GDeletedResourceID.Add(IDResource);
      MemTable_ResourcesRelEd.Delete;
    end;
  end;
end;

procedure TF_AddComponent.EnableEditDelNorm;
begin
  if not TF_Main(GForm).DM.MemTable_NormsEd.Active or (TF_Main(GForm).DM.MemTable_NormsEd.RecordCount = 0) then
  begin
    Act_EditNormResource.Enabled := false;
    Act_DeleteNormResource.Enabled := false;
  end
  else
  begin
    Act_EditNormResource.Enabled := true;
    Act_DeleteNormResource.Enabled := true;
  end;
  EnableEditDelResource;
end;

procedure TF_AddComponent.EnableEditDelResource;
begin
  if not TF_Main(GForm).DM.MemTable_NormsEd.Active or (TF_Main(GForm).DM.MemTable_NormsEd.RecordCount = 0) then
  begin
    Act_AddResource.Enabled := false;
    Act_EditResource.Enabled := false;
    Act_DelResource.Enabled := false;
  end
  else
  begin
    if TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnIsResource).AsBoolean = true {TF_Main(GForm).DM.MemTable_NormsEd.RecNo = 1} {FieldByName('npp').AsInteger = 1} then
      Act_AddResource.Enabled := false
    else
      Act_AddResource.Enabled := true;

    if not TF_Main(GForm).DM.MemTable_ResourcesRelEd.Active or (TF_Main(GForm).DM.MemTable_ResourcesRelEd.RecordCount = 0) then
    begin
      Act_EditResource.Enabled := false;
      Act_DelResource.Enabled := false;
    end
    else
    begin
      Act_EditResource.Enabled := true;
      Act_DelResource.Enabled := true;
    end;
  end;
end;

function TF_AddComponent.GetExistsResourcesIDsFromCurrNorm: TIntList;
var
  IDResource: Integer;
begin
  Result := TIntList.Create;
  with TF_Main(GForm).DM do
  begin
    MemTable_ResourcesRelEd.Last;
    while not MemTable_ResourcesRelEd.Bof do
    begin
      IDResource := MemTable_ResourcesRelEd.FieldByName('id').AsInteger;
      if MemTable_ResourcesRelEd.FieldByName('isNew').AsBoolean = false then
        Result.Add(IDResource);
      MemTable_ResourcesRelEd.Prior;
    end;
  end;
end;

// ##### Добавить / Изменить норму #####

procedure TF_AddComponent.AddEditNorm(AMakeEdit: TMakeEdit);
var
  ExistsResourcesIDsFromCurrNorm: TIntList;

  ID_Norm: Integer;
  //ID_ResourceRel: Integer;
  //ModRes: TModalResult;
  //NewNpp: Integer;
  GUIDNorm: string;
  SCSNorm: TSCSNorm;
  FormMode: TFormMode;
begin
  SCSNorm := nil;
  ExistsResourcesIDsFromCurrNorm := nil;
  if TF_Main(GForm).GDBMode = bkNormBase then
    ExistsResourcesIDsFromCurrNorm := GetExistsResourcesIDsFromCurrNorm;

  SCSNorm := TF_Main(GForm).DM.AddEditNormWithMemTable(AMakeEdit, GIDComponent,
    TF_Main(GForm).DM.MemTable_NormsEd, FNBCurrency, FCurrency, false);

  //*** Занести ресурсы в список удаленных
  if SCSNorm <> nil then
  begin
    if AMakeEdit = meMake then
    begin
      SCSNorm.ID := GenNewID(tkNormEd);
      TF_Main(GForm).DM.MemTable_NormsEd.Edit;
      TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnID).AsInteger := SCSNorm.ID;
      //added by Tolik
      TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnKolvo).AsFloat := TF_Main(GForm).DM.GetExpenceFromIzm(SCSNorm.Izm_);
      //
      TF_Main(GForm).DM.MemTable_NormsEd.Post;
    end;

    TF_Main(GForm).DM.CalcNormTatalCostInMT(TF_Main(GForm).DM.MemTable_NormsEd, FTraccaLength);

    if ExistsResourcesIDsFromCurrNorm <> nil then
      GDeletedResourceID.Assign(ExistsResourcesIDsFromCurrNorm, laOr);
    SCSNorm.Free;
    CalcNormCost;
  end;
  if ExistsResourcesIDsFromCurrNorm <> nil then
    FreeAndNil(ExistsResourcesIDsFromCurrNorm);

  {
  FormMode := fmNone;

  case AMakeEdit of
    meMake:
      FormMode := fmMake;
    meEdit:
      FormMode := fmEdit;
  end;

  //case AMakeEdit of
  //  meMake:
  //    begin
  //      FormMode := fmMake;
  //      F_NormBase.F_CaseForm.SpinEdit_Kolvo.Value := 1;
  //    end;
  //  meEdit:
  //    begin
  //      FormMode := fmEdit;
  //      //if GLength = 0 then
  //        F_NormBase.F_CaseForm.SpinEdit_Kolvo.Value := TF_Main(GForm).DM.MemTable_NormsEd.FieldByName('Kolvo').AsFloat
  //    end;
  //end;

  //if GLength > 0 then
  //  begin
  //      F_NormBase.F_CaseForm.SpinEdit_Kolvo.Value := GLength;
  //      F_NormBase.F_CaseForm.SpinEdit_Kolvo.Properties.ReadOnly := true;
  //      //F_NormBase.F_CaseForm.Label_CaptLength.Visible := true;
  //  end
  //else
    begin
        F_NormBase.F_CaseForm.SpinEdit_Kolvo.Properties.ReadOnly := false;
        //F_NormBase.F_CaseForm.Label_CaptLength.Visible := false;
    end;

  //F_NormBase.F_CaseForm.GViewKind := vkNorm;
  //ModRes := F_NormBase.F_CaseForm.ShowModal;

  SCSNorm := nil;
  GUIDNorm := TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnGuidNB).AsString;
  if TF_Main(GForm).GDBMode = bkNormBase then
  begin
    with TF_Main(GForm) do
    begin
      //if ModRes = mrOk then
      F_NormBase.F_CaseForm.GGUIDToLocate := GUIDNorm;
      if F_NormBase.F_CaseForm.Execute(vkNorm, FormMode) then
      begin
        //*** Занести ресурсы в список удаленных
        if AMakeEdit = meEdit then
          DelResourcesFromCurrNorm;

        ID_Norm := F_NormBase.DM.DataSet_NB_NORMS.FN('ID').AsInteger;
        SCSNorm := TSCSNorm.Create(TF_Main(GForm).FNormBase, ntNB);
        SCSNorm.LoadNorm(ID_Norm, true);
      end;
    end;
  end
  else
  if TF_Main(GForm).GDBMode = bkProjectManager then
  begin
    if ShowCurrProjectProperties(vkNorm, GUIDNorm) then
      if FProjSpravochnik.LastNorm <> nil then
      begin
        SCSNorm := TSCSNorm.Create(GForm, ntNB);
        SCSNorm.ID := FProjSpravochnik.LastNorm.ID;
        SCSNorm.GuidNB := FProjSpravochnik.LastNorm.GUID;
        SCSNorm.Cypher := FProjSpravochnik.LastNorm.Cypher;
        SCSNorm.Name := FProjSpravochnik.LastNorm.Name;
        SCSNorm.Izm := FProjSpravochnik.LastNorm.Izm;
        //SCSNorm.GUIDESmeta := FProjSpravochnik.LastNorm.GUIDESmeta
      end;
  end;

  if SCSNorm <> nil then
  begin
    SCSNorm.IDMaster := GIDComponent; // FIDMaster;

    //*** Преобразование валют
    SCSNorm.RefreshPricesAfterChangeCurrency(FNBCurrency, FCurrency, false);
    SCSNorm.IsFromInterface := biFalse;

    TF_Main(GForm).DM.LoadFromNormToMT(SCSNorm, TF_Main(GForm).DM.MemTable_NormsEd, AMakeEdit, 1, nil);
    SCSNorm.Free;
    CalcNormCost;
  end;}
end;

procedure TF_AddComponent.AddEditResource(AMakeEdit: TMakeEdit; AMemoryTableKind: TTableKind; AMakeFromCompon: Boolean);
var
  //ID_ResourceRel: Integer;
  //ModRes: TModalResult;
  ResourceRel: TSCSResourceRel;
  FormMode: TFormMode;
  ResourceMemTable: TkbmMemTable;
  GUIDNB: string;
begin
  ResourceRel := nil;

  ResourceMemTable := TF_Main(GForm).DM.GetMemTableByMemoryTableKind(AMemoryTableKind);

  ResourceRel := TF_Main(GForm).DM.AddEditResourceWithMemTable(AMakeEdit, GIDComponent, FIDCatalog,
    ResourceMemTable, AMemoryTableKind, FNBCurrency, FCurrency, AMakeFromCompon, false);

  if ResourceRel <> nil then
  begin
    if AMakeEdit = meMake then
    begin
      ResourceRel.ID := GenNewID(tkResourceRelEd);
      ResourceMemTable.Edit;
      ResourceMemTable.FieldByName(fnID).AsInteger := ResourceRel.ID;
      ResourceMemTable.Post;
    end;

    TF_Main(GForm).DM.CalcNormTatalCostInMT(TF_Main(GForm).DM.MemTable_NormsEd, FTraccaLength);

    ResourceRel.Free;

    if AMemoryTableKind = tkResourceRelEd then
      CalcNormCost
    else
      CalcWorkCost;
  end;

  {
  FormMode := fmNone;
  ResourceMemTable := TF_Main(GForm).DM.GetMemTableByMemoryTableKind(AMemoryTableKind);

  case AMakeEdit of
    meMake:
      FormMode := fmMake;
    meEdit:
      begin
        FormMode := fmEdit;
      end;
  end;

  //F_NormBase.F_CaseForm.GViewKind := vkResource;
  //ModRes := F_NormBase.F_CaseForm.ShowModal;

  GUIDNB := ResourceMemTable.FieldByName(fnGuidNB).AsString;

  ResourceRel := nil;
  if TF_Main(GForm).GDBMode = bkNormBase then
  begin
    if AMakeEdit = meEdit then
      F_NormBase.F_CaseForm.SpinEdit_Kolvo.Value := Round3(ResourceMemTable.FieldByName(fnKolvo).AsFloat);
    //if GLength > 0 then
    //  begin
    //      F_NormBase.F_CaseForm.SpinEdit_Kolvo.Value := GLength;
    //      F_NormBase.F_CaseForm.SpinEdit_Kolvo.Properties.ReadOnly := true;
    //      //F_NormBase.F_CaseForm.Label_CaptLength.Visible := true;
    //  end
    //else
    begin
        F_NormBase.F_CaseForm.SpinEdit_Kolvo.Properties.ReadOnly := false;
        //F_NormBase.F_CaseForm.Label_CaptLength.Visible := false;
    end;

    with TF_Main(GForm) do
    begin
      //if ModRes = mrOk then
      F_NormBase.F_CaseForm.GGUIDToLocate := GUIDNB;

      if F_NormBase.F_CaseForm.Execute(vkResource, FormMode) then
      begin
        ResourceRel := TSCSResourceRel.Create(GForm, ntNB);
        //Resource.ID := F_NormBase.DM.DataSet_NB_RESOURCES.FN('ID').AsInteger;

        //ResourceRel.IDMaster := DM.MemTable_NormsEd.FieldByName('Id').AsInteger;

        //ResourceRel.IDResource := F_NormBase.DM.DataSet_NB_RESOURCES.FN('ID').AsInteger;
        ResourceRel.IDNB := F_NormBase.DM.DataSet_NB_RESOURCES.FN('ID').AsInteger;

        ResourceRel.GuidNB := F_NormBase.DM.DataSet_NB_RESOURCES.FN(fnGUID).AsString;
        ResourceRel.Cypher := F_NormBase.DM.DataSet_NB_RESOURCES.FN('Cypher').AsString;
        ResourceRel.Name := F_NormBase.DM.DataSet_NB_RESOURCES.FN('Name').AsString;
        ResourceRel.Izm := F_NormBase.DM.DataSet_NB_RESOURCES.FN('Izm').AsString;
        ResourceRel.Price := F_NormBase.DM.DataSet_NB_RESOURCES.FN('Price').AsFloat;
        ResourceRel.AdditionalPrice := F_NormBase.DM.DataSet_NB_RESOURCES.FN(fnAdditionalPrice).AsFloat;
        ResourceRel.RType := F_NormBase.DM.DataSet_NB_RESOURCES.FN('RType').AsInteger;

        ResourceRel.Kolvo := F_NormBase.F_CaseForm.SpinEdit_Kolvo.Value;
        ResourceRel.Cost := ResourceRel.Price * ResourceRel.Kolvo; //F_NormBase.DM.DataSet_NB_RESOURCES.FN('Cost').AsFloat;

        ResourceRel.RefreshPricesAfterChangeCurrency(FNBCurrency, FCurrency, false);
      end;
    end;
  end
  else
  if TF_Main(GForm).GDBMode = bkProjectManager then
  begin
    if ShowCurrProjectProperties(vkResource, GUIDNB) then
      if FProjSpravochnik.LastResource <> nil then
      begin
        ResourceRel := TSCSResourceRel.Create(GForm, ntNB);

        ResourceRel.IDResource := FProjSpravochnik.LastResource.ID;
        ResourceRel.GuidNB := FProjSpravochnik.LastResource.GUID;
        ResourceRel.Cypher := FProjSpravochnik.LastResource.Cypher;
        ResourceRel.Name := FProjSpravochnik.LastResource.Name;
        ResourceRel.Izm := FProjSpravochnik.LastResource.Izm;
        ResourceRel.Price := FProjSpravochnik.LastResource.Price;
        ResourceRel.AdditionalPrice := 0;
        ResourceRel.RType := FProjSpravochnik.LastResource.RType;

        ResourceRel.Kolvo := 1;
        ResourceRel.Cost := ResourceRel.Price * ResourceRel.Kolvo;
      end;
  end;

  if ResourceRel <> nil then
  begin
    //*** Определить таблицу владельца ресурса
    case AMemoryTableKind of
      tkNormEd:
          ResourceRel.MasterTableKind := ctkComponent; //GMasterTableKind;
      tkResourceRelEd:
          ResourceRel.MasterTableKind := ctkNorm;
    end;
    ResourceRel.IDMaster := GIDComponent;
    ResourceRel.TableKindNB := ctkNBResources;
    ResourceRel.IsOn := 1;

    TF_Main(GForm).DM.LoadFromResourceToMT(ResourceRel, ResourceMemTable, AMakeEdit, AMemoryTableKind, nil);  //LoadFromResourceToMT(ResourceRel, AMakeEdit, AMemoryTableKind);
    ResourceRel.Free;

    if AMemoryTableKind = tkResourceRelEd then
      CalcNormCost
    else
      CalcWorkCost;
  end;}
end;

// ##### Вернет новую позицию #####

function TF_AddComponent.GetNewNPP(AMemTable: TkbmMemTable): Integer;
var
  RecordNo: Integer;
  MaxNPP: Integer;
begin
  Result := 1;
  // Tolik 28/12/2019 --
  MaxNPP := 0;
  if AMemTable.RecordCount > 0 then
  //
  begin
    with AMemTable do
    begin
      RecordNo := RecNo;
      First;
      MaxNPP := FieldByName('NPP').AsInteger;
      while not Eof do
      begin
        if FieldByName('NPP').AsInteger > MaxNPP then
          MaxNPP := FieldByName('NPP').AsInteger;
        Next;
      end;
      RecNo := RecordNo;
    end;
  end;
  Result := MaxNPP + 1;
end;
{
// ##### Здвигает порядковые номера после ANPPAfter на -1 #####
procedure TF_AddComponent.SdvigNPP(ANPPAfter: Integer; AMemTable: TkbmMemTable);
var
  RecordNo: Integer;
  NewNPP: Integer;
begin
  try
    if (AMemTable = nil) or (AMemTable.Active = false) then
      Exit; ///// EXIT /////

    RecordNo := AMemTable.RecNo;
    AMemTable.First;
    while not AMemTable.Eof do
    begin
      if AMemTable.FieldByName(fnNpp).AsInteger > ANPPAfter then
      begin
        NewNPP := AMemTable.FieldByName(fnNpp).AsInteger - 1;
        AMemTable.Edit;
        AMemTable.FieldByName(fnNpp).AsInteger := NewNPP;
        AMemTable.FieldByName(fnisModified).AsBoolean := true;
        AMemTable.Post;
      end;
      AMemTable.Next;
    end;
    AMemTable.RecNo := RecordNo;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.SdvigNPP: ' + E.Message);
  end;
end;}

(*
// ##### Подгружает ресурсы #####
procedure TF_AddComponent.LoadFromResourceToMT(AResource: TSCSResourceRel; AMakeEdit: TMakeEdit; AMemoryTableKind: TTableKind);
var
  TrgMemTable: TkbmMemTable;
  NewNpp: Integer;
begin
  try
    TrgMemTable := nil;
    with TF_Main(GForm).DM do
      TrgMemTable := GetMemTableByMemoryTableKind(AMemoryTableKind);
    if TrgMemTable = nil then
      Exit; //// EXIT ////

    case AMakeEdit of
      meMake:
          begin
              NewNpp := GetNewNPP(TrgMemTable);
              TrgMemTable.Append;
              TrgMemTable.FieldByName('Npp').AsInteger := NewNpp;
              if AMemoryTableKind = tkNormEd then
                TrgMemTable.FieldByName(fnIsResource).AsBoolean := true;
          end;
      meEdit: TrgMemTable.Edit;
      meNone:
          begin
              TrgMemTable.Append;
              TrgMemTable.FieldByName('id').AsInteger := AResource.ID;
              TrgMemTable.FieldByName('id_master').AsInteger := AResource.IDMaster;
              TrgMemTable.FieldByName('Npp').AsInteger := AResource.Npp;
              if AMemoryTableKind = tkNormEd then
                TrgMemTable.FieldByName(fnIsResource).AsBoolean := true;
          end;
    end;
    TrgMemTable.FieldByName('Table_Kind').AsInteger := AResource.MasterTableKind;

    if AMakeEdit <> meEdit then
      TrgMemTable.FieldByName('id_resource').AsInteger := AResource.IDResource;
    TrgMemTable.FieldByName('id_nb').AsInteger := AResource.IDNB;
    TrgMemTable.FieldByName(fnGuidNB).AsString := AResource.GuidNB;
    TrgMemTable.FieldByName('table_kind_nb').AsInteger := AResource.TableKindNB;

    TrgMemTable.FieldByName('kolvo').AsFloat := RoundCP(AResource.Kolvo);
    TrgMemTable.FieldByName('ison').AsInteger := AResource.IsOn;

    TrgMemTable.FieldByName('Cypher').AsString := AResource.Cypher;
    TrgMemTable.FieldByName('Name').AsString := AResource.Name;
    TrgMemTable.FieldByName('Izm').AsString := AResource.Izm;
    case AMemoryTableKind of
      tkResourceRelEd:
        begin
            TrgMemTable.FieldByName('Price').AsFloat := RoundCP(AResource.Price);
            TrgMemTable.FieldByName(fnAdditionalPrice).AsFloat := RoundCP(AResource.AdditionalPrice);
            TrgMemTable.FieldByName('Cost').AsFloat := RoundCP(AResource.Cost);
        end;
      tkNormEd:
        begin
            TrgMemTable.FieldByName('Cost').AsFloat := RoundCP(AResource.Price);
            TrgMemTable.FieldByName('Total_Cost').AsFloat := RoundCP(AResource.Cost);
        end;
    end;
    TrgMemTable.FieldByName(fnExpenseForLength).AsFloat := RoundCP(AResource.ExpenseForLength);

    TrgMemTable.FieldByName('RType').AsInteger := AResource.RType;
    case AMakeEdit of
      meNone:
          begin
              TrgMemTable.FieldByName('isModified').AsBoolean := false;
              TrgMemTable.FieldByName('isNew').AsBoolean := false;
          end;
      meMake:
          TrgMemTable.FieldByName('isNew').AsBoolean := true;
      meEdit:
          TrgMemTable.FieldByName('isModified').AsBoolean := true;
    end;
    TrgMemTable.Post;

    {with TF_Main(GForm).DM do
      begin
          case AMakeEdit of
            meMake : MemTable_ResourcesRelEd.Append;
            meEdit: MemTable_ResourcesRelEd.Edit;
            meNone:
                begin
                    MemTable_ResourcesRelEd.Append;
                    MemTable_ResourcesRelEd.FieldByName('id').AsInteger := AResource.ID;
                    MemTable_ResourcesRelEd.FieldByName('id_master').AsInteger := AResource.IDMaster;
                end;
          end;
          MemTable_ResourcesRelEd.FieldByName('id_resource').AsInteger := AResource.IDResource;
          MemTable_ResourcesRelEd.FieldByName('kolvo').AsFloat := AResource.Kolvo;
          MemTable_ResourcesRelEd.FieldByName('ison').AsInteger := AResource.IsOn;

          MemTable_ResourcesRelEd.FieldByName('Cypher').AsString := AResource.Cypher;
          MemTable_ResourcesRelEd.FieldByName('Name').AsString := AResource.Name;
          MemTable_ResourcesRelEd.FieldByName('Izm').AsString := AResource.Izm;
          MemTable_ResourcesRelEd.FieldByName('Price').AsFloat := AResource.Price;
          MemTable_ResourcesRelEd.FieldByName('Cost').AsFloat := AResource.Cost;
          MemTable_ResourcesRelEd.FieldByName('RType').AsInteger := AResource.RType;
          case AMakeEdit of
            meNone:
                begin
                    MemTable_ResourcesRelEd.FieldByName('isModified').AsBoolean := false;
                    MemTable_ResourcesRelEd.FieldByName('isNew').AsBoolean := false;
                end;
            meMake:
                MemTable_ResourcesRelEd.FieldByName('isNew').AsBoolean := true;
            meEdit:
                MemTable_ResourcesRelEd.FieldByName('isModified').AsBoolean := true;
          end;
          MemTable_ResourcesRelEd.Post;
      end; }
  except
    on E: Exception do AddExceptionToLog('TF_AddComponent.LoadResourceToMT: '+E.Message);
  end;
end;

procedure TF_AddComponent.LoadFromNormToMT(ASCSNorm: TSCSNorm; AMakeEdit: TMakeEdit; AKolvo: Double);
var
  i: Integer;
  ResourceRel: TSCSResourceRel;
  NewNpp: Integer;
begin
  NewNpp := 0;
  with TF_Main(GForm).DM do
  begin
      case AMakeEdit of
        meMake:
            begin
              NewNpp := GetNewNPP(MemTable_NormsEd);
              MemTable_NormsEd.Append;
            end;
        meEdit:
            MemTable_NormsEd.Edit;
        meNone:
            MemTable_NormsEd.Append;
      end;
      MemTable_NormsEd.FieldByName('ID_Master').AsInteger := GIDComponent; //FIDMaster;
      MemTable_NormsEd.FieldByName(fnIDNB).AsInteger := ASCSNorm.IDNB;
      MemTable_NormsEd.FieldByName(fnGuidNB).AsString := ASCSNorm.GuidNB;
      MemTable_NormsEd.FieldByName('TABLE_KIND').AsInteger := ctkComponent; //GMasterTableKind;
      MemTable_NormsEd.FieldByName('Cypher').AsString := ASCSNorm.Cypher;
      MemTable_NormsEd.FieldByName('Name').AsString := ASCSNorm.Name;
      MemTable_NormsEd.FieldByName('Work_Kind').AsString := ASCSNorm.WorkKind;
      MemTable_NormsEd.FieldByName('Izm').AsString := ASCSNorm.Izm;
      MemTable_NormsEd.FieldByName('Cost').AsFloat := RoundCP(ASCSNorm.Cost);
      MemTable_NormsEd.FieldByName('Total_Cost').AsFloat := RoundCP(ASCSNorm.TotalCost);  //ASCSNorm.Cost * ASCSNorm.Kolvo;
      MemTable_NormsEd.FieldByName(fnExpenseForLength).AsFloat := RoundCP(ASCSNorm.ExpenseForLength);
      //MemTable_NormRel.FieldByName('Zarplat').AsFloat := F_NormBase.DM.Query.FN('Zarplat').AsFloat;

      MemTable_NormsEd.FieldByName(fnIsFromInterface).AsInteger := ASCSNorm.IsFromInterface;

      case AMakeEdit of
        meNone:
            begin
                MemTable_NormsEd.FieldByName('ID').AsInteger := ASCSNorm.ID;
                MemTable_NormsEd.FieldByName('NPP').AsInteger := ASCSNorm.NPP;
                MemTable_NormsEd.FieldByName('ISON').AsInteger := ASCSNorm.IsOn;
                MemTable_NormsEd.FieldByName('Kolvo').AsFloat := RoundX(ASCSNorm.Kolvo, PrecisionNormKolvo);

                MemTable_NormsEd.FieldByName(fnIsResource).AsBoolean := false;
                MemTable_NormsEd.FieldByName('isModified').AsBoolean := false;
                MemTable_NormsEd.FieldByName('isNew').AsBoolean := false;
            end;
        meMake:
            begin
                MemTable_NormsEd.FieldByName('NPP').AsInteger := NewNpp;
                MemTable_NormsEd.FieldByName('ISON').AsInteger := 1;
                MemTable_NormsEd.FieldByName('Kolvo').AsFloat := RoundCP(AKolvo);
                MemTable_NormsEd.FieldByName(fnIsResource).AsBoolean := false;
                MemTable_NormsEd.FieldByName('isNew').AsBoolean := true;
            end;
        meEdit:
            begin
                MemTable_NormsEd.FieldByName('Kolvo').AsFloat := RoundCP(AKolvo);
                MemTable_NormsEd.FieldByName('isModified').AsBoolean := true;
            end;
      end;
      MemTable_NormsEd.Post;
  end;

  for i := 0 to ASCSNorm.Resources.Count - 1 do
    begin
        ResourceRel := ASCSNorm.Resources.Items[i];
        LoadFromResourceToMT(ResourceRel, AMakeEdit, tkResourceRelEd);
    end;
end;

procedure TF_AddComponent.LoadFromMTToResource(AMemoryTableKind: TTableKind; AResourceRel: TSCSResourceRel);
var
  TrgMemTable: TkbmMemTable;
begin
  try
    if AResourceRel = nil then
      Exit; /// EXIT ///

    TrgMemTable := nil;
    with TF_Main(GForm).DM do
      case AMemoryTableKind of
        tkResourceRelEd:
          TrgMemTable := MemTable_ResourcesRelEd;
        tkNormEd:
          TrgMemTable := MemTable_NormsEd;
      end;
    if TrgMemTable = nil then
      Exit; //// EXIT ////

    AResourceRel.ID := TrgMemTable.FieldByName('id').AsInteger;
    AResourceRel.IDMaster := TrgMemTable.FieldByName('id_master').AsInteger;
    AResourceRel.MasterTableKind := TrgMemTable.FieldByName('Table_Kind').AsInteger;
    AResourceRel.Npp := TrgMemTable.FieldByName('Npp').AsInteger;
    AResourceRel.IsOn := TrgMemTable.FieldByName('ison').AsInteger;

    AResourceRel.IDResource := TrgMemTable.FieldByName('id_resource').AsInteger;
    AResourceRel.IDNB := TrgMemTable.FieldByName('id_nb').AsInteger;
    AResourceRel.GuidNB := TrgMemTable.FieldByName(fnGuidNB).AsString;
    AResourceRel.TableKindNB := TrgMemTable.FieldByName('table_kind_nb').AsInteger;

    AResourceRel.Kolvo := RoundCP(TrgMemTable.FieldByName('kolvo').AsFloat);

    AResourceRel.Cypher := TrgMemTable.FieldByName('Cypher').AsString;
    AResourceRel.Name  := TrgMemTable.FieldByName('Name').AsString;
    AResourceRel.Izm := TrgMemTable.FieldByName('Izm').AsString;
    case AMemoryTableKind of
      tkResourceRelEd:
        begin
          AResourceRel.Price := RoundCP(TrgMemTable.FieldByName('Price').AsFloat);
          AResourceRel.AdditionalPrice := RoundCP(TrgMemTable.FieldByName(fnAdditionalPrice).AsFloat);
          AResourceRel.Cost := RoundCP(TrgMemTable.FieldByName('Cost').AsFloat);
        end;
      tkNormEd:
        begin
          AResourceRel.Price := RoundCP(TrgMemTable.FieldByName('Cost').AsFloat);
          AResourceRel.Cost := RoundCP(TrgMemTable.FieldByName('Total_Cost').AsFloat);
        end;
    end;
    AResourceRel.ExpenseForLength := RoundCP(TrgMemTable.FieldByName(fnExpenseForLength).AsFloat);

    AResourceRel.RType := TrgMemTable.FieldByName('RType').AsInteger;
    AResourceRel.IsModified := TrgMemTable.FieldByName('isModified').AsBoolean;
    AResourceRel.IsNew := TrgMemTable.FieldByName('isNew').AsBoolean;
  except
    on E: Exception do AddExceptionToLog('TF_AddComponent.LoadFromMTToResource: '+E.Message);
  end;
end;

procedure TF_AddComponent.LoadFromMTToNorm(ASCSNorm: TSCSNorm);
begin
  with TF_Main(GForm).DM do
  begin
    ASCSNorm.ID := MemTable_NormsEd.FieldByName('ID').AsInteger;
    ASCSNorm.IDMaster := MemTable_NormsEd.FieldByName('ID_Master').AsInteger;
    ASCSNorm.IDNB := MemTable_NormsEd.FieldByName(fnIDNB).AsInteger;
    ASCSNorm.GuidNB := MemTable_NormsEd.FieldByName(fnGuidNB).AsString;
    ASCSNorm.MasterTableKind := MemTable_NormsEd.FieldByName('TABLE_KIND').AsInteger;

    ASCSNorm.NPP := MemTable_NormsEd.FieldByName('NPP').AsInteger;
    ASCSNorm.IsOn := MemTable_NormsEd.FieldByName('ISON').AsInteger;
    ASCSNorm.Kolvo := RoundX(MemTable_NormsEd.FieldByName('Kolvo').AsFloat, PrecisionNormKolvo);

    ASCSNorm.Cypher := MemTable_NormsEd.FieldByName('Cypher').AsString;
    ASCSNorm.Name := MemTable_NormsEd.FieldByName('Name').AsString;
    ASCSNorm.WorkKind := MemTable_NormsEd.FieldByName('Work_Kind').AsString;
    ASCSNorm.Izm := MemTable_NormsEd.FieldByName('Izm').AsString;
    ASCSNorm.Cost := RoundCP(MemTable_NormsEd.FieldByName('Cost').AsFloat);
    ASCSNorm.TotalCost := RoundCP(MemTable_NormsEd.FieldByName('Total_Cost').AsFloat);
    ASCSNorm.ExpenseForLength := RoundCP(MemTable_NormsEd.FieldByName(fnExpenseForLength).AsFloat);
    //MemTable_NormRel.FieldByName('Zarplat').AsFloat := F_NormBase.DM.Query.FN('Zarplat').AsFloat;
    ASCSNorm.IsFromInterface := MemTable_NormsEd.FieldByName(fnIsFromInterface).AsInteger;

    ASCSNorm.IsModified := MemTable_NormsEd.FieldByName('isModified').AsBoolean;
    ASCSNorm.IsNew := MemTable_NormsEd.FieldByName('isNew').AsBoolean;
  end;
end;  *)

procedure TF_AddComponent.OncbApplyForChange(Sender: TObject);
var
  ApplyCheckBoxBorderColor: TColor;
  ApplyCheckBoxBorderStyle: TcxEditBorderStyle;
begin
  ApplyCheckBoxBorderColor := FApplyCheckBoxesBorderColor;
  ApplyCheckBoxBorderStyle := FApplyCheckBoxesBorderStyle;
  if not TRzCheckBox(Sender).Checked then
  begin
    ApplyCheckBoxBorderColor := clWindowFrame;
    ApplyCheckBoxBorderStyle := ebsUltraFlat;
  end;
  pnApplyNormsResources.Visible := TRzCheckBox(Sender).Checked;

  //TcxCheckBox(Sender).Style.BorderColor := ApplyCheckBoxBorderColor;
  //TcxCheckBox(Sender).Style.BorderStyle := ApplyCheckBoxBorderStyle;
  //VisibleApplyCheckBoxes(TcxCheckBox(Sender).Checked, false);

  //TRzCheckBox(Sender).Style.BorderColor := ApplyCheckBoxBorderColor;
  //TRzCheckBox(Sender).Style.BorderStyle := ApplyCheckBoxBorderStyle;

  TRzCheckBox(Sender).Font.Color := ApplyCheckBoxBorderColor;
  VisibleApplyCheckBoxes(TRzCheckBox(Sender).Checked, false);


end;

procedure TF_AddComponent.OncbApplyForPMChange(Sender: TObject);
begin
  OncbApplyForChange(Sender);
  EnableDisableApplyIncludingMark; //17.08.2012
  cbApplyForOnlySelected.Enabled := CheckBox_ApplyForList.Checked or CheckBox_ApplyForProject.Checked;
end;

procedure TF_AddComponent.SetGenLastID(ATableKind: TTableKind);
//var LastID: Integer;
var
  GDBMode: TDBKind;
begin
  //LastID := -1;
  //with TF_Main(GForm).DM do
  GDBMode := TF_Main(GForm).GDBMode;
  case ATableKind of
    tkCableCanalConnectorsED:
      GGenLastCableCanalConnectorID := GetLastCableCanalConnectorID(GDBMode);
    tkCompPropRelED:
      GGenLastCompPropRelID := GetLastCompPropRelID(GDBMode);
    tkCrossConnectionED:
      if GDBMode = bkNormBase then
        GGenLastCrossConnectionID := GenIDFromTable(TF_Main(GForm).DM.Query_Select, gnCrossConnectionID, 0)
      else
        GGenLastCrossConnectionID := 0;
    tkInterfRelED:
      GGenLastInterfID := GetLastInterfRelID(GDBMode);
    tkPortInterfRelED:
      GGenLastPortInterfRelID := GetLastPortInterfRelID(GDBMode);
    tkNormEd:
      GGenLastNormID := GetLastNormID(GDBMode);
    tkResourceRelEd:
      GGenLastResourceID := GetLastNormResourceID(GDBMode);
  end;

  //if LastID <> -1 then
  //  GGenLastInterfID := LastID;
end;

function TF_AddComponent.GetMaxNumPair(AMemTable: TkbmMemTable): Integer;
var
  CurrMaxNumPair: Integer;
begin
  Result := 0;
  CurrMaxNumPair := 0;
  AMemTable.First;
  while not AMemTable.Eof do
  begin
    if AMemTable.FieldByName(fnNumPair).AsInteger > CurrMaxNumPair then
      CurrMaxNumPair := AMemTable.FieldByName(fnNumPair).AsInteger;
    AMemTable.Next;
  end;
  Result := CurrMaxNumPair;
end;

function TF_AddComponent.GenNewID(ATableKind: TTableKind): Integer;
begin
  Result := 0;
  case ATableKind of
    tkCableCanalConnectorsED:
      begin
        Inc(GGenLastCableCanalConnectorID);
        Result := GGenLastCableCanalConnectorID
      end;
    tkCompPropRelED:
      begin
        Inc(GGenLastCompPropRelID);
        Result := GGenLastCompPropRelID
      end;
    tkCrossConnectionED:
      begin
        Inc(GGenLastCrossConnectionID);
        Result := GGenLastCrossConnectionID
      end;
    tkInterfRelED, tkPortEd:
      begin
        Inc(GGenLastInterfID);
        Result := GGenLastInterfID;
      end;
    tkPortInterfRelED:
      begin
        Inc(GGenLastPortInterfRelID);
        Result := GGenLastPortInterfRelID
      end;
    tkNormEd:
      begin
        Inc(GGenLastNormID);
        Result := GGenLastNormID;
      end;
    tkResourceRelEd:
      begin
        Inc(GGenLastResourceID);
        Result := GGenLastResourceID;
      end;
  end;
end;

{
function TF_AddComponent.GetStrWithoutSpaces(AString: String): String;
var ResStr: String;
    i: Integer;
    LenStr: Integer;
    ResStrIndex: Integer;
begin
    LenStr := Length(AString);
    ResStrIndex := 0;
    for i := 1 to LenStr do
      begin
          if Ord(AString[i]) <> 160 then
            begin
                ResStrIndex := ResStrIndex + 1;
                SetLength(ResStr, ResStrIndex);
                ResStr[ResStrIndex] := AString[i];
            end;
      end;
    Result := ResStr;
end; }

procedure TF_AddComponent.AddApplyCheckBoxToList(ACheckBox: TcxCheckBox; APageIndex: Integer);
begin
  FApplyCheckBoxes.Add(ACheckBox);
  FApplyCheckBoxesPageIndex.Add(APageIndex);
end;

function TF_AddComponent.CheckRequiredProperties: Boolean;
var
  //MemTableBookmark: string;
  MemTableBookmark: TbookMark;
  MemTable: TkbmMemTable;
  Prop: TProperty;
  MessageStr: string;
  PropSysNamesToDel: TStringList;
  CanEditProp: Boolean;
  RelatedPortPropSysName: String;
begin
  Result := true;
  try
    PropSysNamesToDel := TStringList.Create;

    MemTable := TF_Main(GForm).DM.MemTable_PropertyEd;
    //MemTableBookmark := MemTable.Bookmark;
    MemTableBookmark := MemTable.GetBookmark;
    MemTable.DisableControls;
    try
      MemTable.First;
      while Not MemTable.Eof do
      begin
        Prop := TF_Main(GForm).DM.GetPropertyFromTable(nil, MemTable);

        // Если это свойство обезательное и не предназначено для удаления
        if (GPropRequired.IndexOf(Prop.SysName) <> -1) and
           (PropSysNamesToDel.IndexOf(Prop.SysName) = -1) then
        begin
          MessageStr := '';
          case Prop.IDDataType of
            dtInteger:
              if StrToIntDef(Prop.Value, 0) <= 0 then
                MessageStr := cAddComponent_Msg22_1 +' "'+Prop.Name_+'" '+cAddComponent_Msg22_2;
            dtFloat:
              if StrToFloatDefU(Prop.Value, 0) <= 0 then
                MessageStr := cAddComponent_Msg22_1 +' "'+Prop.Name_+'" '+cAddComponent_Msg22_2;
            dtCableCanalElementType:
              if StrToIntDef(Prop.Value, contNone) = contNone then
                MessageStr := cAddComponent_Msg22_1 +' "'+Prop.Name_+'" '+cAddComponent_Msg22_3;
            dtDimensions:
              if Prop.Value = '' then
                MessageStr := cAddComponent_Msg22_1 +' "'+Prop.Name_+'" '+cAddComponent_Msg22_3;
          end;

          if MessageStr <> '' then
          begin
            // Если это свойство кол-во портов, или жил на порт, спрашиваем будет ли комплектоваться этот компонент
            RelatedPortPropSysName := '';
            if Prop.SysName = pnPortCount then
              RelatedPortPropSysName := pnPortWireCount
            else
            if Prop.SysName = pnPortWireCount then
              RelatedPortPropSysName := pnPortCount;


            //MemTableBookmark := MemTable.Bookmark;

            pcMain.ActivePage := tsCommon;
            Grid.ActiveLevel := GL_Property;
            Application.ProcessMessages;
            Sleep(100);

            MemTable.EnableControls;
            CanEditProp := true;

            // Если это свойство касается порта, то задаем вопрос на счет комплектации этого компонента
            if (RelatedPortPropSysName <> '') and Not FIsTemplate and (FCurrComponentType.IsLine = biFalse) then
            begin
              if MessageQuastYN(cAddComponent_Msg26_1 + snNextRow+
                  '(' +cAddComponent_Msg26_2 + ' "'+Prop.Name_+'")' ) = IDYES then
              begin
                CanEditProp := false;
                PropSysNamesToDel.Add(Prop.SysName);
                PropSysNamesToDel.Add(RelatedPortPropSysName);
              end;
            end
            else
              MessageInfo(MessageStr);
            Application.ProcessMessages;

            // Редактируем свойство
            if CanEditProp then
            begin
              AddEditProperty(meEdit);
              Result := false;
            end;

            Break; //// BREAK ////
          end;
        end;
        MemTable.Next;
      end;
    finally
      MemTable.EnableControls;
      //MemTable.Bookmark := MemTableBookmark;
      if MemTableBookmark <> nil then
      begin
        MemTable.GotoBookmark(MemTableBookmark);
        MemTable.FreeBookmark(MemTableBookmark);
      end;
    end;

    if PropSysNamesToDel.Count > 0 then
      DelPropsBySysNames(PropSysNamesToDel);

    FreeAndNil(PropSysNamesToDel);
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.CheckRequiredProperties', E.Message);
  end;
end;

procedure TF_AddComponent.ClearFormGrids;
begin
  TF_Main(GForm).DM.MemTable_InterfaceRelEd.Active := false;
  TF_Main(GForm).DM.MemTable_InterfaceRelEd.Active := True;

  TF_Main(GForm).DM.MemTable_InterfOfInterf_RelEd.Active := false;
  TF_Main(GForm).DM.MemTable_InterfOfInterf_RelEd.Active := True;

  TF_Main(GForm).DM.MemTable_PortEd.Active := false;
  TF_Main(GForm).DM.MemTable_PortEd.Active := True;

  TF_Main(GForm).DM.MemTable_PortInterfRelEd.Active := false;
  TF_Main(GForm).DM.MemTable_PortInterfRelEd.Active := True;

  TF_Main(GForm).DM.mtInterfInternalConnEd.Active := false;
  TF_Main(GForm).DM.mtInterfInternalConnEd.Active := true;

  TF_Main(GForm).DM.MemTable_PropertyEd.Active := false;
  TF_Main(GForm).DM.MemTable_PropertyEd.Active := True;

  TF_Main(GForm).DM.MemTable_ComplectsEd.Active := false;
  TF_Main(GForm).DM.MemTable_ComplectsEd.Active := True;

  TF_Main(GForm).DM.MemTable_CableCanalConnectorsEd.Active := false;
  TF_Main(GForm).DM.MemTable_CableCanalConnectorsEd.Active := true;

  TF_Main(GForm).DM.mtCrossConnectionEd.Active := false;
  TF_Main(GForm).DM.mtCrossConnectionEd.Active := true;

  TF_Main(GForm).DM.MemTable_ResourcesRelEd.Active := false;
  TF_Main(GForm).DM.MemTable_NormsEd.Active := false;
  TF_Main(GForm).DM.MemTable_NormsEd.Active := true;
  TF_Main(GForm).DM.MemTable_ResourcesRelEd.Active := true;
end;

procedure TF_AddComponent.ClearPortInterfaceMemTable(AMemTable: TkbmMemTable; AIsPort: Boolean);
var
  i: Integer;
  NumPair: Integer;
  CanDelete: Boolean;
begin
  try
    AMemTable.Last;
    while not AMemTable.Bof do
    begin
      if (AMemTable.FieldByName(fnIsBusy).AsInteger = biFalse) and
         (AMemTable.FieldByName(fnIsNative).AsBoolean = True) then
      begin
        NumPair := 0;
        if not AIsPort then
          NumPair := AMemTable.FieldByName(fnNumPair).AsInteger;

        CanDelete := false;
        if AMemTable.FieldByName(fnIsNew).AsBoolean then
          CanDelete := true
        else if not CheckInterfIsUse(GForm, GIDComponent, AMemTable.FieldByName(fnID).AsInteger, NumPair) then
          CanDelete := true;

        if CanDelete then
        begin
          if (AMemTable.FieldByName(fnIsNew).AsBoolean = false) and
            (AMemTable.FieldByName(fnIsNative).AsBoolean = true) then
            GDeletedInterfRel.Add(AMemTable.FieldByName(fnID).AsInteger);
          AMemTable.Delete;
          Continue; ///// CONTINUE /////
        end;
      end;
      AMemTable.Prior;
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.ClearPortInterfaceMemTable', E.Message);
  end;
end;

function TF_AddComponent.CreateFormOnlyComponent: TSCSComponent;
var
  Stream: TStream;
  ComponentType: TComponentType;
  Price: Double;
begin
  Result := nil;
  //ComponentType := TF_Main(GForm).FNormBase.DM.GetComponentType(GetIDFromComboBox(ComboBox_ComponentType));
  ComponentType := GetComponentType;
  Result := TSCSComponent.Create(GForm);
  try

    if GFormMode = fmEdit then
      Result.ID := GIDComponent;
    Result.Name := Edit_Name.Text;
    Result.NameShort := Edit_NameShort.Text;
    Result.MarkStr := '';//Edit_MarkStr.Text;
    Result.MarkID := Trunc(seIndex.Value);
    Result.Izm := Edit_Izm.Text;
    Result.Notice := Edit_Notice.Text;
    Result.ArticulDistributor := Edit_ArticulDistributor.Text;
    Result.ArticulProducer := Edit_ArticulProducer.Text;

    //if Result.Picture <> nil then
    //  FreeAndNil(Result.Picture);
    //Result.Picture := TMemoryStream.Create;
    try
      Image.Picture.SaveToFile(ComponPictFileName);
      if FileExists(ComponPictFileName) then
      begin
        Stream := TFileStream.Create(ComponPictFileName, fmOpenReadWrite);
        Stream.Position := 0;
        Result.Picture.Position := 0;
        Result.Picture.CopyFrom(Stream, 0);
        Result.Picture.Position := 0;
        FreeAndNil(Stream);
        DeleteFile(PChar(ComponPictFileName));
      end;
    except
      on E: Exception do
        ShowMessage(cAddComponent_Msg5);
    end;

    Result.IsLine := GetIsLineByComponType(ComponentType);
    Result.ISComplect := BoolToint(cbCanComplect.Checked); //1 - RadioGroup_CanComplect.ItemIndex;
    //28.08.2013 if ComponentType.IsLine = biFalse then
    //28.08.2013   Result.IsMarkInCaptions := BoolToint(cbIsMarkInCaptions.Checked)
    //28.08.2013 else
    //28.08.2013   Result.IsMarkInCaptions := biFalse;
    Result.IsMarkInCaptions := BoolToint(cbIsMarkInCaptions.Checked);
    Result.UserLength := FloatInUOM(SpinEdit_UserLength.Value, TF_Main(GForm).FUOM, umMetr);
    Result.ObjectIconStep := 0;//SpinEdit_ObjectIconStep.Value;
    Result.HASNDS := BoolToInt(CheckBox_HasNds.Checked); //1- RadioGroup_HasNds.ItemIndex;
    Price := 0;
    //case RadioGroup_HasNds.ItemIndex of
    //  0: Price  := CurrencyEdit_Price1.Value;
    //  1: Price := PriceWithNDS(CurrencyEdit_Price1.Value, GNDS);
    //end;
    case CheckBox_HasNds.Checked of
      true: Price := CurrencyEdit_Price1.Value;
      false: Price := PriceWithNDS(CurrencyEdit_Price1.Value, TF_Main(GForm).GNDS);
    end;
    if CheckPriceTransformToUOMByCompType(@FCurrComponentType) then
      Price := FloatInUOM(Price, umMetr, TF_Main(GForm).FUOM);
    Result.PRICE_CALC := Price;
    Result.PRICE := Price;
    Result.ID_CURRENCY := GID_CURRENCY;
    Result.ID_Producer := GetIDFromComboBox(ComboBox_Producer);
    Result.ID_ComponentType := GetIDFromComboBox(ComboBox_ComponentType);
    Result.IDObjectIcon := GIDObjectIcon;
    Result.IDSymbol := GIDSymbolImage;
    Result.IDNetType := GetIDFromComboBox(ComboBox_NetType);
    Result.IDCompSpecification := GetIDFromComboBox(cbSpecification);
    Result.IDSuppliesKind := GetIDFromComboBox(cbSuppliesKind);

    Result.GUIDProducer := GetGUIDFromComboBox(ComboBox_Producer);
    Result.GUIDNetType := GetGUIDFromComboBox(ComboBox_NetType);
    Result.ComponentType := ComponentType;
    Result.GUIDComponentType := ComponentType.GUID;
    Result.GUIDObjectIcon := GGUIDObjectIcon;
    Result.GUIDSymbol := GGUIDSymbolImage;
    Result.GUIDSuppliesKind := GetGUIDFromComboBox(cbSuppliesKind);
    if TF_Main(GForm).GDBMode = bkProjectManager then
    begin
      Result.NameMark := Edit_NameMark.Text;
      //Result.IsUserMark := BoolToInt(CheckBox_IsUserMark.Checked);
      Result.IsUserMark := BoolToInt(rbMarkByDefault.Checked);
      Result.IsDismount := BoolToInt(cbDismount.Checked);
      Result.IsUseDismounted := BoolToInt(cbUseDismounted.Checked);
    end;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.CreateFormComponent: ' + E.Message);
  end;
end;

function TF_AddComponent.CreateFormComponent: TSCSComponent;
var
  FormCompon: TSCSComponent;
  Interfaces: TSCSInterfaces;
  Properties: TList;
  CrossConnections: TSCSObjectList;
begin
  Result := nil;
  FormCompon := nil;
  FormCompon := CreateFormOnlyComponent;
  if Assigned(FormCompon) then
  begin
    FormCompon.Interfaces.Clear; //ClearList(FormCompon.Interfaces);
    ClearList(FormCompon.Properties);

    Interfaces := nil;
    Interfaces := CreateFormInterfaces;
    if Assigned(Interfaces) then
    begin
      FormCompon.Interfaces.Assign(Interfaces);
      FreeAndNil(Interfaces);
    end;

    Properties := nil;
    Properties := CreateFormProperties;
    if Assigned(Properties) then
    begin
      FormCompon.Properties.Assign(Properties);
      FreeAndNil(Properties);
    end;

    CrossConnections := nil;
    CrossConnections := CreateFormCrossConnections;
    if Assigned(CrossConnections) then
    begin
      FormCompon.CrossConnections.Assign(CrossConnections);
      CrossConnections.OwnsObjects := false;
      FreeAndNil(CrossConnections);
    end;
  end;
  Result := FormCompon;
end;
// Tolik 28/12/2019 -- старая закомменчена - -см ниже
function TF_AddComponent.CreateFormInterfaces: TSCSInterfaces;
var
  ResList: TSCSInterfaces;
  SavedMasterSource: TDataSource;

  procedure LoadToInterfacesList(AMemTable: TkbmMemTable);
  var
    i, j: Integer;
    RecNo: Integer;
    Interfac: TSCSInterface;
    ComponType: TComponentType;
  begin
    if Assigned(AMemTable) then
    begin
      ComponType := GetComponentType;
      if AMemTable.RecordCount > 0 then
      begin
        RecNo := AMemTable.RecNo;

        TF_Main(GForm).DM.mtInterfInternalConnEd.MasterSource := nil;
        AMemTable.DisableControls;
        try
          for i := 0 to AMemTable.RecordCount - 1 do
          begin
            AMemTable.RecNo := i + 1;

            //GetMem(Interfac, SizeOf(TInterface));
            Interfac := TSCSInterface.Create(GForm);
            TF_Main(GForm).DM.LoadFromMemTableToInterface(Interfac, AMemTable);
            Interfac.IsLineCompon := ComponType.IsLine;

            //ResList.Add(Interfac);
            Result.Add(Interfac);
            TF_Main(GForm).DM.LoadPortInterfRelsToInterfaceFromMT(Interfac,
              TF_Main(GForm).DM.MemTable_PortInterfRelEd,
              TF_Main(GForm).DM.mtInterfInternalConnEd);
          end;
        finally
          AMemTable.RecNo := RecNo;
          AMemTable.EnableControls;
        end;
      end;
    end;
  end;

begin
  Result := TSCSInterfaces.Create(false);
  with TF_Main(GForm).DM do
  begin
    LoadToInterfacesList(MemTable_InterfaceRelEd);
    SavedMasterSource := MemTable_PortInterfRelEd.MasterSource;
    MemTable_PortInterfRelEd.MasterSource := nil;
    try
      LoadToInterfacesList(MemTable_PortEd);
    finally
      MemTable_PortInterfRelEd.MasterSource := SavedMasterSource;
    end;
  end;
  //Result := ResList;
end;
{
function TF_AddComponent.CreateFormInterfaces: TSCSInterfaces;
var
  ResList: TSCSInterfaces;
  SavedMasterSource: TDataSource;

  procedure LoadToInterfacesList(AMemTable: TkbmMemTable);
  var
    i, j: Integer;
    RecNo: Integer;
    Interfac: TSCSInterface;
    ComponType: TComponentType;
  begin
    if Assigned(AMemTable) then
    begin
      ComponType := GetComponentType;
      RecNo := AMemTable.RecNo;

      TF_Main(GForm).DM.mtInterfInternalConnEd.MasterSource := nil;
      AMemTable.DisableControls;
      try
        for i := 0 to AMemTable.RecordCount - 1 do
        begin
          AMemTable.RecNo := i + 1;

          //GetMem(Interfac, SizeOf(TInterface));
          Interfac := TSCSInterface.Create(GForm);
          TF_Main(GForm).DM.LoadFromMemTableToInterface(Interfac, AMemTable);
          Interfac.IsLineCompon := ComponType.IsLine;

          ResList.Add(Interfac);

          TF_Main(GForm).DM.LoadPortInterfRelsToInterfaceFromMT(Interfac,
            TF_Main(GForm).DM.MemTable_PortInterfRelEd,
            TF_Main(GForm).DM.mtInterfInternalConnEd);
        end;
      finally
        AMemTable.RecNo := RecNo;
        AMemTable.EnableControls;
      end;
    end;
  end;

begin
  Result := nil;
  ResList := TSCSInterfaces.Create(false);
  with TF_Main(GForm).DM do
  begin
    LoadToInterfacesList(MemTable_InterfaceRelEd);
    SavedMasterSource := MemTable_PortInterfRelEd.MasterSource;
    MemTable_PortInterfRelEd.MasterSource := nil;
    try
      LoadToInterfacesList(MemTable_PortEd);
    finally
      MemTable_PortInterfRelEd.MasterSource := SavedMasterSource;
    end;
  end;
  Result := ResList;
end;
}
function TF_AddComponent.CreateFormProperties: TList;
var
  i: Integer;
  RecNo: Integer;
  ptrProperty: PProperty;
begin
  Result := nil;
  Result := TList.Create;
  // Tolik 28/12/2019 --
  if TF_Main(GForm).DM.MemTable_PropertyEd.RecordCount = 0 then
    exit;
  //
  with TF_Main(GForm).DM do
  begin
    RecNo := MemTable_PropertyEd.RecNo;
    try
      MemTable_PropertyEd.DisableControls;
      RecNo := MemTable_PropertyEd.RecNo;
      for i := 0 to MemTable_PropertyEd.RecordCount - 1 do
      begin
        MemTable_PropertyEd.RecNo := i + 1;
        //16.10.2007 GetMem(ptrProperty, SizeOf(TProperty));
        New(ptrProperty);
        ZeroMemory(ptrProperty, SizeOf(TProperty));
        ptrProperty^ := GetPropertyFromTable(DataSource_MT_PropertyEd);
        {ptrProperty.ID := MemTable_PropertyEd.FieldByName(fnID).AsInteger;
        ptrProperty.ID_Property := MemTable_PropertyEd.FieldByName(fnIDProperty).AsInteger;
        ptrProperty.Name := MemTable_PropertyEd.FieldByName(fnName).AsString;
        ptrProperty.SysName := MemTable_PropertyEd.FieldByName(fnSysName).AsString;
        ptrProperty.Value := MemTable_PropertyEd.FieldByName(fnPValue).AsString;
        ptrProperty.TakeIntoConnect := MemTable_PropertyEd.FieldByName(fnTakeIntoConnect).AsInteger;
        ptrProperty.TakeIntoJoin := MemTable_PropertyEd.FieldByName(fnTakeIntoJoin).AsInteger;
        ptrProperty.IsCrossControl := MemTable_PropertyEd.FieldByName(fnIsCrossControl).AsInteger;
        ptrProperty.IDCrossProperty := MemTable_PropertyEd.FieldByName(fnIDCrossProperty).AsInteger;
        ptrProperty.IsNew := MemTable_PropertyEd.FieldByName(fnIsNew).AsBoolean;
        ptrProperty.IsModified := MemTable_PropertyEd.FieldByName(fnIsModified).AsBoolean;
        }
        Result.Add(ptrProperty);
      end;
    finally
      MemTable_PropertyEd.RecNo := RecNo;
      MemTable_PropertyEd.EnableControls;
    end;
  end;
end;

function TF_AddComponent.CreateFormCableCanalConnectors: TList;
var
  ptrCableCanalConnector: PCableCanalConnector;
  RecNo: Integer;
begin
  Result := TList.Create;
  // Tolik 28/12/2019 --
  if TF_Main(GForm).DM.MemTable_CableCanalConnectorsEd.RecordCount = 0 then
    exit;
  //
  with TF_Main(GForm).DM do
    if MemTable_CableCanalConnectorsEd.Active then
    begin
      RecNo := MemTable_CableCanalConnectorsEd.RecNo;
      MemTable_CableCanalConnectorsEd.DisableControls;
      try
        MemTable_CableCanalConnectorsEd.First;
        while not MemTable_CableCanalConnectorsEd.Eof do
        begin
          GetZeroMem(ptrCableCanalConnector, SizeOf(TCableCanalConnector));
          ptrCableCanalConnector.ID := MemTable_CableCanalConnectorsEd.FieldByName(fnID).AsInteger;
          ptrCableCanalConnector.IDCableCanal := MemTable_CableCanalConnectorsEd.FieldByName(fnIDComponent).AsInteger;
          ptrCableCanalConnector.IDNBConnector := MemTable_CableCanalConnectorsEd.FieldByName(fnIDNBConnector).AsInteger;
          ptrCableCanalConnector.GuidNBConnector := MemTable_CableCanalConnectorsEd.FieldByName(fnGuidNBConnector).AsString;
          ptrCableCanalConnector.ConnectorType := MemTable_CableCanalConnectorsEd.FieldByName(fnConnectorType).AsInteger;
          ptrCableCanalConnector.IsModified := MemTable_CableCanalConnectorsEd.FieldByName(fnIsModified).AsBoolean;
          ptrCableCanalConnector.IsNew := MemTable_CableCanalConnectorsEd.FieldByName(fnIsNew).AsBoolean;
          Result.Add(ptrCableCanalConnector);

          MemTable_CableCanalConnectorsEd.Next;
        end;
        MemTable_CableCanalConnectorsEd.RecNo := RecNo;
      finally
        MemTable_CableCanalConnectorsEd.EnableControls;
        MemTable_CableCanalConnectorsEd.RecNo := RecNo;
      end;
    end;
end;

function TF_AddComponent.CreateFormCrossConnections: TSCSObjectList;
var
  ptrDestCrossConnection: TSCSCrossConnection;
  MemTable: TkbmMemTable;
  RecNo: Integer;
  i: Integer;
begin
  Result := TSCSObjectList.Create(false);
  MemTable := TF_Main(GForm).DM.mtCrossConnectionEd;
  if MemTable.Active and (MemTable.RecordCount > 0) then
  begin
    RecNo := MemTable.RecNo;
    MemTable.DisableControls;
    try
      for i := 0 to MemTable.RecordCount - 1 do
      begin
        MemTable.RecNo := i + 1;

        //GetMem(ptrDestCrossConnection, SizeOf(TCrossConnection));
        ptrDestCrossConnection := TSCSCrossConnection.Create(GForm);
        TF_Main(GForm).DM.LoadCrossConnectionFromMemTable(MemTable, ptrDestCrossConnection);
        Result.Add(ptrDestCrossConnection);
      end;
    finally
      MemTable.RecNo := RecNo;
      MemTable.EnableControls;
    end;
  end;
end;

procedure TF_AddComponent.DeleteAllPortsAndInterf;
begin
  with TF_Main(GForm).DM do
  begin
    ClearPortInterfaceMemTable(MemTable_PortEd, true);
    ClearPortInterfaceMemTable(MemTable_InterfaceRelEd, false);

    //*** Удалить внутренние связи портв с интерфейсами
    mtInterfInternalConnEd.First;
    while not mtInterfInternalConnEd.Eof do
      mtInterfInternalConnEd.Delete;
  end;
end;

function TF_AddComponent.DelRequiredEmptyProps: Boolean;
var
  //PropSysNamesCanDel: TStringList;
  i: Integer;

  //PropsBookmarks: TStringList;
  PropsNames: TStringList;
  PropsSysNames: TStringList;
  //MemTableBookmark: string;
  MemTableBookmark: TBookMark;
  MemTable: TkbmMemTable;

  MessageStr: string;
  StrValue: String;
begin
  Result := false;
  try
    //PropSysNamesCanDel := TStringList.Create;
    //PropSysNamesCanDel.Add(pnPortCount);
    //PropSysNamesCanDel.Add(pnPortWireCount);

    //PropsBookmarks := TStringList.Create;
    PropsSysNames := TStringList.Create;
    PropsNames := TStringList.Create;
    MemTable := TF_Main(GForm).DM.MemTable_PropertyEd;

    // Ищем обязательные свойства с пустыми значениями
    //MemTableBookmark := MemTable.Bookmark;
    MemTableBookmark := MemTable.GetBookmark;
    MemTable.DisableControls;
    try
      MemTable.First;
      while Not MemTable.Eof do
      begin
        if GPropRequired.IndexOf(MemTable.FieldByName(fnSysName).AsString) <> -1 then
        begin
          StrValue := PropValueToCaption(
                        MemTable.FieldByName(fnPValue).AsString,
                        MemTable.FieldByName(fnSysName).AsString, '',
                        MemTable.FieldByName(fnIDDataType).AsInteger,
                        TF_Main(GForm).FUOM, false);
          if (StrValue = '') or (StrToFloatDef_My(StrValue, 0) <= 0) then
          begin
            //PropsBookmarks.Add(MemTable.Bookmark);
            PropsSysNames.Add(MemTable.FieldByName(fnSysName).AsString);
            PropsNames.Add(MemTable.FieldByName(fnName).AsString);
          end;
        end;
        MemTable.Next;
      end;
    finally
      MemTable.EnableControls;
      if MemTableBookmark <> nil then
      begin
        MemTable.GotoBookmark(MemTableBookmark);
        MemTable.FreeBookmark(MemTableBookmark);
      end;
      //MemTable.Bookmark := MemTableBookmark;
    end;

    // Спрашиваем удалять их и удаляем
    if PropsSysNames.Count > 0 then
    begin
      MessageStr := cAddComponent_Msg25_1 + ': ';
      for i := 0 to PropsNames.Count - 1 do
      begin
        if i > 0 then
          MessageStr := MessageStr + snCommaS;
        MessageStr := MessageStr + PropsNames[i];
      end;
      MessageStr := MessageStr + snPoint + snNextRow+ cAddComponent_Msg25_2;

      if MessageQuastYN(MessageStr) = IDYES then
      begin
        {MemTableBookmark := MemTable.Bookmark;
        MemTable.DisableControls;
        try
          for i := 0 to PropsSysNames.Count - 1 do
            if MemTable.Locate(fnSysName, PropsSysNames[i], []) then
            begin
              if MemTableBookmark = MemTable.Bookmark then
                MemTableBookmark := '';
              if Not MemTable.FieldByName(fnIsNew).AsBoolean then
                GDeletedPropRel.Add(MemTable.FieldByName(fnID).AsInteger);
              MemTable.Delete;
            end;
        finally
          MemTable.EnableControls;
          if MemTableBookmark <> '' then
            MemTable.Bookmark := MemTableBookmark;
        end;}
        DelPropsBySysNames(PropsSysNames);
        Result := true;
      end;
    end
    else
      Result := true;

    FreeAndNil(PropsNames);
    FreeAndNil(PropsSysNames);
    //FreeAndNil(PropsBookmarks);
    //FreeAndNil(PropSysNamesCanDel);
  except
    on E: Exception do AddExceptionToLogExt(ClassName, 'DelPortProps', E.Message);
  end;
end;

function TF_AddComponent.GetComponentActualPrice: Double;
begin
  Result := 0;
  if CheckBox_HasNds.Checked then
    Result := StrToFloatU(CorrectStrToFloat(CurrencyEdit_Price1.Text))
  else
    Result := StrToFloatU(CorrectStrToFloat(CurrencyEdit_NDS1.Text));
end;

function TF_AddComponent.GetComponentNameMarkByTemplate: string;
var
  ProjComponent: TSCSComponent;
  ProjComponentOwner: TSCSCatalog;
  FormComponent: TSCSComponent;
begin
  if TF_Main(GForm).GDBMode = bkProjectManager then
  begin
    ProjComponent := TF_Main(GForm).GSCSBase.CurrProject.GetComponentFromReferences(GIDComponent);
    if ProjComponent <> nil then
    begin
      if TF_Main(GForm).GSCSBase.CurrProject.Setting.MarkMode = mmTemplate then
      begin
        ProjComponentOwner := ProjComponent.GetFirstParentCatalog;
        if ProjComponentOwner <> nil then
        begin
          FormComponent := CreateFormOnlyComponent;
          FormComponent.ProjectOwner := ProjComponent.ProjectOwner;
          try
            Result := TF_Main(GForm).MakeNameMarkComponent(FormComponent, ProjComponentOwner, false);
          finally
            FreeAndNil(FormComponent);
          end;
        end;
      end
      else
      begin
        Result := TF_Main(GForm).MakeNameMarkComponent(ProjComponent, nil, false);
      end;
    end;
  end;
end;

function TF_AddComponent.GetNormResourcesCountByCompPropRelID(AIDCompPropRel: Integer): Integer;
var
  MemTable: TkbmMemTable;
  //MemTableBookmark: string;
  MemTableBookmark: TBookMark;
begin
  Result := 0;
  try
    MemTable := TF_Main(GForm).DM.MemTable_NormsEd;
    //MemTableBookmark := MemTable.Bookmark;
    MemTableBookmark := MemTable.GetBookmark;
    MemTable.DisableControls;
    try
      MemTable.First;
      while Not MemTable.Eof do
      begin
        if MemTable.FieldByName(fnIDCompPropRel).AsInteger = AIDCompPropRel then
          Result := Result + 1;
        MemTable.Next;
      end;
    finally
      MemTable.EnableControls;
      //MemTable.Bookmark := MemTableBookmark;
      if MemTableBookmark <> nil then
      begin
        MemTable.GotoBookmark(MemTableBookmark);
        MemTable.FreeBookmark(MemTableBookmark);
      end;
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.DeleteComponNormResByIDCompPropRel', E.Message);
  end;
end;

function TF_AddComponent.GetSignType: Integer;
var
  //BookMarkStr: string;
  BookMarkStr: TBookMark;
begin
  Result := oitProjectible;

  //*** Найти Свойство "Тип условного обозначения"
  //BookMarkStr := TF_Main(GForm).DM.MemTable_PropertyEd.Bookmark;
  BookMarkStr := TF_Main(GForm).DM.MemTable_PropertyEd.GetBookmark;

  TF_Main(GForm).DM.MemTable_PropertyEd.DisableControls;
  try
    //if SearchRecordMT(TF_Main(GForm).DM.MemTable_PropertyEd, 'ID_Data_Type', dtCompStateType) then
    if TF_Main(GForm).DM.MemTable_PropertyEd.Locate(fnSysName, pnSignType, []) then
      Result := TF_Main(GForm).DM.MemTable_PropertyEd.FieldByName(fnPValue).AsVariant;

   // TF_Main(GForm).DM.MemTable_PropertyEd.Bookmark := BookMarkStr;
   if BookMarkStr <> nil then
   begin
     TF_Main(GForm).DM.MemTable_PropertyEd.GotoBookmark(BookMarkStr);
     TF_Main(GForm).DM.MemTable_PropertyEd.FreeBookmark(BookMarkStr);
   end;
  finally
    TF_Main(GForm).DM.MemTable_PropertyEd.EnableControls;
  end;
end;

procedure TF_AddComponent.ImportComponentByID(AID: Integer);
var
  TemplateComponent: TSCSComponent;
begin
  TemplateComponent := TSCSComponent.Create(GForm);
  //*** Установить записи как удаленные
  with TF_Main(GForm).DM do
  begin
    //*** Установить Свойства как удаленные
    SetAsDeletedMTRecords(MemTable_PropertyEd, nil, GDeletedPropRel, nil);

    //*** Порты/Интерфейсы
    RemoveNoNativeInterfacesFromMemTable(MemTable_PortEd);
    RemoveNoNativeInterfacesFromMemTable(MemTable_InterfaceRelEd);
    SetAsDeletedMTRecords(MemTable_PortEd, MemTable_PortInterfRelEd, GDeletedInterfRel, GDeletedPortInterfRels);
    SetAsDeletedMTRecords(MemTable_InterfaceRelEd, nil, GDeletedInterfRel, nil);
    //*** Элементы каб. каналов
    SetAsDeletedMTRecords(MemTable_CableCanalConnectorsEd, nil, GDeletedCableCanalConnectors, nil);
    //*** Кросс-соединения
    SetAsDeletedMTRecords(mtCrossConnectionEd, nil, GDeletedCrossConnections, nil);
  end;

  TemplateComponent.LoadComponentByID(AID, false);
  TemplateComponent.LoadComponentData([cdCableCanalConnectors,
    //cdConections,
    cdCrossConnections,
      cdProperties,
      cdInterfaces,
      cdComponentType,
      cdNorms,
      cdResources]);
  TemplateComponent.SetPortInterfRelInterfaces;
  TemplateComponent.SetInterfacesParallel;

  SendComponentToForm(TemplateComponent, true);

  FreeAndNil(TemplateComponent);
end;

procedure TF_AddComponent.SetAsDeletedMTRecords(AMemTable, ADetailMemTable: TkbmMemTable;
  ADeletedIDs, ADeletedIDsFromDetail: TIntList);
var
  SavedMasterSource: TDataSource;

  procedure SetForMT(AMT: TkbmMemTable; ADelIDs: TIntList);
  var
    i: Integer;
    RecNo: Integer;
    TableID: Integer;
  begin
    if AMT.RecordCount > 0 then
    begin
      RecNo := AMT.RecNo;
      AMT.DisableControls;
      try
        for i := 0 to AMT.RecordCount - 1 do
        begin
          AMT.RecNo := i + 1;
          if AMT.FieldByName(fnIsNew).AsBoolean = false then
          begin
            TableID := AMT.FieldByName(fnID).AsInteger;
            if (TableID > 0) and (ADelIDs.IndexOf(TableID) = -1) then
              ADelIDs.Add(TableID);
          end;
        end;
      finally
        AMT.EnableControls;
        AMT.RecNo := RecNo;
      end;
    end;
  end;

begin
  try
    SavedMasterSource := nil;
    if ADetailMemTable <> nil then
    begin
      SavedMasterSource := ADetailMemTable.MasterSource;
      ADetailMemTable.MasterSource := nil;
    end;
    try
      SetForMT(AMemTable, ADeletedIDs);
      if (ADetailMemTable <> nil) and (ADeletedIDsFromDetail <> nil) then
        SetForMT(ADetailMemTable, ADeletedIDsFromDetail);
    finally
      if ADetailMemTable <> nil then
        ADetailMemTable.MasterSource := SavedMasterSource;
    end;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.SetAsDeletedMTRecords: ' + E.Message);
  end;
end;

procedure TF_AddComponent.SendComponentToForm(AComponent: TSCSComponent; AFromChangeComponType: Boolean);
var
  Stream: TStream;
  ProjManCompon: TSCSComponent;
  ComponPrice: Double;
  IsEnableControls: Boolean;
begin
  ProjManCompon := nil;

  FIsLoadingForm := true;
  try
    ClearFormGrids;

    GIDObjectIcon := AComponent.IDObjectIcon;
    GIDSymbolImage := AComponent.IDSymbol;
    GGUIDObjectIcon := AComponent.GUIDObjectIcon;
    GGUIDSymbolImage := AComponent.GUIDSymbol;

    if TF_Main(GForm).GDBMode = bkProjectManager then
    begin
      ProjManCompon := TF_Main(GForm).GSCSBase.CurrProject.GetComponentFromReferences(AComponent.ID);
      if ProjManCompon <> nil then
      begin
        if ProjManCompon.IsLine = biTrue then
        begin
          FTraccaLength := ProjManCompon.GetPartLength;
          GT_NORMSTotalKolvo.Caption := GetCaptionNormsResourcesTotalKolvo(TF_Main(GForm).FUOM, FTraccaLength);
        end;

        //*** определить отсутствующие УГО из КАД объекта
        if ProjManCompon.ProjectOwner <> nil then
          ProjManCompon.ProjectOwner.DefineSpravObjectIconFromCAD(ProjManCompon.GUIDObjectIcon, ProjManCompon.GetFirstParentCatalog);
      end;
    end;

    if AComponent.Picture <> nil then
      try
        AComponent.Picture.Position := 0;
        if AComponent.Picture.Size > 0 then
        begin
          Stream := TFileStream.Create(ComponPictFileName, fmCreate);
          Stream.Position := 0;
          Stream.CopyFrom(AComponent.Picture, 0);
          Stream.Position := 0;
          FreeAndNil(Stream);
          Image.Picture.LoadFromFile(ComponPictFileName);
          DeleteFile(ComponPictFileName);
          //Image.Picture.Bitmap.LoadFromStream(Stream);
          //Stream.Free;
        end;
      except
        on E: Exception do
          ShowMessage(cAddComponent_Msg5);
      end;

    if Assigned(AComponent.Description) then
      if AComponent.Description.Size > 0 then
      begin
        AComponent.Description.Position := 0;
        meDescription.Lines.LoadFromStream(AComponent.Description);
      end;

    if not AFromChangeComponType then
    begin
      Edit_Name.Text := AComponent.Name;
      //Edit_Izm.Text := AComponent.Izm; //#From Oleg# 2007.07.19

      MaskEdit_Cyper.Text := AComponent.Cypher;

      Edit_ArticulDistributor.Text := AComponent.ArticulDistributor;
      Edit_ArticulProducer.Text := AComponent.ArticulProducer;

      if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        seIndex.Properties.OnChange := nil;
        try
          seIndex.Value := AComponent.MarkID;
        finally
          seIndex.Properties.OnChange := seIndexPropertiesChange;
        end;
      end;

      //*** Тип компоненты
      AComponent.LoadComponentType;
      ComboBox_ComponentType.Properties.OnChange := nil;
      try
        case TF_Main(GForm).GDBMode of
          bkNormBase:
            SelectItemByIDinCombo(ComboBox_ComponentType, AComponent.ID_ComponentType);
          bkProjectManager:
            begin
              AddItemToCombo(ComboBox_ComponentType, AComponent.ComponentType.Name, AComponent.GUIDComponentType, AComponent.ID_ComponentType,
                AComponent.GUIDComponentType, AComponent.ID_ComponentType, nil);
              SelectItemByGUIDinCombo(ComboBox_ComponentType, AComponent.GUIDComponentType);
            end;
        end;
      finally
        ComboBox_ComponentType.Properties.OnChange := ComboBox_ComponentTypePropertiesChange;
      end;
      FCurrComponentType := AComponent.ComponentType;

      //*** Вид поставки
      //cePriceSupply.Properties.OnChange := nil;
      cePriceSupply.Value := RoundCP(AComponent.PriceSupply);

      //cePriceSupply.Properties.OnChange := cePriceSupplyPropertiesChange;
      //FSuppliesKind := F_NormBase.DM.GetSuppliesKindByID(AComponent.IDSuppliesKind, AComponent.GUIDSuppliesKind);
      FSuppliesKind := TF_Main(GForm).DM.GetSuppliesKindByID(AComponent.IDSuppliesKind, AComponent.GUIDSuppliesKind);
      DefineSuppliesKindWorkValuesToFields(FSuppliesKind, TF_Main(GForm).FUOM);

      cbSuppliesKind.Properties.OnChange := nil;
      if AComponent.GUIDSuppliesKind <> '' then
        SelectItemByGUIDinCombo(cbSuppliesKind, AComponent.GUIDSuppliesKind)
      else
        SelectItemByIDinCombo(cbSuppliesKind, AComponent.IDSuppliesKind);
      cbSuppliesKind.Properties.OnChange := cbSuppliesKindPropertiesChange;

      // Загрузить цены
      CheckBox_HasNds.Checked := IntToBool(AComponent.HASNDS);

      ShowNDSPrice;
      ComponPrice := AComponent.Price;
      if CheckPriceTransformToUOMByCompType(@FCurrComponentType) then
        ComponPrice := FloatInUOM(ComponPrice, TF_Main(GForm).FUOM, umMetr);
      case AComponent.HASNDS of
        biFalse:
          begin // В том числе с НДС - да
            CurrencyEdit_Nds1.Value := Round3(ComponPrice);
            //CurrencyEdit_Nds2.Value := Round3(AComponent.Price *
            //                     (TF_Main(GForm).GLocalCurrencyM.Data.Ratio / TF_Main(GForm).GLocalCurrencyS.Data.Ratio));
            CurrencyEdit_Nds2.Value := Round3(GetPriceAfterChangeCurrency(ComponPrice,
              TF_Main(GForm).GLocalCurrencyM.Data, TF_Main(GForm).GLocalCurrencyS.Data));

            CurrencyEdit_Price1.Value := Round3(PriceWithoutNDS(ComponPrice, TF_Main(GForm).GNDS));
            //CurrencyEdit_Price2.Value := Round3( PriceWithoutNDS( AComponent.Price, TF_Main(GForm).GNDS) *
            //                     (TF_Main(GForm).GLocalCurrencyM.Data.Ratio / TF_Main(GForm).GLocalCurrencyS.Data.Ratio));
            CurrencyEdit_Price2.Value := Round3(GetPriceAfterChangeCurrency(PriceWithoutNDS(ComponPrice, TF_Main(GForm).GNDS),
              TF_Main(GForm).GLocalCurrencyM.Data, TF_Main(GForm).GLocalCurrencyS.Data));
          end;
        biTrue:
          begin // В том числе с НДС - Нет
            CurrencyEdit_Price1.Value := Round3(ComponPrice);
            //CurrencyEdit_Price2.Value := Round3(AComponent.Price *
            //                     (TF_Main(GForm).GLocalCurrencyM.Data.Ratio / TF_Main(GForm).GLocalCurrencyS.Data.Ratio));
            CurrencyEdit_Price2.Value := Round3(GetPriceAfterChangeCurrency(ComponPrice,
              TF_Main(GForm).GLocalCurrencyM.Data, TF_Main(GForm).GLocalCurrencyS.Data));
          end;
      end;
    end;
    DefineSupplyPriceByComponActualPrice;

    Edit_NameShort.Text := AComponent.NameShort;
    Edit_Izm.Text := AComponent.Izm;
    Edit_NameMark.Text := AComponent.NameMark;
    //Edit_MarkStr.Text := AComponent.MarkStr;
    Edit_Notice.Text := AComponent.Notice;

    //CheckBox_IsUserMark.Checked := IntToBool(IsUserMark);
    if AComponent.IsUserMark = biTrue then
      SetValueToCXRadioBottonAsNoChange(rbMarkByDefault, true)
    else
      SetValueToCXRadioBottonAsNoChange(rbMarkByTemplate, true);

    //case ISComplect of
    //  0: RadioGroup_CanComplect.ItemIndex := 1;
    //  1: RadioGroup_CanComplect.ItemIndex := 0;
    //end;
    cbCanComplect.Checked := IntToBool(AComponent.ISComplect);
    cbIsMarkInCaptions.Checked := IntToBool(AComponent.IsMarkInCaptions);

    //case HASNDS  of
    //  0: RadioGroup_HasNds.ItemIndex := 1;
    //  1: RadioGroup_HasNds.ItemIndex := 0;
    //end;

    ComboBox_ComponentType.Properties.OnChange := nil;
    VisibleInterfaceColumns(AComponent.IsLine = biTrue);
    ComboBox_ComponentType.Properties.OnChange := ComboBox_ComponentTypePropertiesChange;

    //DefineParamsBySupply(false);

    SpinEdit_UserLength.Value := FloatInUOM(AComponent.UserLength, umMetr, TF_Main(GForm).FUOM);
    //SpinEdit_ObjectIconStep.Value := AComponent.ObjectIconStep;
    cbDismount.OnClick := nil;
    try
      cbDismount.Checked := IntToBool(AComponent.IsDismount);
    finally
      cbDismount.OnClick := cbDismountClick;
    end;
    cbUseDismounted.Checked := IntToBool(AComponent.IsUseDismounted);

    if AComponent.GUIDProducer <> '' then
      SelectItemByGUIDinCombo(ComboBox_Producer, AComponent.GUIDProducer)
    else
      SelectItemByIDinCombo(ComboBox_Producer, AComponent.ID_Producer);
    if AComponent.GUIDNetType <> '' then
      SelectItemByGUIDinCombo(ComboBox_NetType, AComponent.GUIDNetType)
    else
      SelectItemByIDinCombo(ComboBox_NetType, AComponent.IDNetType);

    SelectItemByIDinCombo(cbSpecification, AComponent.IDCompSpecification);


    // Загрузить Тип Сети
    {ID_NetType := TObject.Create;
    for i := 0 to ComboBox_NetType.Properties.Items.Count - 1 do
      begin
          ID_NetType := ComboBox_NetType.Properties.Items.Objects[i];
          if (ID_NetType as TID).ID = IDNetType then
            begin
                ComboBox_NetType.ItemIndex := i;
                ComboBox_NetType.Refresh;
                Break;
            end;
      end;}

    //With TF_Main(GForm).DM do
    //  LoadMT(GID_COMPONENT, tkComponIconsED, ComponIconsFields);
              
    // Загрузить интерфейсы
    with TF_Main(GForm).DM do
    begin
      if not AFromChangeComponType then
      begin
        LoadMT(AComponent.ID, tkInterfRelED, InterfFields, AFromChangeComponType);

        //MemTable_InterfaceRelEd.LoadFromDataSet(MemTable_InterfaceRel, []);

        // Загрузить портов
        if AComponent.IsLine = biFalse then
        begin
          //With TF_Main(GForm).DM do
          LoadMT(AComponent.ID, tkPortED, PortFields, AFromChangeComponType);
          LoadMT(AComponent.ID, tkPortInterfRelED, nil, AFromChangeComponType);
          DefineAllPortInterfRelNames;
        end;
        LoadMT(AComponent.ID, tkInterfInternalConnED, nil, AFromChangeComponType);
      end
      else
        SendInterfacesPortsToMemTable(AComponent, true, false);

      // Загрузить свойства
      //With TF_Main(GForm).DM do
      if not AFromChangeComponType then
        LoadMT(AComponent.ID, tkPropertyRelED, PropertFields, AFromChangeComponType)
      else
        FillMemTablePropFromList(MemTable_PropertyEd, AComponent.Properties, true);

      //MemTable_PropertyEd.LoadFromDataSet(MemTable_Property, [], AFromChangeComponType);
      LoadComponIcon(AComponent.IDObjectIcon, AComponent.GUIDObjectIcon, Image_CompIcons);
      LoadComponIcon(AComponent.IDSymbol, AComponent.GUIDSymbol, Image_Symbol);

      // Загрузить комплектующие
      //With TF_Main(GForm).DM do
      if not AFromChangeComponType then
        LoadMT(AComponent.ID, tkComplectED, ComplectsFields, AFromChangeComponType);

      // Загрузить элементы кабельных каналов
      if AComponent.ComponentType.SysName = ctsnCableChannel then
        if not AFromChangeComponType then
          LoadMT(AComponent.ID, tkCableCanalConnectorsED, CableCanalConnectorsFields, AFromChangeComponType)
        else
          FillMemTableCableCanalConnectors(MemTable_CableCanalConnectorsEd, AComponent.CableCanalConnectors, true);

      // Загрузить кросс-соединения
      if AComponent.ComponentType.SysName = ctsnCupBoard then
        if not AFromChangeComponType then
          LoadMT(AComponent.ID, tkCrossConnectionED, nil, AFromChangeComponType)
    end;
    LoadNormsResources(AFromChangeComponType);

    IsEnableControls := true;
    if TF_Main(GForm).GDBMode = bkProjectManager then
    begin
      GLastPort := TF_Main(GForm).DM.GetComponentLastPort(AComponent.ID);
      //26.05.2009 EnableControl(false);
      IsEnableControls := false;
      //Caption := 'Промотр данных комплектующей';
    end
    else
    begin
      {$IF Defined (FINAL_SCS)}
        IsEnableControls := Not FIsTemplate;
      {$IFEND}
    end;
    EnableControl(IsEnableControls);

    SetVisibleByIsLine(AComponent.ComponentType.IsLine);
  finally
    FIsLoadingForm := false;
  end;
end;

procedure TF_AddComponent.SendInterfacesPortsToMemTable(ASCSComponent: TSCSComponent; AAsNew, AAskDelInterf: Boolean);
var
  ComponentType: TComponentType;
  Interf: TSCSInterface;
  InternalConnected: TSCSInterface;
  ptrPortInterfRel: PPortInterfRel;
  NewID: Integer;
  i, j: Integer;
  WorkMemTable: TkbmMemtable;
  SavedMasterSource: TDataSource;
  PortInterfRelName: string;

  CurrNumPair: Integer;

  {procedure ClearPortInterfaceMemTable(AMemTable: TkbmMemTable; AIsPort: Boolean);
  var
    i: Integer;
    NumPair: Integer;
    CanDelete: Boolean;
  begin
    AMemTable.Last;
    while not AMemTable.Bof do
    begin
      if (AMemTable.FieldByName(fnIsBusy).AsInteger = biFalse) and
        (AMemTable.FieldByName(fnIsNative).AsBoolean = True) then
      begin
        NumPair := 0;
        if not AIsPort then
          NumPair := AMemTable.FieldByName(fnNumPair).AsInteger;

        CanDelete := false;
        if AMemTable.FieldByName(fnIsNew).AsBoolean then
          CanDelete := true
        else if not CheckInterfIsUse(GForm, GIDComponent, AMemTable.FieldByName(fnID).AsInteger, NumPair) then
          CanDelete := true;

        if CanDelete then
        begin
          if (AMemTable.FieldByName(fnIsNew).AsBoolean = false) and
            (AMemTable.FieldByName(fnIsNative).AsBoolean = true) then
            GDeletedInterfRel.Add(AMemTable.FieldByName(fnID).AsInteger);
          AMemTable.Delete;
          Continue; ///// CONTINUE /////
        end;
      end;
      AMemTable.Prior;
    end;
  end;}

begin
  ComponentType := GetComponentType;
  CurrNumPair := 0;

  with TF_Main(GForm).DM do
  begin
    //*** Удалить не используемые интерфейсы
    if (MemTable_PortEd.RecordCount > 0) or (MemTable_InterfaceRelEd.RecordCount > 0) then
    begin
      if Not AAskDelInterf or (MessageModal(cQuastLeavePresentInterfaces, ApplicationName, MB_ICONINFORMATION or MB_YESNO) = IDNO) then
      begin
        //ClearPortInterfaceMemTable(MemTable_PortEd, true);
//        ClearPortInterfaceMemTable(MemTable_InterfaceRelEd, false);
//
//        //*** Удалить внутренние связи портв с интерфейсами
//        mtInterfInternalConnEd.First;
//        while not mtInterfInternalConnEd.Eof do
//          mtInterfInternalConnEd.Delete;

        DeleteAllPortsAndInterf;
      end
      else
      begin
        CurrNumPair := GetMaxNumPair(MemTable_InterfaceRelEd);

        //*** Установить номера пар в новых интерфейсах как 0
        for i := 0 to ASCSComponent.Interfaces.Count - 1 do
          ASCSComponent.Interfaces[i].NumPair := 0;
      end;
    end;

    //*** Переопределить ID ки
    for i := 0 to ASCSComponent.Interfaces.Count - 1 do
    begin
      Interf := ASCSComponent.Interfaces[i];

      NewID := GenNewID(tkInterfRelED);
      Interf.ClearIOfIRels;
      if Interf.ParallelInterface <> nil then
      begin
        case ComponentType.IsLine of
          biTrue:
            begin
              Interf.ParallelInterface.IDAdverse := NewID;
              if (Interf.NumPair = 0) and (Interf.ParallelInterface.NumPair = 0) then
              begin
                Inc(CurrNumPair);
                Interf.NumPair := CurrNumPair;
                Interf.ParallelInterface.NumPair := CurrNumPair;
              end;
            end;
          biFalse:
            begin
              Interf.ParallelInterface.IDAdverse := 0;
              Interf.IDAdverse := 0;
            end;
        end;
      end;
      //if Interf.PortOwner <> nil then
//      begin
//        ptrPortInterfRel := Interf.PortOwner.GetPortInterfRelByInterfID(Interf.ID);
//        if ptrPortInterfRel <> nil then
//          ptrPortInterfRel.IDInterfRel := NewID;
//      end;
      ////if Interf.IsPort = biTrue then ##ISPORT
        //for j := 0 to Interf.PortInterfRels.Count - 1 do
//        begin
//          ptrPortInterfRel := Interf.PortInterfRels[j];
//          ptrPortInterfRel.ID := GenNewID(tkPortInterfRelED);
//          ptrPortInterfRel.IDPort := NewID;
//        end;
      Interf.NewID := NewID;
      Interf.ID_Component := GIDComponent;
      Interf.IsBusy := biFalse;
      Interf.IsNew := True;
    end;
    //*** Внутренние связи интерфейсов
    for i := 0 to ASCSComponent.Interfaces.Count - 1 do
    begin
      Interf := ASCSComponent.Interfaces[i];
      for j := 0 to Interf.PortInterfRels.Count - 1 do
      begin
        ptrPortInterfRel := Interf.PortInterfRels[j];
        ptrPortInterfRel.ID := GenNewID(tkPortInterfRelED);
        ptrPortInterfRel.IDPort := Interf.NewID;
        InternalConnected := ASCSComponent.GetInterfaceByID(ptrPortInterfRel.IDInterfRel);
        //if InternalConnected <> nil then
        ptrPortInterfRel.IDInterfRel := InternalConnected.NewID;
        ptrPortInterfRel.IsNew := True;
      end;
    end;
    //*** Перекинуть ID-ки
    for i := 0 to ASCSComponent.Interfaces.Count - 1 do
    begin
      Interf := ASCSComponent.Interfaces[i];
      Interf.ID := Interf.NewID;
    end;

    //*** Насыпать интерфейсы в таблици
    for i := 0 to ASCSComponent.Interfaces.Count - 1 do
    begin
      Interf := ASCSComponent.Interfaces[i];
      WorkMemTable := nil;
      case Interf.IsPort of
        biTrue:
          WorkMemTable := MemTable_PortEd;
        biFalse:
          WorkMemTable := MemTable_InterfaceRelEd;
      end;

      if WorkMemTable <> nil then
      begin
        LoadInterfaceToMemTable(Interf, WorkMemTable, MemTable_PortInterfRelEd, mtInterfInternalConnEd, meMake,
          ComponentType.IsLine, true, false);
        WorkMemTable.Edit;
        WorkMemTable.FieldByName(fnIsNew).AsBoolean := AAsNew;
        WorkMemTable.Post;
      end;
    end;
    LoadInterfRelNamesToMemTable(MemTable_PortEd);
    LoadInterfRelNamesToMemTable(MemTable_InterfaceRelEd);

    //*** указать связи портов с интерфейсами как новые
    if MemTable_PortInterfRelEd.RecordCount > 0 then // Tolik 28/12/2019 --
    begin
      SavedMasterSource := MemTable_PortInterfRelEd.MasterSource;
      MemTable_PortInterfRelEd.MasterSource := nil;
      try
        for j := 0 to MemTable_PortInterfRelEd.RecordCount - 1 do
        begin
          PortInterfRelName := '';
          Interf := ASCSComponent.GetInterfaceByID(MemTable_PortInterfRelEd.FieldByName(fnIDInterfRel).AsInteger);
          if Interf <> nil then
            PortInterfRelName := Interf.LoadName;

          MemTable_PortInterfRelEd.RecNo := j + 1;
          MemTable_PortInterfRelEd.Edit;
          MemTable_PortInterfRelEd.FieldByName(fnName).AsString := PortInterfRelName;
          MemTable_PortInterfRelEd.FieldByName(fnIsNew).AsBoolean := AAsNew;
          MemTable_PortInterfRelEd.Post;
        end;
      finally
        MemTable_PortInterfRelEd.MasterSource := SavedMasterSource;
      end;
    end;
    DefineAllPortInterfRelNames;
  end;
end;

procedure TF_AddComponent.DefineComponCurrencies;
begin
  //FCurrency := TF_Main(GForm).GCurrencyM;
  //FNBCurrency := TF_Main(GForm).FNormBase.GCurrencyM;
  FCurrency := TF_Main(GForm).GLocalCurrencyM.Data;
  // Ресурс добавляется в компонент НБ из нормативной базы, то валюту берем по папке с валютами.
  FIDCatalog := 0;
  if GFormMode = fmMake then
    FIDCatalog := TF_Main(GForm).GSCSBase.SCSCatalog.ID
  else
    FIDCatalog := TF_Main(GForm).DM.GetComponCatalogOwnerID(GIDComponent);
  FNBCurrency := TF_Main(GForm).DM.GetCatalogOrComponCurrencyProperGlobalMainInNB(FIDCatalog, GIDComponent);
end;

procedure TF_AddComponent.DefineComponSecondPrice(AFirstPrice: Double);
var
  RoundValue: Double;
begin
  //RoundValue := Round3(AFirstPrice * (TF_Main(GForm).GLocalCurrencyM.Data.Ratio / TF_Main(GForm).GLocalCurrencyS.Data.Ratio));
  RoundValue := Round3(GetPriceAfterChangeCurrency(AFirstPrice, TF_Main(GForm).GLocalCurrencyM.Data, TF_Main(GForm).GLocalCurrencyS.Data));
  CurrencyEdit_Price2.Value := RoundValue;
end;

procedure TF_AddComponent.DefineNormResByProperty(Aproperty: PProperty);
var
  Compon: TSCSComponent;
  SCSNorm: TSCSNorm;
  ResourceRel: TSCSResourceRel;
  
  MemTable: TkbmMemTable;
  //MemTableBookmark: String;
  MemTableBookmark: TBookMark;

  DeletedFromMemTable: Boolean;
  FDeletedNormIDs: TIntList;
  FDeletedResIDs: TIntList;
  ObjFromMemTable: TRapList;
  i: Integer;
begin
  try
    if TF_Main(GForm).GDBMode = bkProjectManager then
    begin
      Compon := CreateFormOnlyComponent;
      ObjFromMemTable := TRapList.Create;
      MemTable := TF_Main(GForm).DM.MemTable_NormsEd;
      //MemTableBookmark := MemTable.Bookmark;
      MemTableBookmark := MemTable.GetBookmark;
      MemTable.DisableControls;
      try
        MemTable.First;
        while not MemTable.Eof do
        begin
          case MemTable.FieldByName(fnIsResource).AsBoolean of
            true: // Внести ресурс
              begin
                ResourceRel := TSCSResourceRel.Create(GForm, ntProj);
                TF_Main(GForm).DM.LoadFromMTToResource(MemTable, ResourceRel, tkNormEd);
                ResourceRel.IDMaster := Compon.ID;
                Compon.NormsResources.Resources.Add(ResourceRel);
                InsertValueToSortetRapList(ResourceRel, ObjFromMemTable);
              end;
            false: // Внести Норму
              begin
                SCSNorm := TSCSNorm.Create(GForm, ntProj);
                TF_Main(GForm).DM.LoadFromMTToNorm(MemTable, SCSNorm);
                SCSNorm.IDMaster := Compon.ID;
                Compon.NormsResources.Norms.Add(SCSNorm);
                InsertValueToSortetRapList(SCSNorm, ObjFromMemTable);
              end;
          end;
          MemTable.Next;
        end;

        Compon.ProjectOwner := TF_Main(GForm).GSCSBase.CurrProject;

        FDeletedNormIDs := TIntList.Create;
        FDeletedResIDs := TIntList.Create;
        try
          // Определяем новые нормы. ресурсы из свойства
          DefineComponNormResByProperty(Compon, Aproperty, false, FDeletedNormIDs, FDeletedResIDs);
          
          // Удаляем удаленные
          if (FDeletedNormIDs.Count > 0) or (FDeletedResIDs.Count > 0) then
          begin
            MemTable.Last;
            while Not MemTable.Bof do
            begin
              DeletedFromMemTable := false;
              if MemTable.FieldByName(fnIsResource).AsBoolean then
              begin
                if FDeletedResIDs.IndexOf(MemTable.FieldByName(fnID).AsInteger) <> -1 then
                begin
                  if Not MemTable.FieldByName(fnIsNew).AsBoolean then
                    GDeletedResourceID.Add(MemTable.FieldByName(fnID).AsInteger);
                  {if MemTableBookmark = MemTable.Bookmark then
                    MemTableBookmark := '';}
                  MemTable.Delete;
                  DeletedFromMemTable := true;
                end;
              end
              else
              if FDeletedNormIDs.IndexOf(MemTable.FieldByName(fnID).AsInteger) <> -1 then
              begin
                if Not MemTable.FieldByName(fnIsNew).AsBoolean then
                  GDeletedNormID.Add(MemTable.FieldByName(fnID).AsInteger);
               { if MemTableBookmark = MemTable.Bookmark then
                  MemTableBookmark := '';}
                MemTable.Delete;
                DeletedFromMemTable := true;
              end;

              if Not DeletedFromMemTable then
                MemTable.Prior;
            end;
            //GDeletedNormID.Assign(FDeletedNormIDs, laOr);
            //GDeletedResourceID.Assign(FDeletedResIDs, laOr);
          end;

          // Добавляем в таблицу новые нормы
          for i := 0 to Compon.NormsResources.Norms.Count - 1 do
          begin
            SCSNorm := Compon.NormsResources.Norms[i];
            if GetValueIndexFromSortedRapList(SCSNorm, ObjFromMemTable) = -1 then
            begin
              SCSNorm.ID := GenNewID(tkNormEd);
              SCSNorm.IsNew := True;
              TF_Main(GForm).DM.LoadFromNormToMT(SCSNorm, MemTable, meMake, -1, FTraccaLength, nil);
             { if MemTableBookmark = '' then
                MemTableBookmark := MemTable.Bookmark;}
            end;
          end;
          // Добавляем в таблицу новые ресурсы
          for i := 0 to Compon.NormsResources.Resources.Count - 1 do
          begin
            ResourceRel := Compon.NormsResources.Resources[i];
            if GetValueIndexFromSortedRapList(ResourceRel, ObjFromMemTable) = -1 then
            begin
              ResourceRel.ID := GenNewID(tkResourceRelEd);
              ResourceRel.IsNew := True;
              TF_Main(GForm).DM.LoadFromResourceToMT(ResourceRel, MemTable, meMake, tkNormEd, FTraccaLength, nil);
             { if MemTableBookmark = '' then
                MemTableBookmark := MemTable.Bookmark;}
            end;
          end;
        finally
          FreeAndNil(FDeletedNormIDs);
          FreeAndNil(FDeletedResIDs);
        end;
      finally
        MemTable.EnableControls;
        FreeAndNil(Compon);
        FreeAndNil(ObjFromMemTable);
        {if MemTableBookmark <> '' then
          MemTable.Bookmark := MemTableBookmark;}
        if MemTableBookmark <> nil then
        begin
          MemTable.GotoBookmark(MemTableBookmark);
          MemTable.FreeBookmark(MemTableBookmark);
        end;
      end;
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.DefineNormResByProperty', E.Message);
  end;
end;

procedure TF_AddComponent.DefineParamsBySupply(APriceSupply: Double; ADefIzm: Boolean);
var
  IDSuppliesKind: Integer;
  GUIDSuppliesKind: string;
  SuppliesKind: TSuppliesKind;
  Key: Word;

  NewComponPrice: Double;
begin
  IDSuppliesKind := GetIDFromComboBox(cbSuppliesKind);
  GUIDSuppliesKind := GetGUIDFromComboBox(cbSuppliesKind);

  SuppliesKind := FSuppliesKind; //F_NormBase.DM.GetSuppliesKindByID(IDSuppliesKind);
  if (SuppliesKind.ID <> 0) or (SuppliesKind.GUID <> '') then
  begin
    NewComponPrice := Round3(APriceSupply / SuppliesKind.UnitKolvo);
    if CheckPriceTransformToUOMByCompType(@FCurrComponentType) then
      // Конвертируем цену из ед. длины поставки (метры, или футы) в тек. ед.длины
      NewComponPrice := FloatInUOM(NewComponPrice, TF_Main(GForm).FUOM, TF_Main(GForm).FUOMSupplKind);


    //*** Если цена указане не как с НДС, то убираем знач- НДС с новой цены
    if not CheckBox_HasNds.Checked then
      NewComponPrice := PriceWithoutNDS(NewComponPrice, TF_Main(GForm).GNDS);

    CurrencyEdit_Price1.Value := NewComponPrice;
    DefineComponSecondPrice(CurrencyEdit_Price1.Value);

    ShowNDSPrice;

    //Key := 0;
    //CurrencyEdit_Price1_KeyUp(CurrencyEdit_Price1, Key, []);

    if ADefIzm then
    begin
      if SuppliesKind.Izm <> '' then
        if GetNameUOMForCompon('', @FCurrComponentType, TF_Main(GForm).FUOM) = '' then
          Edit_Izm.Text := SuppliesKind.Izm;
    end;
  end;
end;

procedure TF_AddComponent.DefineSupplyPriceByComponActualPrice;
begin
  DefineSupplyPriceByComponPrice(GetComponentActualPrice);
end;

procedure TF_AddComponent.DefineSupplyPriceByComponPrice(AComponPrice: Double);
var
  SavedOnChange: TNotifyEvent;
  ComponPrice: Double;
begin
  if FSuppliesKind.ID > 0 then
  begin
    SavedOnChange := cePriceSupply.Properties.OnChange;
    cePriceSupply.Properties.OnChange := nil;
    try
      ComponPrice := AComponPrice;
      if CheckPriceTransformToUOMByCompType(@FCurrComponentType) then
        // Конвертируем цену из тек. ед.длины в едю длины поставки (метры, или футы)
        ComponPrice := FloatInUOM(ComponPrice, TF_Main(GForm).FUOMSupplKind, TF_Main(GForm).FUOM);

      cePriceSupply.Value := RoundCP(ComponPrice * FSuppliesKind.UnitKolvo);
    finally
      cePriceSupply.Properties.OnChange := SavedOnChange;
    end;
  end;
end;

procedure TF_AddComponent.DefinecbApplyCompData;
begin
  //*** Применить для
  if cbApplyForCurrentDir.Checked then
    if TF_Main(GForm).GDBMode = bkNormBase then
    begin
      cbApplyComponData.Visible := IntToBool(FApplyComponElementsVisible[Grid.ActiveLevel.Index]);
      cbApplyComponData.Checked := IntToBool(FApplyComponElementsChecked[Grid.ActiveLevel.Index]);
    end;
end;

procedure TF_AddComponent.DefineUniversalInterfacesByProperty(AProp: PProperty; const ACompTypeSysName: string);
var
  MemTableProp: TkbmMemTable;
  //MemTablePropBookmark: string;
  MemTablePropBookmark, MemTablePortBookmark,MemTableInterfRelBookmark: TBookMark;
  MemTablePort: TkbmMemTable;
  //MemTablePortBookmark: string;
  MemTableInterfRel: TkbmMemTable;
  //MemTableInterfRelBookmark: string;
  MemTablePortInterfRel: TkbmMemTable;
  MemTableInterfInternalConn: TkbmMemTable;

  Spravochnik: TSpravochnik;
  //SprInterface: TNBInterface;

  mePortRel: TmeInterfaceRel;
  meInterfRel: TmeInterfaceRel;
  InterfFinded: Boolean;

  PortCount: Integer;
  PortWireCount: Integer;
  WireCount: Integer;

  PropGender: ShortInt;
  InterfSection: Double;
  InterfGuid: String;

  InterfRelCount: Integer;
  KeyValues: OleVariant;

  PropSysNamesConduitElmtSideDimensions: TStringList;
  IDChangedInterfaces: TIntList;

  FindedInterf: Boolean;

  i: Integer;

  function GetNewInterfPortRel(const AGUID: string): TmeInterfaceRel;
  var
    SprInterface: TNBInterface;
  begin
    Result.ID := GGenLastInterfID + 1;
    Result.ID_COMPONENT := GIDComponent;
    Result.IsLineCompon := FCurrComponentType.IsLine;
    Result.Color := clWhite;
    Result.ID_INTERFACE := 0;
    Result.IsBusy := biFalse;
    Result.SignType := oitProjectible;

    Result.Count := 1;

    SprInterface := Spravochnik.CreateInterfaceByStandartGUID(AGUID);
    Result.ID_INTERFACE := SprInterface.ID;
    Result.GUIDInterface := AGUID;
    Result.Name := SprInterface.Name;
  end;

begin
  try
    if (AProp <> nil) or (ACompTypeSysName <> '') then
    begin

      MemTableProp := TF_Main(GForm).DM.MemTable_PropertyEd;
      //MemTablePropBookmark := MemTableProp.Bookmark;
      MemTablePropBookmark := MemTableProp.GetBookmark;

      MemTablePort := TF_Main(GForm).DM.MemTable_PortEd;
      //MemTablePortBookmark := MemTablePort.Bookmark;
      MemTablePortBookmark := MemTablePort.GetBookmark;

      MemTableInterfRel := TF_Main(GForm).DM.MemTable_InterfaceRelEd;
      //MemTableInterfRelBookmark := MemTableInterfRel.Bookmark;
      MemTableInterfRelBookmark := MemTableInterfRel.getBookmark;

      MemTablePortInterfRel := TF_Main(GForm).DM.MemTable_PortInterfRelEd;
      MemTableInterfInternalConn := TF_Main(GForm).DM.mtInterfInternalConnEd;

      Spravochnik := TF_Main(GForm).GetSpravochnik;

      PropSysNamesConduitElmtSideDimensions := CreateStringListSorted; //TStringList.Create;
      PropSysNamesConduitElmtSideDimensions.Add(pnConduitElmentSideDimensions);  // Размеры стороны элемента канала
      PropSysNamesConduitElmtSideDimensions.Add(pnConduitElmentSide1Dimensions); // Размеры стороны 1 элемента канала
      PropSysNamesConduitElmtSideDimensions.Add(pnConduitElmentSide2Dimensions); // Размеры стороны 2 элемента канала
      PropSysNamesConduitElmtSideDimensions.Add(pnConduitElmentSide3Dimensions); // Размеры стороны 3 элемента канала
      PropSysNamesConduitElmtSideDimensions.Add(pnConduitElmentSide4Dimensions); // Размеры стороны 4 элемента канала

      MemTableProp.DisableControls;
      try
        ZeroMemory(@mePortRel, SizeOf(TmeInterfaceRel));
        ZeroMemory(@meInterfRel, SizeOf(TmeInterfaceRel));
        if AProp <> nil then
        begin
          // Количество портов и количество жил на порт
          if (AProp.SysName = pnPortCount) or (AProp.SysName = pnPortWireCount) then
          begin
            {IGOR} //D0000006314
            // оставим пока только в полностью лайт версии
            if GLiteVersion or GAllowConvertInterfToUniversal then
            begin
              PortCount := -1;
              PortWireCount := -1;

              if AProp.SysName = pnPortCount then
              begin
                // Количество портов и жил на порт
                PortCount := StrToIntDef(AProp.Value, 0);
                if MemTableProp.Locate(fnSysName, pnPortWireCount, []) then
                  PortWireCount := StrToIntDef(MemTableProp.FieldByName(fnPValue).AsString, 0);

                // Добавляем/изменяем порт
                if Not MemTablePort.Locate(fnGuidInterface, guidUniversalPort, []) then
                begin
                  mePortRel := GetNewInterfPortRel(guidUniversalPort);
                  mePortRel.IsPort := biTrue;

                  mePortRel.TypeI := itFunctional;
                  mePortRel.Kind := ikSplit;
                  mePortRel.Gender := gtFemale;
                  mePortRel.Multiple := biFalse;
                  mePortRel.Kolvo := PortCount;
                  AddInterfaceToMT(mePortRel);
                  mePortRel.ID := MemTablePort.FieldByName(fnID).AsInteger;
                end
                else
                begin
                  MemTablePort.Edit;
                  MemTablePort.FieldByName(fnKolvo).AsInteger := PortCount;
                  MemTablePort.FieldByName(fnIsModified).AsBoolean := true;
                  MemTablePort.Post;
                  mePortRel.ID := MemTablePort.FieldByName(fnID).AsInteger;
                end;
              end
              else
              if AProp.SysName = pnPortWireCount then
              begin
                // Количество жил на порт и портов
                PortWireCount := StrToIntDef(AProp.Value, 0);
                if MemTableProp.Locate(fnSysName, pnPortCount, []) then
                  PortCount := StrToIntDef(MemTableProp.FieldByName(fnPValue).AsString, 0);

                // Ищем ID порта
                if MemTablePort.Locate(fnGuidInterface, guidUniversalPort, []) then
                  mePortRel.ID := MemTablePort.FieldByName(fnID).AsInteger;
              end;

              // Добавляем/изменяем интерфейс + его привязку к порту
              if PortWireCount <> -1 then
              begin
                InterfRelCount := PortWireCount;
                if PortCount <> -1 then
                  InterfRelCount := PortCount * PortWireCount;

                // Добавляем/изменяем интерфейс
                KeyValues := VarArrayCreate([0, 2], varVariant);
                KeyValues[0] := guidUniversalWire;
                KeyValues[1] := itFunctional;
                KeyValues[2] := gtFemale;
                if Not MemTableInterfRel.Locate(fnGuidInterface+';'+fnTypeI+';'+fnGender, KeyValues, []) then
                begin
                  meInterfRel := GetNewInterfPortRel(guidUniversalWire);
                  meInterfRel.IsPort := biFalse;

                  meInterfRel.TypeI := itFunctional;
                  meInterfRel.Kind := ikNoSplit;
                  meInterfRel.Gender := gtFemale;
                  meInterfRel.Multiple := biFalse;
                  meInterfRel.Kolvo := InterfRelCount;
                  AddInterfaceToMT(meInterfRel);
                  meInterfRel.ID := MemTableInterfRel.FieldByName(fnID).AsInteger;
                end
                else
                begin
                  MemTableInterfRel.Edit;
                  MemTableInterfRel.FieldByName(fnKolvo).AsInteger := InterfRelCount;
                  MemTableInterfRel.FieldByName(fnIsModified).AsBoolean := true;
                  MemTableInterfRel.Post;
                  meInterfRel.ID := MemTableInterfRel.FieldByName(fnID).AsInteger;
                  meInterfRel.Name := MemTableInterfRel.FieldByName(fnName).AsString;
                end;

                // Добавляем/изменяем привязку интерфейса к порту
                if (mePortRel.ID <> 0) and (meInterfRel.ID <> 0) then
                begin
                  KeyValues := VarArrayCreate([0, 2], varVariant);
                  KeyValues[0] := mePortRel.ID; //fnIDPort
                  KeyValues[1] := meInterfRel.ID; //fnIDInterfRel
                  KeyValues[2] := rtPortInterfRel; //fnRelType
                  if Not MemTablePortInterfRel.Locate(fnIDPort+';'+fnIDInterfRel+';'+fnRelType, KeyValues, []) then
                  begin
                    MemTablePortInterfRel.Append;
                    MemTablePortInterfRel.FieldByName(fnRelType).AsInteger := rtPortInterfRel;
                    MemTablePortInterfRel.FieldByName(fnIDPort).AsInteger := mePortRel.ID;
                    MemTablePortInterfRel.FieldByName(fnIDInterfRel).AsInteger := meInterfRel.ID;
                    MemTablePortInterfRel.FieldByName(fnUnitInterfKolvo).AsInteger := PortWireCount;
                    MemTablePortInterfRel.FieldByName(fnName).AsString := meInterfRel.Name;
                    MemTablePortInterfRel.FieldByName(fnIsNew).AsBoolean := true;
                    MemTablePortInterfRel.Post;
                  end
                  else
                  begin
                    MemTablePortInterfRel.Edit;
                    MemTablePortInterfRel.FieldByName(fnUnitInterfKolvo).AsInteger := PortWireCount;
                    MemTablePortInterfRel.FieldByName(fnIsModified).AsBoolean := true;
                    MemTablePortInterfRel.Post;
                  end;
                end;
              end;
            end;  
          end
          else
          //Количество жил
          if AProp.SysName = pnWireCount then
          begin
            {IGOR} //D0000006314
            // оставим пока только в полностью лайт версии
            if GLiteVersion or GAllowConvertInterfToUniversal then
            begin
              WireCount := StrToIntDef(AProp.Value, 0);

              PropGender := gtMale;
              // Если компонент точечный (мало ли), то интерфейс будет мама
              if FCurrComponentType.IsLine = biFalse then
                PropGender := gtFemale;

              // Добавляем/изменяем интерфейс
              KeyValues := VarArrayCreate([0, 2], varVariant);
              KeyValues[0] := guidUniversalWire;
              KeyValues[1] := itFunctional;
              KeyValues[2] := PropGender;
              if Not MemTableInterfRel.Locate(fnGuidInterface+';'+fnTypeI+';'+fnGender, KeyValues, []) then
              begin
                meInterfRel := GetNewInterfPortRel(guidUniversalWire);
                meInterfRel.IsPort := biFalse;

                meInterfRel.TypeI := itFunctional;
                meInterfRel.Kind := ikNoSplit;
                meInterfRel.Gender := PropGender;
                meInterfRel.Multiple := biFalse;
                meInterfRel.Kolvo := WireCount;

                // Для линейного компонента создаем парный интерфейс
                if FCurrComponentType.IsLine = biTrue then
                begin
                  meInterfRel.Count := 2;
                  meInterfRel.ServiceIsPair := true;
                end;
                AddInterfaceToMT(meInterfRel);
                meInterfRel.ID := MemTableInterfRel.FieldByName(fnID).AsInteger;
              end
              else
              begin
                MemTableInterfRel.Edit;
                MemTableInterfRel.FieldByName(fnKolvo).AsInteger := WireCount;
                MemTableInterfRel.FieldByName(fnIsModified).AsBoolean := true;
                MemTableInterfRel.Post;
                meInterfRel.ID := MemTableInterfRel.FieldByName(fnID).AsInteger;
                meInterfRel.ID_Adverse := MemTableInterfRel.FieldByName(fnIDAdverse).AsInteger;

                // Для линейного компонента рихтуем парный интерфейс
                if FCurrComponentType.IsLine = biTrue then
                  if MemTableInterfRel.Locate(fnID, meInterfRel.ID_Adverse, []) then
                  begin
                    MemTableInterfRel.Edit;
                    MemTableInterfRel.FieldByName(fnKolvo).AsInteger := WireCount;
                    MemTableInterfRel.FieldByName(fnIsModified).AsBoolean := true;
                    MemTableInterfRel.Post;
                  end;
              end;
            end;  
          end
          else
          // Внешний/внутренний сечение - для кабеля и каб канала
          if (AProp.SysName = pnInSection) or (AProp.SysName = pnOutSection) then
          begin
            InterfSection := StrToFloatDef_My(AProp.Value, 0);
            InterfSection := FloatInUOM(InterfSection, umMM, umSM, 2);

            InterfFinded := false;

            // Добавляем/изменяем интерфейс
            InterfGuid := guidUniversalInConstr;
            PropGender := gtFemale;
            if AProp.SysName = pnOutSection then
            begin
              InterfGuid := guidUniversalOutConstr;
              PropGender := gtMale;
            end;
            KeyValues := VarArrayCreate([0, 2], varVariant);
            KeyValues[0] := InterfGuid;
            KeyValues[1] := itConstructive;
            KeyValues[2] := PropGender;
            if Not MemTableInterfRel.Locate(fnGuidInterface+';'+fnTypeI+';'+fnGender, KeyValues, []) then
            begin
              // Найти емкостной интерфейc КК - конструктив, род=PropGender, родной, многократный
              KeyValues := VarArrayCreate([0, 3], varVariant);
              KeyValues[0] := itConstructive;
              KeyValues[1] := PropGender;
              KeyValues[2] := True; //IsNative
              KeyValues[3] := biTrue; // Multiple
              if Not MemTableInterfRel.Locate(fnTypeI+';'+fnGender+';'+fnIsNative+';'+fnMultiple, KeyValues, []) then
              begin
                meInterfRel := GetNewInterfPortRel(InterfGuid);
                meInterfRel.IsPort := biFalse;

                meInterfRel.TypeI := itConstructive;
                meInterfRel.Kind := ikNoSplit;
                meInterfRel.Gender := PropGender;
                meInterfRel.Multiple := biTrue;
                meInterfRel.Kolvo := 1;
                meInterfRel.ValueI := InterfSection;
                AddInterfaceToMT(meInterfRel);
                meInterfRel.ID := MemTableInterfRel.FieldByName(fnID).AsInteger;
              end
              else
                InterfFinded := true;
            end
            else
              InterfFinded := true;

            if InterfFinded then
            begin
              MemTableInterfRel.Edit;
              MemTableInterfRel.FieldByName(fnValueI).AsFloat := InterfSection;
              MemTableInterfRel.FieldByName(fnIsModified).AsBoolean := true;
              MemTableInterfRel.Post;
            end;
          end
          else
          // Размеры сторон кабельного канала - применяется на каб канале
          if (AProp.SysName = pnConduitSideDimensions) or (AProp.SysName = pnCableChannelSideSection) then
          begin
            //18.01.2011
            // Если применяется свойство "Сечение стороны кабельного канала"
            // и в компонента есть более приоритетное своствой "Размеры сторон кабельного канала", то игнорируем
            if (AProp.SysName = pnCableChannelSideSection) and MemTableProp.Locate(fnSysName, pnConduitSideDimensions, []) then
              Exit; ///// EXIT /////

            InterfFinded := false;

            PropGender := gtMale;
            // Если компонент точечный, то интерфейс будет мама
            if FCurrComponentType.IsLine = biFalse then
              PropGender := gtFemale;

            // Добавляем/изменяем интерфейс
            KeyValues := VarArrayCreate([0, 2], varVariant);
            KeyValues[0] := guidUniversalChannelSide;
            KeyValues[1] := itFunctional;
            KeyValues[2] := PropGender;
            if Not MemTableInterfRel.Locate(fnGuidInterface+';'+fnTypeI+';'+fnGender, KeyValues, []) then
            begin
              // Найти интерфейc стороны КК - функционал, папа, родной, немногократный
              KeyValues := VarArrayCreate([0, 3], varVariant);
              KeyValues[0] := itFunctional;
              KeyValues[1] := gtMale;
              KeyValues[2] := True; //IsNative
              KeyValues[3] := biFalse;
              if Not MemTableInterfRel.Locate(fnTypeI+';'+fnGender+';'+fnIsNative+';'+fnMultiple, KeyValues, []) then
              begin
                meInterfRel := GetNewInterfPortRel(guidUniversalChannelSide);
                meInterfRel.IsPort := biFalse;

                meInterfRel.TypeI := itFunctional;
                meInterfRel.Kind := ikNoSplit;
                meInterfRel.Gender := PropGender;
                meInterfRel.Multiple := biFalse;
                meInterfRel.Kolvo := 1;
                meInterfRel.SideSection := AProp.Value;

                // Для линейного компонента создаем парный интерфейс
                if FCurrComponentType.IsLine = biTrue then
                begin
                  meInterfRel.Count := 2;
                  meInterfRel.ServiceIsPair := true;
                end;
                AddInterfaceToMT(meInterfRel);
                meInterfRel.ID := MemTableInterfRel.FieldByName(fnID).AsInteger;
              end
              else
                InterfFinded := true;
            end
            else
              InterfFinded := true;

            if InterfFinded then
            begin
              MemTableInterfRel.Edit;
              MemTableInterfRel.FieldByName(fnSideSection).AsString := AProp.Value;
              MemTableInterfRel.FieldByName(fnIsModified).AsBoolean := true;
              MemTableInterfRel.Post;
              meInterfRel.ID := MemTableInterfRel.FieldByName(fnID).AsInteger;
              meInterfRel.ID_Adverse := MemTableInterfRel.FieldByName(fnIDAdverse).AsInteger;

              // Для линейного компонента рихтуем парный интерфейс
              if FCurrComponentType.IsLine = biTrue then
                if MemTableInterfRel.Locate(fnID, meInterfRel.ID_Adverse, []) then
                begin
                  MemTableInterfRel.Edit;
                  MemTableInterfRel.FieldByName(fnSideSection).AsString := AProp.Value;
                  MemTableInterfRel.FieldByName(fnIsModified).AsBoolean := true;
                  MemTableInterfRel.Post;
                end;
            end;
          end
          else
          // Размеры стороны элемента канала
          if PropSysNamesConduitElmtSideDimensions.IndexOf(AProp.SysName) <> -1 then
          begin
            IDChangedInterfaces := TIntList.Create;
            try
              // Для каждого свойства, определяющего размерность, определяем интерфейс
              for i := 0 to PropSysNamesConduitElmtSideDimensions.Count - 1 do
              begin
                if MemTableProp.Locate(fnSysName, PropSysNamesConduitElmtSideDimensions[i], []) then
                begin
                  FindedInterf := false;
                  MemTableInterfRel.First;
                  while Not MemTableInterfRel.Eof do
                  begin
                    if (MemTableInterfRel.FieldByName(fnGuidInterface).AsString = guidUniversalChannelSide) and
                       (MemTableInterfRel.FieldByName(fnIsPort).AsInteger = biFalse) and
                       (IDChangedInterfaces.IndexOf(MemTableInterfRel.FieldByName(fnID).AsInteger) = -1) and
                       (MemTableInterfRel.FieldByName(fnGender).AsInteger = gtFemale) and
                       (MemTableInterfRel.FieldByName(fnTypeI).AsInteger = itFunctional) then
                    begin
                      MemTableInterfRel.Edit;
                      MemTableInterfRel.FieldByName(fnSideSection).AsString := MemTableProp.FieldByName(fnPValue).AsString;
                      MemTableInterfRel.FieldByName(fnIsModified).AsBoolean := true;
                      MemTableInterfRel.Post;

                      FindedInterf := true;
                      Break; //// BREAK ////
                    end;
                    MemTableInterfRel.Next;
                  end;
                  if Not FindedInterf then
                  begin
                    meInterfRel := GetNewInterfPortRel(guidUniversalChannelSide);

                    meInterfRel.IsPort := biFalse;
                    meInterfRel.TypeI := itFunctional;
                    meInterfRel.Kind := ikNoSplit;
                    meInterfRel.Gender := gtFemale;
                    meInterfRel.Multiple := biFalse;
                    meInterfRel.Kolvo := 1;
                    meInterfRel.SideSection := MemTableProp.FieldByName(fnPValue).AsString;

                    AddInterfaceToMT(meInterfRel);
                  end;
                  IDChangedInterfaces.Add(MemTableInterfRel.FieldByName(fnID).AsInteger);
                end;
              end;
            finally
              FreeAndNil(IDChangedInterfaces);
            end;
          end;
        end
        else
        if ACompTypeSysName <> '' then
        begin
          // Если тип компонента Патч корд
          if ACompTypeSysName = ctsnPatchCord then
          begin
            {IGOR} //D0000006314
            // оставим пока только в полностью лайт версии
            if GLiteVersion or GAllowConvertInterfToUniversal then
            begin
              // Добавляем интерфейсы
              KeyValues := VarArrayCreate([0, 2], varVariant);
              KeyValues[0] := guidUniversalPort;
              KeyValues[1] := itFunctional;
              KeyValues[2] := gtMale;
              if Not MemTableInterfRel.Locate(fnGuidInterface+';'+fnTypeI+';'+fnGender, KeyValues, []) then
              begin
                meInterfRel := GetNewInterfPortRel(guidUniversalPort);
                meInterfRel.IsPort := biFalse;

                meInterfRel.TypeI := itFunctional;
                meInterfRel.Kind := ikSplit;
                meInterfRel.Gender := gtMale;
                meInterfRel.Multiple := biFalse;
                meInterfRel.Kolvo := 1;
                AddInterfaceToMT(meInterfRel);
                meInterfRel.ID := MemTableInterfRel.FieldByName(fnID).AsInteger;
                AddInterfaceToMT(meInterfRel);
                mePortRel.ID := MemTableInterfRel.FieldByName(fnID).AsInteger;
              end;

              // Добавляем привязку интерфейсов
              if (mePortRel.ID <> 0) and (meInterfRel.ID <> 0) then
              begin
                KeyValues := VarArrayCreate([0, 2], varVariant);
                KeyValues[0] := mePortRel.ID; //fnIDPort
                KeyValues[1] := meInterfRel.ID; //fnIDInterfRel
                KeyValues[2] := rtInterfInternalConn; //fnRelType
                if Not MemTableInterfInternalConn.Locate(fnIDPort+';'+fnIDInterfRel+';'+fnRelType, KeyValues, []) then
                begin
                  MemTableInterfInternalConn.Append;
                  MemTableInterfInternalConn.FieldByName(fnRelType).AsInteger := rtInterfInternalConn;
                  MemTableInterfInternalConn.FieldByName(fnIDPort).AsInteger := meInterfRel.ID;
                  MemTableInterfInternalConn.FieldByName(fnIDInterfRel).AsInteger := mePortRel.ID;
                  MemTableInterfInternalConn.FieldByName(fnName).AsString := meInterfRel.Name;
                  MemTableInterfInternalConn.FieldByName(fnUnitInterfKolvo).AsInteger := 1;
                  MemTableInterfInternalConn.FieldByName(fnGender).AsInteger := gtMale;
                  MemTableInterfInternalConn.FieldByName(fnIsNew).AsBoolean := true;
                  MemTableInterfInternalConn.Post;
                end;
              end;
            end;  
          end;
        end;
      finally
        MemTableProp.EnableControls;
        { MemTableProp.Bookmark := MemTablePropBookmark;
        MemTablePort.Bookmark := MemTablePortBookmark;
        MemTableInterfRel.Bookmark := MemTableInterfRelBookmark;}

        if MemTablePropBookmark <> nil then
        begin
           MemTableProp.GotoBookmark(MemTablePropBookmark);
           MemTableProp.FreeBookmark(MemTablePropBookmark);
        end;
        if MemTablePortBookmark <> nil then
        begin
          MemTablePort.GotoBookmark(MemTablePortBookmark);
          MemTablePort.FreeBookmark(MemTablePortBookmark);
        end;
        if MemTableInterfRelBookmark <> nil then
        begin
          MemTableInterfRel.GotoBookmark(MemTableInterfRelBookmark);
          MemTableInterfRel.FreeBookmark(MemTableInterfRelBookmark);
        end;

        FreeAndNil(PropSysNamesConduitElmtSideDimensions);
      end;
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.DefineUniqueInterfacesByProperty', E.Message);
  end;
end;

procedure TF_AddComponent.DeleteNormResByIDCompPropRel(AIDCompPropRel: Integer);
var
  MemTable: TkbmMemTable;
  //MemTableBookmark: string;
  MemTableBookmark: TBookMark;
begin
  try
    MemTable := TF_Main(GForm).DM.MemTable_NormsEd;
    //MemTableBookmark := MemTable.Bookmark;
    MemTableBookmark := MemTable.GetBookmark;
    MemTable.DisableControls;
    try
      MemTable.Last;
      while Not MemTable.Bof do
      begin
        if MemTable.FieldByName(fnIDCompPropRel).AsInteger = AIDCompPropRel then
        begin
          if MemTable.FieldByName(fnIsResource).AsBoolean then
          begin
            if Not MemTable.FieldByName(fnIsNew).AsBoolean then
              GDeletedResourceID.Add(MemTable.FieldByName(fnID).AsInteger);
          end
          else
          begin
            if Not MemTable.FieldByName(fnIsNew).AsBoolean then
              GDeletedNormID.Add(MemTable.FieldByName(fnID).AsInteger);
          end;

          {if MemTableBookmark = MemTable.Bookmark then
            MemTableBookmark := '';}
          MemTable.Delete;
        end
        else
          MemTable.Prior;
      end;
    finally
      MemTable.EnableControls;
      {
      if MemTableBookmark <> '' then
        MemTable.Bookmark := MemTableBookmark;
      }
      if MemTableBookmark <> nil then
      begin
        MemTable.GotoBookmark(MemTableBookmark);
        MemTable.FreeBookmark(MemTableBookmark);
      end;
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.DeleteComponNormResByIDCompPropRel', E.Message);
  end;
end;

procedure TF_AddComponent.LoadNetTypesToForm;
begin
  try
    ComboBox_NetType.Properties.OnChange := nil;
    ComboBox_NetType.Properties.BeginUpdate;
    try
      FSpravochnik.LoadNetTypesToStrings(ComboBox_NetType.Properties.Items, true);
      ComboBox_NetType.ItemIndex := 0; //18.02.2009
    finally
      ComboBox_NetType.Properties.EndUpdate;
    end;
    ComboBox_NetType.Properties.OnChange := ComboBox_NetTypePropertiesChange;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.LoadNetTypesToForm', E.Message);
  end;
end;

procedure TF_AddComponent.LoadCompSpecificationToForm;
begin
  try
    cbSpecification.Properties.BeginUpdate;
    try
      FillComboBox(cbSpecification, F_NormBase, true, tnFiles, fnID, fnFileName, '', 0);
    finally
      cbSpecification.Properties.EndUpdate;
    end;
    cbSpecification.ItemIndex := 0;
  except
    on E: Exception do AddExceptionToLogExt(ClassName, MethodName(@TF_AddComponent.LoadCompSpecificationToForm), E.Message);
  end;
end;

procedure TF_AddComponent.LoadProducersToForm;
begin
  try
    ComboBox_Producer.Properties.BeginUpdate;
    try
      FSpravochnik.LoadProducersToStrings(ComboBox_Producer.Properties.Items, true);
    finally
      ComboBox_Producer.Properties.EndUpdate;
    end;
    ComboBox_Producer.ItemIndex := 0;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.LoadProducersToForm', E.Message);
  end;
end;

procedure TF_AddComponent.LoadSuppliesKindsToForm;
begin
  try
    //FillComboBox(cbSuppliesKind, F_NormBase, True, tnSuppliesKinds, fnID, fnName, strNoDefined, 0);
    cbSuppliesKind.Properties.OnChange := nil;
    cbSuppliesKind.Properties.BeginUpdate;
    try
      FSpravochnik.LoadSuppliesKindsToStrings(cbSuppliesKind.Properties.Items, true);
    finally
      cbSuppliesKind.Properties.EndUpdate;
    end;
    cbSuppliesKind.Properties.OnChange := cbSuppliesKindPropertiesChange;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.LoadSuppliesKindsToForm', E.Message);
  end;
end;

procedure TF_AddComponent.SetNewCompPropIDsToNormRes(AOldCompPropIDs, ANewCompPropIDs: TintList);
var
  MemTable: TkbmMemTable;
  //MemTableBookmark: String;
  MemTableBookmark: TBookMark;
  IDCompPropRel: Integer;
  IDIndex: Integer;
begin
  try
    if (AOldCompPropIDs.Count > 0) and (ANewCompPropIDs.Count > 0) then
    begin
      MemTable := TF_Main(GForm).DM.MemTable_NormsEd;
      //MemTableBookmark := MemTable.Bookmark;
      MemTableBookmark := MemTable.GetBookmark;
      MemTable.DisableControls;
      try
        MemTable.First;
        while Not MemTable.Eof do
        begin
          if MemTable.FieldByName(fnIsNew).AsBoolean then
          begin
            IDCompPropRel := MemTable.FieldByName(fnIDCompPropRel).AsInteger;
            if IDCompPropRel <> 0 then
            begin
              IDIndex := AOldCompPropIDs.IndexOf(IDCompPropRel);
              if IDIndex <> -1 then
              begin
                IDCompPropRel := ANewCompPropIDs[IDIndex];
                MemTable.Edit;
                MemTable.FieldByName(fnIDCompPropRel).AsInteger := IDCompPropRel;
                MemTable.Post;
              end;
            end;
          end;
          MemTable.Next;
        end;
      finally
        MemTable.EnableControls;
        //MemTable.Bookmark := MemTableBookmark;
        if MemTableBookmark <> nil then
        begin
          MemTable.GotoBookmark(MemTableBookmark);
          MemTable.FreeBookmark(MemTableBookmark);
        end;
      end;
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.SetNewCompPropIDsToNormRes', E.Message);
  end;
end;


procedure TF_AddComponent.SetValueToAllApplyCheckBoxes(AValue: Boolean);
var
  i: Integer;
  ApplyCheckBox: TcxCheckBox;
begin
  try
    for i := 0 to FApplyCheckBoxes.Count - 1 do
    begin
      ApplyCheckBox := TcxCheckBox(FApplyCheckBoxes[i]);
      ApplyCheckBox.Checked := AValue;
    end;
    for i := 0 to FApplyComponElementsChecked.Count - 1 do
      FApplyComponElementsChecked[i] := BoolToInt(AValue);
    DefinecbApplyCompData;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.SetValueToAllApplyCheckBoxes', E.Message);
  end;
end;

procedure TF_AddComponent.SetValueToCurrPageApplyCheckBoxes(AValue: Boolean);
var
  i, j: Integer;
  CurrPageIndex: Integer;
  ApplyCheckBox: TcxCheckBox;
begin
  try
    CurrPageIndex := pcMain.ActivePageIndex;
    for i := 0 to FApplyCheckBoxesPageIndex.Count - 1 do
    begin
      if FApplyCheckBoxesPageIndex[i] = CurrPageIndex then
      begin
        ApplyCheckBox := TcxCheckBox(FApplyCheckBoxes[i]);
        ApplyCheckBox.Checked := AValue;

        if ApplyCheckBox = cbApplyComponData then
          for j := 0 to FApplyComponElementsChecked.Count - 1 do
            FApplyComponElementsChecked[j] := BoolToInt(AValue);
      end;
    end;
  except
    on E: Exception do AddExceptionToLogEx('TF_AddComponent.SetValueToCurrPageApplyCheckBoxes', E.Message);
  end;
end;

procedure TF_AddComponent.VisibleApplyCheckBoxes(AVisible, ASetAsChecked: Boolean);
var
  i: Integer;
  CurrCheckBox: TcxCheckBox;
begin
  for i := 0 to FApplyCheckBoxes.Count - 1 do
  begin
    CurrCheckBox := TcxCheckBox(FApplyCheckBoxes[i]);
    if AVisible then
    begin
      if (FApplyControls[i] = Grid) and (TF_Main(GForm).GDBMode = bkProjectManager) then
        Continue; ///// CONTINUE /////
      if TControl(FApplyControls[i]).Visible and TControl(FApplyControls[i]).Enabled then
        CurrCheckBox.Visible := true
      else
        CurrCheckBox.Visible := false;

      if TF_Main(GForm).GDBMode = bkProjectManager then
      begin
        if CurrCheckBox = cbApplySpecification then
          CurrCheckBox.Visible := false;
      end;
    end
    else
      CurrCheckBox.Visible := false;

    if ASetAsChecked then
      CurrCheckBox.Checked := true;
    if AVisible then
    begin
      CurrCheckBox.Style.BorderColor := FApplyCheckBoxesBorderColor;
      CurrCheckBox.Style.BorderStyle := FApplyCheckBoxesBorderStyle;
    end;
  end;
  if AVisible then
    DefinecbApplyCompData;
end;

procedure TF_AddComponent.Act_CancelExecute(Sender: TObject);
var
  MessResult: Integer;
begin
  if GFormMode = fmView then
  begin
    ModalResult := mrCancel;
    Exit; ///// EXIT /////
  end;

  MessResult := ID_NO;
  if GWasChanging then
    MessResult := MessageModal(cQuastSaveChanging, Application.Title, MB_YESNOCANCEL or MB_ICONQUESTION);
  case MessResult of
    ID_YES:
      BitBtn_OK.Click;
    ID_NO:
      BitBtn_Cancel.Click;
  end;
end;

procedure TF_AddComponent.Edit_NamePropertiesChange(Sender: TObject);
begin
  GWasChanging := true;
end;

procedure TF_AddComponent.Edit_NameShortPropertiesChange(Sender: TObject);
begin
  GWasChanging := true;
end;

procedure TF_AddComponent.Edit_NameMarkPropertiesChange(Sender: TObject);
begin
  GWasChanging := true;
end;

procedure TF_AddComponent.Edit_NameDblClick(Sender: TObject);
begin
  if GComponGuidNB <> '' then
  begin
    Clipboard.Open;
    Clipboard.AsText := GComponGuidNB;
    Clipboard.Close;
  end;
end;

procedure TF_AddComponent.Edit_NameMarkEditing(Sender: TObject;
  var CanEdit: Boolean);
begin
  //CheckBox_IsUserMark.Checked := true;
  rbMarkByDefault.Checked := true;
end;

procedure TF_AddComponent.rbMarkByDefaultClick(Sender: TObject);
begin
  GWasChanging := true;
end;

procedure TF_AddComponent.rbMarkByTemplateClick(Sender: TObject);
begin
  Edit_NameMark.Text := GetComponentNameMarkByTemplate;
  GWasChanging := true;
end;

procedure TF_AddComponent.Edit_IzmPropertiesChange(Sender: TObject);
begin
  GWasChanging := True;
end;

procedure TF_AddComponent.ComboBox_NetTypePropertiesChange(
  Sender: TObject);
begin
  GWasChanging := true;
end;

procedure TF_AddComponent.ComboBox_ComponentTypePropertiesChange(
  Sender: TObject);
begin
  FChangedComponTypeInCombo := true;
end;

procedure TF_AddComponent.GT_InterfaceFocusedRecordChanged(
  Sender: TcxCustomGridTableView; APrevFocusedRecord,
  AFocusedRecord: TcxCustomGridRecord;
  ANewItemRecordFocusingChanged: Boolean);
begin
  {with TF_Main(GForm) do
    if GDBMode = bkProjectManager then
      if DM.MemTable_InterfaceRelEd.FieldByName('IsNew').AsBoolean = true then
      begin
        Self.Act_Edit.Enabled := true;
        Self.Act_Del.Enabled := true;
      end
      else
      begin
        Self.Act_Edit.Enabled := false;
        Self.Act_Del.Enabled := false;
      end; }
end;

procedure TF_AddComponent.GT_PortFocusedRecordChanged(
  Sender: TcxCustomGridTableView; APrevFocusedRecord,
  AFocusedRecord: TcxCustomGridRecord;
  ANewItemRecordFocusingChanged: Boolean);
begin
  {with TF_Main(GForm) do
    if GDBMode = bkProjectManager then
      if DM.MemTable_PortEd.FieldByName('IsNew').AsBoolean = true then
        begin
            Self.Act_Edit.Enabled := true;
            Self.Act_Del.Enabled := true;
        end
      else
        begin
            Self.Act_Edit.Enabled := false;
            Self.Act_Del.Enabled := false;
        end;}
end;

procedure TF_AddComponent.GT_PropertyFocusedRecordChanged(
  Sender: TcxCustomGridTableView; APrevFocusedRecord,
  AFocusedRecord: TcxCustomGridRecord;
  ANewItemRecordFocusingChanged: Boolean);
begin
  with TF_Main(GForm) do
    if GDBMode = bkProjectManager then
    begin
      {if DM.MemTable_PropertyEd.FieldByName('IsNew').AsBoolean = true then
      begin
        Self.Act_Edit.Enabled := true;
        Self.Act_Del.Enabled := true;
      end
      else
      begin
        Self.Act_Edit.Enabled := false;
        Self.Act_Del.Enabled := false;
      end;}

      //if DM.CanEditProperty(DM.MemTable_PropertyEd) then
      //  GT_PROPERTY.OptionsSelection.CellSelect := true
      //else
      //  GT_PROPERTY.OptionsSelection.CellSelect := false;
    end;
end;

procedure TF_AddComponent.GT_InterfaceNppGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: string);
begin
  if AText = '0' then
    AText := cAddComponent_Msg10;
end;

procedure TF_AddComponent.GT_PortNppGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: string);
begin
  if AText = '0' then
    AText := cAddComponent_Msg10;
end;

procedure TF_AddComponent.GT_CableCanalConnectorsConnectorTypeGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: string);
begin
  if AText <> '' then
    AText := GetCableChannelElementName(StrToInt(AText));
  {if AText = IntToStr(contCork) then
    AText := ctnCork
  else
  if AText = IntToStr(contAnglePlane) then
    AText := ctnAnglePlane
  else
  if AText = IntToStr(contTjoin) then
    AText := ctnTjoin
  else
  if AText = IntToStr(contAngleIn) then
    AText := ctnAngleIn
  else
  if AText = IntToStr(contAngleOut) then
    AText := ctnAngleOut
  else
  if AText = IntToStr(contADapter) then
    AText := ctnADapter
  else
  if AText = IntToStr(contConnector) then
    AText := ctnConnector;}
end;

procedure TF_AddComponent.CheckBox_ApplyForProjectPropertiesChange(
  Sender: TObject);
begin
  CheckBox_ApplyForList.Enabled := not TRzCheckBox(Sender).Checked;
  //17.08.2012 OncbApplyForChange(Sender);
  //17.08.2012 EnableDisableApplyIncludingMark;
  OncbApplyForPMChange(Sender);
end;

procedure TF_AddComponent.CheckBox_ApplyForListPropertiesChange(
  Sender: TObject);
begin
  //17.08.2012 OncbApplyForChange(Sender);
  //17.08.2012 EnableDisableApplyIncludingMark;
  OncbApplyForPMChange(Sender);
end;

procedure TF_AddComponent.Edit_NameShortKeyPress(Sender: TObject;
  var Key: Char);
begin
  GChangedNameShort := true;
end;

procedure TF_AddComponent.Timer_AfterEditPropertyTimer(Sender: TObject);
begin
  GWasChanging := True;
  Timer_AfterEditProperty.Enabled := false;

  GT_PROPERTY.DataController.Post;
  GT_PROPERTY.OnEditValueChanged := GT_PROPERTYEditValueChanged;
end;

procedure TF_AddComponent.GT_PropertyEditValueChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
begin
  if GT_PROPERTY.DataController.IsEditing then
  begin
    GT_PROPERTY.OnEditValueChanged := nil;
    Timer_AfterEditProperty.Enabled := true;
  end;
end;

procedure TF_AddComponent.GT_PropertyEditChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
begin
  //with TF_Main(GForm).DM do
  //  MemTable_PropertyEd.AfterEdit := MemTable_PropertyEdAfterEdit;

  with TF_Main(GForm).DM do
  begin
    if MemTable_PropertyEd.FieldByName(fnIDDataType).AsInteger = dtCompStateType then
      LoadComponIcon(GIDObjectIcon, GGUIDObjectIcon, Image_CompIcons);
  end;
end;

procedure TF_AddComponent.SpinEdit_UserLengthPropertiesEditValueChanged(
  Sender: TObject);
var
  WholeLength: Double;
  SavedUserLength: Double;
  Compon: TSCSComponent;
begin
  GChangedUserLength := True;
  GWasChanging := True;
  Compon := nil;
  WholeLength := 0;

  if TF_Main(GForm).GDBMode = bkProjectManager then
    if TF_Main(GForm).GSCSBase.SCSComponent.IsLine = biTrue then
    begin
      Compon := TF_Main(GForm).GSCSBase.CurrProject.GetComponentFromReferences(GIDComponent);
      if Assigned(Compon) then
      begin
        SavedUserLength := Compon.UserLength;
        try
          Compon.UserLength := FloatInUOM(SpinEdit_UserLength.Value, TF_Main(GForm).FUOM, umMetr);
          WholeLength := Compon.GetWholeLength;
        finally
          Compon.UserLength := SavedUserLength;
        end;
      end;
      SetPropertyValueBySysNameAsFloat(pnLength, WholeLength);
    end;
end;

procedure TF_AddComponent.GT_NORMSCellClick(Sender: TcxCustomGridTableView;
  ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
  AShift: TShiftState; var AHandled: Boolean);
begin
  //if TF_Main(GForm).DM.MemTable_NormsEd.RecNo > 1 then
  if ACellViewInfo.Item.Index = finIsOn then //*** Поле "Включен"
    with TF_Main(GForm).DM do
    begin
      if MemTable_NormsEd.RecordCount > 0 then // Tolik 28/12/2019 --
      begin
        MemTable_NormsEd.Edit;
        MemTable_NormsEd.FieldByName('IsOn').AsInteger := 1 - MemTable_NormsEd.FieldByName('IsOn').AsInteger;
        MemTable_NormsEd.FieldByName('IsModified').AsBoolean := true;
        MemTable_NormsEd.Post;
      end;
      CalcWorkCost;
      AHandled := true;
    end;
end;

procedure TF_AddComponent.GT_NORMSEditing(Sender: TcxCustomGridTableView;
  AItem: TcxCustomGridTableItem; var AAllow: Boolean);
begin
  with TF_Main(GForm).DM do
  begin
    MemTable_NormsEd.Edit;
    MemTable_NormsEd.FieldByName(fnIsModified).AsBoolean := true;
    MemTable_NormsEd.Post;
  end;

  //if AItem = GT_NORMSExpenseForLength then
  //  AItem.EditValue := GetNORMExpenseForLengthDisplayText(AItem.EditValue);
end;

procedure TF_AddComponent.GT_NORMSFocusedRecordChanged(
  Sender: TcxCustomGridTableView; APrevFocusedRecord,
  AFocusedRecord: TcxCustomGridRecord;
  ANewItemRecordFocusingChanged: Boolean);
var
  IsResource: Boolean;
  IsNormFromInterface: Boolean;
begin
  IsResource := false;
  IsNormFromInterface := false;
  if TF_Main(GForm).DM.MemTable_NormsEd.Active and (TF_Main(GForm).DM.MemTable_NormsEd.RecordCount > 0) then
  begin
    IsResource := TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnIsResource).AsBoolean;
    if not IsResource then
      IsNormFromInterface := IntToBool(TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnIsFromInterface).AsInteger);
  end;
  GroupBox_ResourcesRel.Enabled := not IsResource;
  GT_NORMSLaborTime.Options.Editing := Not IsResource; //01.11.2013
  GT_NORMSPricePerTime.Options.Editing := Not IsResource; //01.11.2013
  GT_NORMSCost.Options.Editing := IsResource or not IsNormFromInterface; //24.09.2010 IsResource;
  GT_NORMSKolvo.Options.Editing := IsResource or not IsNormFromInterface;
  GT_NORMSExpenseForLength.Options.Editing := IsResource or not IsNormFromInterface;
  GT_NORMSCountForPoint.Options.Editing := GT_NORMSExpenseForLength.Options.Editing;
  GT_NORMSStepOfPoint.Options.Editing := GT_NORMSExpenseForLength.Options.Editing;
  //GT_NORMSExpenseForSection.Options.Editing := GT_NORMSExpenseForLength.Options.Editing;
  //GT_NORMSTotalCost.Options.Editing := IsResource;

  //*** Количество знаков после хапятой
  if IsResource then
  begin
    TcxCurrencyEditProperties(GT_NORMSKolvo.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(GT_NORMSKolvo.Properties).DecimalPlaces := FloatPrecision;
  end
  else
  begin
    TcxCurrencyEditProperties(GT_NORMSKolvo.Properties).DisplayFormat := GetDisplayFormatForFloatByPrecision(PrecisionNormKolvo);
    TcxCurrencyEditProperties(GT_NORMSKolvo.Properties).DecimalPlaces := PrecisionNormKolvo;
  end;

  EnableEditDelNorm;
end;


procedure TF_AddComponent.GT_NORMSLaborTimePropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
var
  IsCalcNormTotal: Boolean;
begin
  Error := false;
  with TF_Main(GForm).DM do
  begin
    if DisplayValue = '' then
    begin
      DisplayValue := MemTable_NormsEd.FieldByName(fnLaborTime).AsFloat;
      Exit; ///// EXIT /////
    end;

    MemTable_NormsEd.Edit;
    MemTable_NormsEd.FieldByName(fnLaborTime).AsFloat := DisplayValue;
    MemTable_NormsEd.Post;

    CalcNormCostTime(MemTable_NormsEd, fnLaborTime, IsCalcNormTotal); //01.11.2013
    if IsCalcNormTotal = true then
    begin
      CalcNormTatalCostInMT(MemTable_NormsEd, FTraccaLength);
      CalcWorkCost;
    end;
  end;
end;

procedure TF_AddComponent.GT_NORMSPricePerTimePropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
var
  IsCalcNormTotal: Boolean;
begin
  Error := false;
  with TF_Main(GForm).DM do
  begin
    if DisplayValue = '' then
    begin
      DisplayValue := MemTable_NormsEd.FieldByName(fnPricePerTime).AsFloat;
      Exit; ///// EXIT /////
    end;

    MemTable_NormsEd.Edit;
    MemTable_NormsEd.FieldByName(fnPricePerTime).AsFloat := DisplayValue;
    MemTable_NormsEd.Post;

    CalcNormCostTime(MemTable_NormsEd, fnPricePerTime, IsCalcNormTotal); //01.11.2013
    if IsCalcNormTotal = true then
    begin
      CalcNormTatalCostInMT(MemTable_NormsEd, FTraccaLength);
      CalcWorkCost;
    end;
  end;
end;


procedure TF_AddComponent.GT_NORMSCostPropertiesValidate(Sender: TObject;
  var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
//var
//  Cost, Kolvo, TotalCost: Double;
var
  IsCalcNormTotal: Boolean;
begin
  Error := false;
  with TF_Main(GForm).DM do
  begin
    if DisplayValue = '' then
    begin
      DisplayValue := MemTable_NormsEd.FieldByName(fnCost).AsFloat;
      Exit; ///// EXIT /////
    end;
    //Cost := DisplayValue;
    //Kolvo := MemTable_NormsEd.FieldByName(fnKolvo).AsFloat;
    //CalcNormTatalCostInMT(MemTable_NormsEd, Cost, Kolvo);

    MemTable_NormsEd.Edit;
    MemTable_NormsEd.FieldByName(fnCost).AsFloat := DisplayValue;
    MemTable_NormsEd.Post;

    CalcNormCostTime(MemTable_NormsEd, fnCost, IsCalcNormTotal); //01.11.2013

    CalcNormTatalCostInMT(MemTable_NormsEd, FTraccaLength);

    //TotalCost := RoundCP(Cost * Kolvo);
    //MemTable_NormsEd.Edit;
    //MemTable_NormsEd.FieldByName('Total_Cost').AsFloat := TotalCost;
    //MemTable_NormsEd.FieldByName('Cost').AsFloat := Cost;
    //MemTable_NormsEd.Post;
  end;
  CalcWorkCost;
end;

// Added by Tolik
// Функция извлекает число из измерителя,если оно там есть
procedure TF_AddComponent.GT_NORMSKolvoPropertiesValidate(Sender: TObject;
  var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean);
var
  Cost, Kolvo, TotalCost: Double;
begin
  Error := false;
  with TF_Main(GForm).DM do
  begin
    //Cost := MemTable_NormsEd.FieldByName(fnCost).AsFloat;
    //Kolvo := DisplayValue;
    if DisplayValue = '' then
    begin
      DisplayValue := MemTable_NormsEd.FieldByName(fnKolvo).AsFloat;
      Exit; ///// EXIT /////
    end
    else
      if GetExpenceFromIzm(MemTable_NormsEd.FieldByName(fnIzm).AsString) <> 1 then
        DisplayValue := DisplayValue*GetExpenceFromIzm(MemTable_NormsEd.FieldByName(fnIzm).AsString);

    MemTable_NormsEd.Edit;
    MemTable_NormsEd.FieldByName(fnKolvo).AsFloat := DisplayValue;

    MemTable_NormsEd.FieldByName(fnExpenseForLength).AsFloat := 0;
    MemTable_NormsEd.FieldByName(fnCountForPoint).AsFloat := 0;
    MemTable_NormsEd.FieldByName(fnStepOfPoint).AsFloat := 0;
    MemTable_NormsEd.Post;

    CalcNormTatalCostInMT(MemTable_NormsEd, FTraccaLength);

    //TotalCost := RoundCP(Cost * Kolvo);
    //MemTable_NormsEd.Edit;
    //MemTable_NormsEd.FieldByName('Total_Cost').AsFloat := TotalCost;
    //MemTable_NormsEd.FieldByName('kolvo').AsFloat := kolvo;
    //MemTable_NormsEd.Post;
  end;
  CalcWorkCost;
end;

procedure TF_AddComponent.GT_ResourcesPricePropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
var
  cost, price, AdditionalPrice, kolvo: Double;
begin
  Error := false;
  with TF_Main(GForm).DM do
  begin
    price := DisplayValue;
    AdditionalPrice := MemTable_ResourcesRelEd.FieldByName(fnAdditionalPrice).AsFloat;
    kolvo := MemTable_ResourcesRelEd.FieldByName('kolvo').AsFloat;
    cost := (price + AdditionalPrice) * kolvo;
    MemTable_ResourcesRelEd.Edit;
    MemTable_ResourcesRelEd.FieldByName('Cost').AsFloat := cost; //MemTable_ResourcesRelEd.FieldByName('Price').AsFloat * MemTable_ResourcesRelEd.FieldByName('kolvo').AsInteger;
    MemTable_ResourcesRelEd.FieldByName('price').AsFloat := price;
    MemTable_ResourcesRelEd.Post;
  end;
  CalcNormCost;
end;

procedure TF_AddComponent.GT_ResourcesAdditionalPricePropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
var
  cost, price, AdditionalPrice, kolvo: Double;
begin
  Error := false;
  with TF_Main(GForm).DM do
  begin
    price := MemTable_ResourcesRelEd.FieldByName(fnPrice).AsFloat;
    AdditionalPrice := DisplayValue;
    kolvo := MemTable_ResourcesRelEd.FieldByName('kolvo').AsInteger;
    cost := (price + AdditionalPrice) * kolvo;
    MemTable_ResourcesRelEd.Edit;
    MemTable_ResourcesRelEd.FieldByName('Cost').AsFloat := cost; //MemTable_ResourcesRelEd.FieldByName('Price').AsFloat * MemTable_ResourcesRelEd.FieldByName('kolvo').AsInteger;
    MemTable_ResourcesRelEd.FieldByName(fnAdditionalPrice).AsFloat := AdditionalPrice;
    MemTable_ResourcesRelEd.Post;
  end;
  CalcNormCost;
end;

procedure TF_AddComponent.GT_ResourcesKolvoPropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
var
  cost, price, AdditionalPrice, kolvo: Double;
begin
  Error := false;
  with TF_Main(GForm).DM do
  begin
    price := MemTable_ResourcesRelEd.FieldByName('Price').AsFloat;
    AdditionalPrice := MemTable_ResourcesRelEd.FieldByName(fnAdditionalPrice).AsFloat;
    kolvo := DisplayValue; //MemTable_ResourcesRelEd.FieldByName('kolvo').AsInteger;
    cost := (price + AdditionalPrice) * kolvo;
    MemTable_ResourcesRelEd.Edit;
    MemTable_ResourcesRelEd.FieldByName('Cost').AsFloat := cost; //MemTable_ResourcesRelEd.FieldByName('Price').AsFloat * MemTable_ResourcesRelEd.FieldByName('kolvo').AsInteger;
    MemTable_ResourcesRelEd.FieldByName('kolvo').AsFloat := kolvo;
    MemTable_ResourcesRelEd.Post;
  end;
  CalcNormCost;
end;

procedure TF_AddComponent.Act_AddNormExecute(Sender: TObject);
begin
  if pcMain.ActivePage = tsWorkingAndResources then
    if Grid_NORMS.Showing then
      SetFocusToControl(Grid_NORMS);
  //Grid_NORMS.SetFocus;
  //ProcessMessagesEx;

  if ReadOnly then
    Exit; ///// EXIT /////

  AddEditNorm(meMake);
  EnableEditDelNorm;
end;

procedure TF_AddComponent.Act_AddResourceToMTNormExecute(Sender: TObject);
begin
  SetFocusToControl(Grid_NORMS);

  if ReadOnly then
    Exit; ///// EXIT /////

  AddEditResource(meMake, tkNormEd, false);
  EnableEditDelNorm;
end;

procedure TF_AddComponent.Act_AddResourceComponToMTNormExecute(
  Sender: TObject);
begin
  SetFocusToControl(Grid_NORMS);

  if ReadOnly then
    Exit; ///// EXIT /////

  AddEditResource(meMake, tkNormEd, true);
  EnableEditDelNorm;
end;

procedure TF_AddComponent.Act_EditNormResourceExecute(Sender: TObject);
var
  EditName: string;
begin
  SetFocusToControl(Grid_NORMS);

  if ReadOnly then
    Exit; ///// EXIT /////

  case TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnIsResource).AsBoolean of
    true:
      AddEditResource(meEdit, tkNormEd, false);
    false:
      begin
        EditName := TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnName).AsString;
        if GUseVisibleInterfaces and
           (TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnIsFromInterface).AsInteger = biTrue) then
          MessageModal(cImpossibleReplaceNorm + ' "' + EditName + '" ' + cbMessage5, cReplacingNorm, MB_ICONINFORMATION or MB_OK)
        else
          AddEditNorm(meEdit);
      end;
  end;
end;

procedure TF_AddComponent.Act_DeleteNormResourceExecute(Sender: TObject);
var
  DelName: string;
  IDDel: Integer;
  CurrNPP: Integer;
  CanDel: Boolean;
  StrMessg: String;
  // Tolik
  FromInterFace, Deleted: Boolean;
  SCSCompon: TSCSComponent; // компонент, с которого удаляется норма
  i, j, k, l, NormID: Integer;
  ChildCompon: TSCSComponent;
  currInterFace: TSCSInterface;
  s, currNormGuid: string;

  DelDataSet: TpFIBDataSet;
  MemTable: TkbmMemTable;
  InterfIdList: TIntList;
  currNorm: TSCSNorm;
  sprInterf: TNBInterFace;
  currForm: TF_Main;
  currInterfaceID: Integer;
  Norm_ID: Integer;
  Id_Interface: Integer;
  NormInterfaceGuid: String;

begin
  SetFocusToControl(Grid_NORMS);
  currInterfaceID := -1;
  if ReadOnly then
    Exit; ///// EXIT /////

  try
    CanDel := false;
    currNormGuid := '';
    FromInterFace :=False;
    Norm_ID := -1;
    Id_Interface := -1;
    NormInterfaceGuid := '';

    Norm_ID := TF_Main(GForm).DM.MemTable_NormsEd.FieldByName('ID').Value;
    currNormGuid := TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnGuidNB).Value;
    // Tolik
    if not TF_Main(GForm).DM.MemTable_NormsEd.FieldByName('GuidInterface').IsNull then // 21/02/2018 --
      NormInterFaceGuid := TF_Main(GForm).DM.MemTable_NormsEd.FieldByName('GuidInterface').Value;
    //
    DelName := TF_Main(GForm).DM.MemTable_NormsEd.FieldByName('Name').AsString;
    case TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnIsResource).AsBoolean of
      true:
        begin
          StrMessg := '';
          if TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnGuidNBComponent).AsString = '' then
            StrMessg := cQuastDelResource
          else
            StrMessg := cQuastDelAccessoryCompon;
          if MessageModal(StrMessg + ' "' + DelName + '"?',
            ApplicationName, MB_ICONQUESTION or MB_YESNO) = IDYES then
            CanDel := true;
        end;
      false:
        begin
          // Tolik
          //*** Не дать юзеру удалять нормы пришедшие с интерфейсов
//           if MessageModal(cImpossibleDelNorm + ' "' + DelName + '" ' + cbMessage5, ApplicationName, MB_ICONINFORMATION or YESNO) = IDYES then
          if GUseVisibleInterfaces and (TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnIsFromInterface).AsInteger = biTrue) then
          begin
           if MessageModal(cAttentionDelInterfNorm + #13#10 + cQuastDelNorm + ' "' + DelName + '"?' , cDeletingNorm, MB_ICONQUESTION or MB_YESNO) = IDYES then
             CanDel := True;
          end
          else
          begin
            if MessageModal(cQuastDelNorm + ' "' + DelName + '"?', cDeletingNorm, MB_ICONQUESTION or MB_YESNO) = IDYES then
              CanDel := true;
          end;
        end;
    end;

    if CanDel then
    begin
      //Tolik
      if GUseVisibleInterfaces and (TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnIsFromInterface).AsInteger = biTrue) then
        FromInterFace := True;
      //
      IDDel := TF_Main(GForm).DM.MemTable_NormsEd.FieldByName('ID').AsInteger;

      if TF_Main(GForm).DM.MemTable_NormsEd.FieldByName('isNew').AsBoolean = false then
        case TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnIsResource).AsBoolean of
          true:
            GDeletedResourceID.Add(IDDel);
          false:
            begin
              DelResourcesFromCurrNorm;
              GDeletedNormID.Add(IDDel);
            end;
        end;
      CurrNPP := TF_Main(GForm).DM.MemTable_NormsEd.FieldByName('NPP').AsInteger;
      TF_Main(GForm).DM.MemTable_NormsEd.Delete;
      TF_Main(GForm).DM.SdvigNPPInMemTable(CurrNPP, TF_Main(GForm).DM.MemTable_NormsEd);
      CalcWorkCost;

      // Tolik
      // Если норма пришла с интерфейса, то удалить норму на интерфейсе
      // для этого нужно поискать такую же норму на интерфейсах компонента или чилдов
      // и удалить там, чтоб не цеплялась при следующем вызове пересчета норм/ресурсов

      // если норма пришла с интерфейса
      if FromInterFace then
      begin
        currForm := nil;
        currForm := TF_MAIN(GForm);
        if currForm <> nil then
        begin
  //        if TF_MAIN(GForm).GDBMode = bkProjectManager then
          begin
            //if F_ProjMan.GSCSBase.SCSComponent.ID <> 0 then
            if currForm.GSCSBase.SCSComponent.ID <> 0 then
            begin
              sprInterf := nil;
              sprInterf := currForm.GSCSBase.CurrProject.Spravochnik.GetInterfaceWithAssign(NormInterfaceGUID, F_ProjMan.GSCSBase.NBSpravochnik, false, false);
              if sprInterf <> nil then
              begin
                for k := 0 to sprInterF.InterfaceNorms.Count - 1 do
                begin
                  Deleted := False;
                  if TNBInterFaceNorm(sprInterf.InterfaceNorms[k]).GuidNBNorm = currNormGuid then
                  begin
                    TNBInterFaceNorm(sprInterf.InterfaceNorms[k]).Free;
                    sprInterf.InterfaceNorms[k] := nil;
                    Deleted := True;
                    //break;
                  end;
                end;
                sprInterF.InterfaceNorms.Pack;
              end;


              //SCSCompon := F_ProjMan.GSCSBase.CurrProject.GetComponentFromReferences(F_ProjMan.GSCSBase.SCSComponent.ID);
             (* SCSCompon := currForm.GSCSBase.CurrProject.GetComponentFromReferences(F_ProjMan.GSCSBase.SCSComponent.ID);
              if SCSCompon <> nil then
              begin
                Deleted := False;
                for i := 0 to SCSCompon.NormsResources.Norms.Count - 1 do
                begin
                  currNorm := SCSCompon.NormsResources.Norms[i];
                  if (currNorm.IsFromInterface = biTrue) then
                  begin
                    for j := 0 to SCSCompon.Interfaces.Count - 1 do
                    begin
                      sprInterf := nil;
                      currInterFace := TSCSInterface(SCSCompon.Interfaces[j]);

                      sprInterf := currForm.GSCSBase.CurrProject.Spravochnik.GetInterfaceWithAssign(currInterFace.GUIDInterface, F_ProjMan.GSCSBase.NBSpravochnik, false, false);

                      if sprInterf <> nil then
                      begin
                        for k := 0 to sprInterF.InterfaceNorms.Count - 1 do
                        begin
                         // if TNBInterFaceNorm(sprInterf.InterfaceNorms[k]).GuidNBNorm = currNormGuid then
                          if TNBInterFaceNorm(sprInterf.InterfaceNorms[k]).IDNBNorm = Norm_ID then
                          begin
                            TNBInterFaceNorm(sprInterf.InterfaceNorms[k]).Free;
                            sprInterf.InterfaceNorms[k] := nil;
                            Deleted := True;
                            //break;
                          end;
                        end;
                        sprInterF.InterfaceNorms.Pack;
                      end;
                    end;
                  end;
                end;
                //Tolik -- 21/06/2016 --
                // если не удалена норма, то поищем ее на чилдах компонента(если они есть)
                if not Deleted then
                begin
                  for i := 0 to SCSCompon.ChildReferences.Count - 1 do
                  begin
                    ChildCompon := TSCSComponent(SCSCompon.ChildReferences[i]);
                    if not ChildCompon.ServToDelete then
                    begin
                      {for j := 0 to ChildCompon.NormsResources.Norms.Count - 1 do
                      begin
                        currNorm := ChildCompon.NormsResources.Norms[j];
                        if (currNorm.IsFromInterface = biTrue) then
                        begin}
                          for k := 0 to ChildCompon.Interfaces.Count - 1 do
                          begin
                            sprInterf := nil;
                            currInterFace := TSCSInterface(ChildCompon.Interfaces[k]);
                            sprInterf := currForm.GSCSBase.CurrProject.Spravochnik.GetInterfaceWithAssign(currInterFace.GUIDInterface, F_ProjMan.GSCSBase.NBSpravochnik, false, false);
                            if sprInterf <> nil then
                            begin
                              for l := 0 to sprInterF.InterfaceNorms.Count - 1 do
                              begin
                                //if TNBInterFaceNorm(sprInterf.InterfaceNorms[l]).GuidNBNorm = currNormGuid then
                                if TNBInterFaceNorm(sprInterf.InterfaceNorms[k]).IDNbNorm = Norm_ID then
                                begin
                                  TNBInterFaceNorm(sprInterf.InterfaceNorms[l]).Free;
                                  sprInterf.InterfaceNorms[l] := nil;
                                  Deleted := True;
                                  //break;
                                end;
                              end;
                              sprInterF.InterfaceNorms.Pack;
                            end;
                          end;

                    end;
                  end;
                end;
                //
              end;
              *)
            end;
          end;
        end;
      end;
      EnableEditDelNorm;
    end;
  except
    on E: Exception do
      AddExceptionToLog('TF_AddComponent.Act_DeleteNormResourceExecute: ' + E.Message);
  end;
end;

procedure TF_AddComponent.Act_AddResourceExecute(Sender: TObject);
begin
  AddEditResource(meMake, tkResourceRelEd, false);
  EnableEditDelResource;
end;

procedure TF_AddComponent.Act_EditResourceExecute(Sender: TObject);
begin
  AddEditResource(meEdit, tkResourceRelEd, false);
end;

procedure TF_AddComponent.Act_DelResourceExecute(Sender: TObject);
var
  DelName: string;
  IDDel: Integer;
  CurrNPP: Integer;
begin
  try
    DelName := TF_Main(GForm).DM.MemTable_ResourcesRelEd.FieldByName('Name').AsString;
    if MessageModal(cQuastDelResource + ' "' + DelName + '"?',
      cDeletingResource, MB_ICONQUESTION or MB_YESNO) = IDYES then
    begin
      if TF_Main(GForm).DM.MemTable_ResourcesRelEd.FieldByName('isNew').AsBoolean = false then
      begin
        IDDel := TF_Main(GForm).DM.MemTable_ResourcesRelEd.FieldByName('ID').AsInteger;
        GDeletedResourceID.Add(IDDel);
      end;
      CurrNPP := TF_Main(GForm).DM.MemTable_ResourcesRelEd.FieldByName('NPP').AsInteger;
      TF_Main(GForm).DM.MemTable_ResourcesRelEd.Delete;
      TF_Main(GForm).DM.SdvigNPPInMemTable(CurrNPP, TF_Main(GForm).DM.MemTable_ResourcesRelEd);

      CalcNormCost;
      EnableEditDelResource;
    end;
  except
    on E: Exception do
      AddExceptionToLog('TF_Norms.Act_DelResourceExecute: ' + E.Message);
  end;
end;

procedure TF_AddComponent.GT_NORMSRTypeGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: string);
begin
  if AText <> '' then
    AText := GetResourceTypeName(StrToInt(AText));

  {if AText <> '' then
  begin
    if (StrToInt(AText) = rtMat) then
      AText := cAddComponent_Msg13_1
    else if (StrToInt(AText) = rtMachMech) then
      AText := cAddComponent_Msg13_2
    else if (StrToInt(AText) = rtPrice) then
      AText := cAddComponent_Msg13_3;
  end;}
end;

procedure TF_AddComponent.cbApplyForCurrentDirPropertiesChange(
  Sender: TObject);
//var
  //ApplyCheckBoxBorderColor: TColor;
  //ApplyCheckBoxBorderStyle: TcxEditBorderStyle;
begin
  cbIncludingSubFolders.Enabled := cbApplyForCurrentDir.Checked;
  lbSelectFieldsFromApplyInNB.Enabled := cbApplyForCurrentDir.Checked;

  OncbApplyForChange(Sender);
  if (FApplyComponElementsChecked[liProperty] = biTrue) then
    cbApplyForFocusedProp.Enabled := cbApplyForCurrentDir.Checked
  else
    cbApplyForFocusedProp.Enabled := False;

  cbAutoAddInter.Enabled := cbApplyForCurrentDir.Checked;
  //ApplyCheckBoxBorderColor := FApplyCheckBoxesBorderColor;
  //ApplyCheckBoxBorderStyle := FApplyCheckBoxesBorderStyle;
  //if Not cbApplyForCurrentDir.Checked then
  //begin
  //  ApplyCheckBoxBorderColor := clWindowFrame;
  //  ApplyCheckBoxBorderStyle := ebsUltraFlat;
  //end;

  //cbApplyForCurrentDir.Style.BorderColor := ApplyCheckBoxBorderColor;
  //cbApplyForCurrentDir.Style.BorderStyle := ApplyCheckBoxBorderStyle;
  //VisibleApplyCheckBoxes(cbApplyForCurrentDir.Checked, false);
end;

procedure TF_AddComponent.cbSuppliesKindPropertiesChange(Sender: TObject);
var
  IDSuppliesKind: Integer;
  GUIDSuppliesKind: string;
  //SavedOnChange: TNotifyEvent;
begin
  IDSuppliesKind := GetIDFromComboBox(cbSuppliesKind);
  GUIDSuppliesKind := GetGUIDFromComboBox(cbSuppliesKind);

  FSuppliesKind := TF_Main(GForm).DM.GetSuppliesKindByID(IDSuppliesKind, GUIDSuppliesKind);
  DefineSuppliesKindWorkValuesToFields(FSuppliesKind, TF_Main(GForm).FUOM);


  SetSupplyKindControls;

  if (IDSuppliesKind > 0) or (GUIDSuppliesKind <> '') then
  begin
    DefineSupplyPriceByComponPrice(CurrencyEdit_Price1.Value);

    if FSuppliesKind.Izm <> '' then
      if GetNameUOMForCompon('', @FCurrComponentType, TF_Main(GForm).FUOM) = '' then
        Edit_Izm.Text := FSuppliesKind.Izm;

    //*** Если был неогпределен вид поставки и цена поставки
    {if FSuppliesKind.ID = 0 then
      if (cePriceSupply.Value = 0) and (CurrencyEdit_Price1.Value > 0) then
      begin
        SavedOnChange := cePriceSupply.Properties.OnChange;
        cePriceSupply.Properties.OnChange := nil;
        try
          cePriceSupply.Value := RoundCP(CurrencyEdit_Price1.Value * SuppliesKind.UnitKolvo);
        finally
          cePriceSupply.Properties.OnChange := SavedOnChange;
        end;
      end;}

    //DefineParamsBySupply(cePriceSupply.Value, true);
  end;

  GWasChanging := true;
end;

procedure TF_AddComponent.btSuppliesKindClick(Sender: TObject);
var
  IDSuppliesKind: Integer;
  GUIDSuppliesKind: string;
  //Iindex: Integer;
begin
  IDSuppliesKind := GetIDFromComboBox(cbSuppliesKind);
  GUIDSuppliesKind := GetGUIDFromComboBox(cbSuppliesKind);

  if TF_Main(GForm).GDBMode = bkNormBase then
  begin
    F_NormBase.F_CaseForm.GIDNotDel := IDSuppliesKind;
    F_NormBase.F_CaseForm.GIDToLocate := IDSuppliesKind;

    if (F_NormBase.F_CaseForm.Execute(VKSuppliesKind, fmEdit)) then
    begin
      IDSuppliesKind := F_NormBase.DM.DataSet_SuppliesKinds.FN(fnID).AsInteger;

      cbSuppliesKind.Properties.BeginUpdate;
      try
        //cbSuppliesKind.Properties.OnChange := nil;
        //FSpravochnik.LoadSuppliesKindsToStrings(cbSuppliesKind.Properties.Items, true);
        //cbSuppliesKind.Properties.OnChange := cbSuppliesKindPropertiesChange;
        LoadSuppliesKindsToForm;
      finally
        cbSuppliesKind.Properties.EndUpdate;
      end;
      SelectItemByIDinCombo(cbSuppliesKind, IDSuppliesKind);

      GWasChanging := true;
    end;
  end
  else
  if TF_Main(GForm).GDBMode = bkprojectManager then
  begin
    if ShowCurrProjectProperties(vkSuppliesKind, GUIDSuppliesKind) then
      if FProjSpravochnik.LastSuppliesKind <> nil then
        GUIDSuppliesKind := FProjSpravochnik.LastSuppliesKind.Data.GUID;

    //cbSuppliesKind.Properties.OnChange := nil;
    //FProjSpravochnik.LoadSuppliesKindsToStrings(cbSuppliesKind.Properties.Items, true);
    //cbSuppliesKind.Properties.OnChange := cbSuppliesKindPropertiesChange;
    LoadSuppliesKindsToForm;
    SelectItemByGUIDinCombo(cbSuppliesKind, GUIDSuppliesKind);
  end;
  //FillComboBox(cbSuppliesKind, F_NormBase, true, tnSuppliesKinds, fnID, fnName, strNoDefined, IDSuppliesKind);
end;

procedure TF_AddComponent.Act_AddCompDataFromOtherComponExecute(
  Sender: TObject);
var
  NBComponent: TSCSComponent;
begin
  if ReadOnly then
    Exit; ///// EXIT /////

  NBComponent := TF_Main(GForm).CreateFConnectComplWith.GetComponentFromNB(GIDComponent, '');
  if NBComponent <> nil then
  begin
    try
      with TF_Main(GForm).DM do
        case Grid.ActiveLevel.Index of
          liInterface, liPort:
            begin
              NBComponent.LoadInterfaces;
              NBComponent.SetPortInterfRelInterfaces;
              NBComponent.SetInterfacesParallel;

              SendInterfacesPortsToMemTable(NBComponent, true, true);
            end;
          liProperty: ;
        end;
    finally
      NBComponent.Free;
    end;
    EnableButtons;
  end;
end;

procedure TF_AddComponent.CurrencyEdit_Price1Exit(Sender: TObject);
begin
  if TcxCurrencyEdit(Sender).Text = '' then
    TcxCurrencyEdit(Sender).Value := 0;
end;

procedure TF_AddComponent.cbApplyComponDataClick(Sender: TObject);
begin
  FApplyComponElementsChecked[Grid.ActiveLevel.Index] := BoolToInt(TcxCheckBox(Sender).Checked);
  if Grid.ActiveLevel.Index = liPort then
    FApplyComponElementsChecked[liInterface] := FApplyComponElementsChecked[liPort];
  if Grid.ActiveLevel.Index = liInterface then
    FApplyComponElementsChecked[liPort] := FApplyComponElementsChecked[liInterface];

  if (FApplyComponElementsChecked[liProperty] = biTrue) then
    cbApplyForFocusedProp.Enabled := cbApplyForCurrentDir.Checked
  else
    cbApplyForFocusedProp.Enabled := False;
  cbAutoAddInter.Enabled := cbApplyForCurrentDir.Checked;
end;

procedure TF_AddComponent.Act_DublicatePortInterfaceExecute(
  Sender: TObject);
var
  meInterfacePortRel: TmeInterfaceRel;
  dsrcPortInterface: TDataSource;
  IsPort: Integer;
  ComponentType: TComponentType;
begin
  if ReadOnly then
    Exit; ///// EXIT /////

  dsrcPortInterface := nil;
  IsPort := biFalse;
  case Grid.ActiveLevel.Index of
    liInterface:
      begin
        dsrcPortInterface := TF_Main(GForm).DM.DataSource_MT_INTERFACERelEd;
        IsPort := biFalse;
      end;
    liPort:
      begin
        dsrcPortInterface := TF_Main(GForm).DM.DataSource_MT_PortEd;
        IsPort := biTrue;
      end;
  end;

  if dsrcPortInterface <> nil then
  begin
    meInterfacePortRel := TF_Main(GForm).DM.GetInterfaceRel(dsrcPortInterface, nil);
    if meInterfacePortRel.IsNative = false then
      MessageModal(cImpossibleDupNoNativeInterface, ApplicationName, MB_ICONINFORMATION or MB_OK)
    else
    begin
      ComponentType := GetComponentType;

      meInterfacePortRel.Count := 1;
      meInterfacePortRel.IsPort := IsPort;
      meInterfacePortRel.IsBusy := biFalse;
      meInterfacePortRel.DataSource := nil;
      meInterfacePortRel.IsLineCompon := ComponentType.IsLine;
      meInterfacePortRel.ServiceIsPair := (meInterfacePortRel.IsLineCompon = biTrue) and (meInterfacePortRel.ID_Adverse > 0);
      if meInterfacePortRel.ServiceIsPair then
        Inc(meInterfacePortRel.Count);
      AddInterfaceToMT(meInterfacePortRel);
    end;
  end;
end;

procedure TF_AddComponent.GT_InterfaceRNumberGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: string);
begin
  AText := IntToStr(AREcord.Index + 1);
end;

procedure TF_AddComponent.GT_PortRNumberGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: string);
begin
  AText := IntToStr(AREcord.Index + 1);
end;

procedure TF_AddComponent.GT_NORMSNPPGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: string);
begin
  AText := IntToStr(ARecord.Index + 1);
end;

procedure TF_AddComponent.gbOkCancelResize(Sender: TObject);
begin
  SetMiddleControlChilds(TControl(Sender), Self);
end;

procedure TF_AddComponent.Act_TurnFromMemTableToSpravochnikExecute(
  Sender: TObject);
var
  InterfPortMemTable: TkbmMemTable;
begin
  if ReadOnly then
    Exit; ///// EXIT /////

  InterfPortMemTable := GetInterfPortMemTable;
  if InterfPortMemTable <> nil then
    ShowSpravochnikForInterface(GForm, InterfPortMemTable);
end;

procedure TF_AddComponent.Act_AddCrossConnectionExecute(Sender: TObject);
begin
  AddEditCrossConnection(meMake);
  EnableButtons;
end;

procedure TF_AddComponent.Act_EditCrossConnectionExecute(Sender: TObject);
begin
  AddEditCrossConnection(meEdit);
end;

procedure TF_AddComponent.Act_DelCrossConnectionExecute(Sender: TObject);
var
  DelID: Integer;
begin
  if MessageModal(cQuastDelCurrCrossConnection,
    Application.Title, MB_ICONQUESTION or MB_YESNO) = IDYES then
  begin
    DelID := TF_Main(GForm).DM.mtCrossConnectionEd.FieldByName(fnID).AsInteger;
    if TF_Main(GForm).DM.mtCrossConnectionEd.FieldByName(fnIsNew).AsBoolean = false then
      GDeletedCrossConnections.Add(DelID);
    TF_Main(GForm).DM.mtCrossConnectionEd.Delete;
  end;
  EnableButtons;
end;

procedure TF_AddComponent.seIndexPropertiesChange(Sender: TObject);
begin
  GChangedIndex := true;
  if TF_Main(GForm).GDBMode = bkProjectManager then
    if rbMarkByTemplate.Checked then
    begin
      Edit_NameMark.Text := GetComponentNameMarkByTemplate;
    end;
end;

procedure TF_AddComponent.Act_EnterExecute(Sender: TObject);
begin
  BitBtn_OK.Click;
end;

procedure TF_AddComponent.cbDismountClick(Sender: TObject);
var
  //BookmarkStr: string;
  BookmarkStr: TBookMark;
  MemTableNorms: TkbmMemTable;
begin
  try
    cbUseDismounted.Enabled := cbDismount.Checked;

    {$IF Not Defined(NORMSCS_PE) and Not Defined(SCS_SPA)}
      if cbDismount.Checked then
      begin
        MemTableNorms := TF_Main(GForm).DM.MemTable_NormsEd;
        if MemTableNorms.Active then
          if MessageModal(cAddComponent_Msg14, ApplicationName, MB_ICONQUESTION or MB_YESNO) = IDYES then
          begin
            //BookmarkStr := MemTableNorms.Bookmark;
            BookmarkStr := MemTableNorms.GetBookmark;
            MemTableNorms.DisableControls;
            try
              MemTableNorms.First;
              while not MemTableNorms.Eof do
              begin
                if not MemTableNorms.FieldByName(fnIsResource).AsBoolean and
                  (MemTableNorms.FieldByName(fnIsOn).AsInteger = biTrue) then
                begin
                  MemTableNorms.Edit;
                  MemTableNorms.FieldByName(fnIsOn).AsInteger := biFalse;
                  MemTableNorms.FieldByName(fnIsModified).AsBoolean := true;
                  MemTableNorms.Post;
                end;
                MemTableNorms.Next;
              end;
            finally
              if BookmarkStr <> nil then
              begin
                MemTableNorms.GotoBookMark(BookmarkStr);
                MemTableNorms.FreeBookMark(BookmarkStr);
              end;

              MemTableNorms.EnableControls;
            end;
            Act_AddNorm.Execute;

            cbUseDismounted.Checked := true;
          end
          else
            cbUseDismounted.Checked := false;
      end;
    {$IFEND}
  except
    on E: Exception do
      AddExceptionToLogEx('TF_AddComponent.cbDismountClick', E.Message);
  end;
end;

procedure TF_AddComponent.GT_CableCanalConnectorsDblClick(Sender: TObject);
begin
  Act_EditCableCanalConnector.Execute;
end;

procedure TF_AddComponent.ComboBox_ComponentTypeExit(Sender: TObject);
begin
  FChangedComponTypeInCombo := false;
  if GFormMode <> fmView then
    ApplyChangedComponentType;
end;

procedure TF_AddComponent.GT_NORMSEditChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
begin
  //
end;

procedure TF_AddComponent.GT_NORMSEditValueChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
begin
  //
end;

procedure TF_AddComponent.btImportComponByArtProducerClick(
  Sender: TObject);
var
  IDComponent: Integer;
  NewComponentType: TComponentType;
  SavedOnChange: TNotifyEvent;
begin
  IDComponent := 0;
  if Edit_ArticulProducer.Text <> '' then
  begin
    IDComponent := TF_Main(GForm).DM.GetComponIDByArtProducer(Edit_ArticulProducer.Text, GIDComponent);
    if IDComponent <> 0 then
    begin
      FCurrComponentType := TF_Main(GForm).DM.GetComponentTypeByIDCompon(IDComponent);
      if FCurrComponentType.ID <> 0 then
      begin
        //*** подгрузить тип компоненты
        SavedOnChange := ComboBox_ComponentType.Properties.OnChange;
        ComboBox_ComponentType.Properties.OnChange := nil;
        try
          SelectItemByIDinCombo(ComboBox_ComponentType, FCurrComponentType.ID);
        finally
          ComboBox_ComponentType.Properties.OnChange := SavedOnChange;
        end;

        //*** Подгрузить сам компонент
        ImportComponentByID(IDComponent);

        EnableButtons;
        SetControls(nil);
      end;
    end
    else
      MessageModal(cAddComponent_Msg15, ApplicationName, MB_OK or MB_ICONINFORMATION);
  end;
end;

procedure TF_AddComponent.lbSelectFieldsFromApplyInPMClick(
  Sender: TObject);
begin
  ShowPopupMenuForControl(lbSelectFieldsFromApplyInPM, pmSelectApplyFields);
end;

procedure TF_AddComponent.lbSelectFieldsFromApplyInNBClick(
  Sender: TObject);
begin
  ShowPopupMenuForControl(lbSelectFieldsFromApplyInNB, pmSelectApplyFields);
end;


procedure TF_AddComponent.Act_SelectAllApplyFieldsExecute(Sender: TObject);
begin
  SetValueToAllApplyCheckBoxes(true);
end;

procedure TF_AddComponent.Act_DeSelectAllApplyFieldsExecute(
  Sender: TObject);
begin
  SetValueToAllApplyCheckBoxes(false);
end;

procedure TF_AddComponent.Act_SelectCurrPageAllApplyFieldsExecute(
  Sender: TObject);
begin
  SetValueToCurrPageApplyCheckBoxes(true);
end;

procedure TF_AddComponent.Act_DeSelectCurrPagetAllApplyFieldsExecute(
  Sender: TObject);
begin
  SetValueToCurrPageApplyCheckBoxes(false);
end;

procedure TF_AddComponent.GT_PropertyIzmGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  SetDisplayTextToGridTablePropIzm(AText, ARecord, 7, TF_Main(GForm).FUOM);
end;

procedure TF_AddComponent.GT_NORMSExpenseForLengthGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  try
    AText := GetDisplayTextToNORMExpenseForLength(AText, TF_Main(GForm).FUOM);
  except
  end;
end;

procedure TF_AddComponent.GT_NORMSExpenseForLengthPropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
var
  ValueFloat: Double;
  //added by Tolik
  ExpenseForIzm : string;
  //
begin
  try
    ExpenseForIzm := (TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnIzm).AsString);
    // Преобразуем расход из TF_Main(GForm).FUOM на метр
    if DisplayValue = '' then
    begin
      DisplayValue := FloatToStr(TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnExpenseForLength).AsFloat);
      Exit; ///// EXIT /////
    end
   // added by Tolik
    else
      if TF_Main(GForm).DM.GetExpenceFromIzm(ExpenseForIzm) <> 1 then
        DisplayValue := FloatToStr(StrToFloat_My(DisplayValue)*TF_Main(GForm).DM.GetExpenceFromIzm(ExpenseForIzm));
   //
    ValueFloat := StrToFloat_My(DisplayValue);
    ValueFloat := FloatInUOM(ValueFloat, umMetr, TF_Main(GForm).FUOM);

    with TF_Main(GForm).DM do
    begin
      MemTable_NormsEd.Edit;
      MemTable_NormsEd.FieldByName(fnExpenseForLength).AsFloat := RoundCP(ValueFloat);

      if MemTable_NormsEd.FieldByName(fnIsResource).AsBoolean then
        MemTable_NormsEd.FieldByName(fnTotalCost).AsFloat := 0;
      MemTable_NormsEd.FieldByName(fnKolvo).AsFloat := 0;
      MemTable_NormsEd.FieldByName(fnCountForPoint).AsFloat := 0;
      MemTable_NormsEd.FieldByName(fnStepOfPoint).AsFloat := 0;
      MemTable_NormsEd.Post;

      CalcNormTatalCostInMT(MemTable_NormsEd, FTraccaLength);
    end;
    CalcWorkCost;
  except
  end;
end;

procedure TF_AddComponent.GT_NORMSCountForPointPropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
var
  ValueFloat: Double;
begin
  try
    if DisplayValue = '' then
    begin
      DisplayValue := FloatToStr(TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnCountForPoint).AsFloat);
      Exit; ///// EXIT /////
    end
     else
      if TF_Main(GForm).DM.GetExpenceFromIzm(TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnIzm).AsString) <> 1 then
        DisplayValue := DisplayValue*TF_Main(GForm).DM.GetExpenceFromIzm(TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnIzm).AsString);

    ValueFloat := StrToFloat_My(DisplayValue);

    with TF_Main(GForm).DM do
    begin
      InputFloatToRelatedZeroFieldInMT(MemTable_NormsEd, ValueFloat, fnCountForPoint, fnStepOfPoint,
        fnKolvo+';'+fnTotalCost+';'+fnExpenseForLength, cAddComponent_Msg20_1, true, TF_Main(GForm).FUOM);

      CalcNormTatalCostInMT(MemTable_NormsEd, FTraccaLength);
      //MemTable_NormsEd.Edit;
      //MemTable_NormsEd.FieldByName(fnCountForPoint).AsFloat := RoundCP(ValueFloat);
      //MemTable_NormsEd.Post;
    end;
    CalcWorkCost;
  except
  end;
end;

procedure TF_AddComponent.GT_NORMSStepOfPointGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  AText := GetDisplayTextInFLoatUOM(AText, TF_Main(GForm).FUOM);
end;

procedure TF_AddComponent.GT_NORMSStepOfPointPropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
var
  ValueFloat: Double;
begin
  try
    if DisplayValue = '' then
    begin
      DisplayValue := FloatToStr(TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnStepOfPoint).AsFloat);
      Exit; ///// EXIT /////
    end;
    ValueFloat := StrToFloat_My(DisplayValue);
    ValueFloat := FloatInUOM(ValueFloat, TF_Main(GForm).FUOM, umMetr);

    with TF_Main(GForm).DM do
    begin
      InputFloatToRelatedZeroFieldInMT(MemTable_NormsEd, ValueFloat, fnStepOfPoint, fnCountForPoint,
        fnKolvo+';'+fnTotalCost+';'+fnExpenseForLength, cAddComponent_Msg20_2, false, TF_Main(GForm).FUOM);
      CalcNormTatalCostInMT(MemTable_NormsEd, FTraccaLength);
      //MemTable_NormsEd.Edit;
      //MemTable_NormsEd.FieldByName(fnStepOfPoint).AsFloat := RoundCP(ValueFloat);
      //MemTable_NormsEd.Post;
    end;
    CalcWorkCost;
  except
  end;
end;


procedure TF_AddComponent.GT_NORMSInitEdit(Sender: TcxCustomGridTableView;
  AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit);
begin
  if AItem = GT_NORMSExpenseForLength then
    AEdit.EditValue := GetDisplayTextToNORMExpenseForLength(AEdit.EditValue, TF_Main(GForm).FUOM)
  else
  if AItem = GT_NORMSStepOfPoint then
    AEdit.EditValue := GetDisplayTextInFLoatUOM(AEdit.EditValue, TF_Main(GForm).FUOM);
end;

procedure TF_AddComponent.GT_InterfaceCoordZGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  AText := GetDisplayTextInFLoatUOM(AText, TF_Main(GForm).FUOM);
end;

procedure TF_AddComponent.pcMainChanging(Sender: TObject;
  NewIndex: Integer; var AllowChange: Boolean);
begin
  if pcMain.ActivePage = tsWorkingAndResources then
    if GT_Norms.DataController.IsEditing then
      SetFocusToControl(Grid_NORMS);
end;

procedure TF_AddComponent.Act_DelAllExecute(Sender: TObject);
begin
  if ReadOnly then
    Exit; ///// EXIT /////

  case Grid.ActiveLevel.Index of
    liInterface:
      DelAllInterfacesPorts(false);
    liPort:
      DelAllInterfacesPorts(true);
    liProperty:
      DelAllProperties;
    liComplects:
      ;
    liCableCanalConnectors:
      DelAllCableCanalConnectors;
    liCrossConnections:
      DelAllCrossConnections;
  end;
  EnableButtons;
end;


procedure TF_AddComponent.GT_NORMSCustomDrawCell(
  Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
  AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
begin
  OnNormsResourcesCustomDrawCell(ACanvas, AViewInfo, GT_NORMSIsResource.Index,
    GT_NORMSGUIDNBCompon.Index, GT_NORMSTotalKolvo.Index, true);
end;

procedure TF_AddComponent.GT_NORMSTotalKolvoGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  //AText := GetDisplayTextInFLoatUOM(AText, TF_Main(GForm).FUOM);
end;

procedure TF_AddComponent.ComboBox_ProducerPropertiesChange(
  Sender: TObject);
begin
  GWasChanging := true;
end;

procedure TF_AddComponent.cePriceSupplyPropertiesChange(Sender: TObject);
begin
  GWasChanging := true;
end;

procedure TF_AddComponent.Edit_NoticePropertiesChange(Sender: TObject);
begin
  GWasChanging := true;
end;

procedure TF_AddComponent.Timer_ChoiceCompTypeTimer(Sender: TObject);
var
  GUIDCompType: String;
begin
  TTimer(Sender).Enabled := false;

  GUIDCompType := ExecuteChoiceComponType(GForm);
  if GUIDCompType <> '' then
  begin
    if SelectItemByGUIDinCombo(ComboBox_ComponentType, GUIDCompType) then
      ComboBox_ComponentTypeExit(ComboBox_ComponentType);
  end
  else
  begin
    ComboBox_ComponentType.SetFocus;
    ComboBox_ComponentType.DroppedDown := true;
  end;
end;

function TF_AddComponent.Execute(AFormMode: TFormMode; AIsTemplate: Boolean): Boolean;
begin
  Result := false;
  try
    GFormMode := AFormMode;
    FIsTemplate := AIsTemplate;

    if ShowModal = mrOK then
      Result := true;
  except
    on E: Exception do AddExceptionToLogExt(ClassName, MethodName(@TF_AddComponent.Execute), E.Message);
  end;
end;

procedure TF_AddComponent.btChangeSpecificationClick(Sender: TObject);
var
  IDObject: Integer;
begin
  IDObject := GetIDFromComboBox(cbSpecification);
  if TF_Main(GForm).GDBMode = bkNormBase then
  begin
    F_NormBase.F_CaseForm.GIDNotDel := IDObject;
    F_NormBase.F_CaseForm.GIDToLocate := IDObject;

    if (F_NormBase.F_CaseForm.Execute(vkCompSpecifications, fmEdit)) then
    begin
      IDObject := F_NormBase.DM.dsetCompSpecifications.FN(fnID).AsInteger;
      FillComboBox(cbSpecification, F_NormBase, true, tnFiles, fnID, fnFileName, '', IDObject);
      GWasChanging := true;
    end
    else
      FillComboBox(cbSpecification, F_NormBase, true, tnFiles, fnID, fnFileName, '', IDObject);
  end;
end;

procedure TF_AddComponent.OnChangeComponPropertyVal(AProperty: PProperty; AOldProperty: PProperty=nil);
begin
  if AProperty.SysName = pnHeightInUnits then
  begin
    SetPropertyValueBySysNameAsFloat(pnHeight, StrToFloatU(AProperty^.Value) * cUnitHeight);
  end;
end;

procedure TF_AddComponent.OnSetComponPropertyVal(AMakeEdit: TMakeEdit; AProperty: PProperty; AOldProperty: PProperty=nil);
begin
  OnChangeComponPropertyVal(AProperty, AOldProperty);
end;

procedure TF_AddComponent.OnControlChange(Sender: TObject);
begin
  if Not FIsLoadingForm then
    GWasChanging := true;
end;

procedure TF_AddComponent.GT_NORMSLaborTimeGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  AText := GetDisplayTextToNORMLaborTime(AText);
end;

procedure TF_AddComponent.Act_ShowInNormBaseExecute(Sender: TObject);
var
  InterfPortMemTable: TkbmMemTable;
  Spravochnick: TSpravochnik;
  Node: TTreeNode;
  SCSComponent : TSCSComponent;
  currInterFace: TSCSInterface;
  sprInterf: TNBInterface;
  currNormGuid: string;
  i,j,k : Integer;
  currNorm: TSCSNorm;
begin
  currNormGuid := TF_Main(GForm).DM.MemTable_NormsEd.FieldByName(fnGuidNB).Value;
  SCSComponent := nil;
  SCScomponent := F_ProjMan.GSCSBase.SCSComponent;
  if SCScomponent <> nil then
  begin
    Node := F_NormBase.FindComponentByGUIDWithBlink(SCSComponent.GuidNB);
    if Node <> nil then
    begin
      Node.Selected := True;
      if F_NormBase.GSCSBase.SCSComponent <> nil then
      begin
        F_NormBase.OnClickCompon(F_NormBase.GSCSBase.SCScomponent);
        F_NormBase.GSCSBase.SCSComponent.LoadInterfaces;
        SCScomponent := F_NormBase.GSCSBase.SCSComponent;
        InterfPortMemTable := TF_MAIN(F_NormBase).DM.MemTable_InterfaceRelEd;

        //InterfPortMemTable := TF_Main(F_NormBase).DM.MemTable_InterfaceRel;
        if InterfPortMemTable <> nil then
        begin
          if not InterfPortMemTable.Active then
            InterfPortMemTable.Open;
          F_NormBase.GT_Interface.Focused := True;

        end;

        SCSComponent := F_ProjMan.GSCSBase.CurrProject.GetComponentFromReferences(F_ProjMan.GSCSBase.SCSComponent.ID);
        if SCSComponent <> nil then
        begin
          
          for i := 0 to SCSComponent.NormsResources.Norms.Count - 1 do
          begin
            currNorm := SCSComponent.NormsResources.Norms[i];
            if (currNorm.IsFromInterface = biTrue) then
            begin
              for j := 0 to SCSComponent.Interfaces.Count - 1 do
              begin
                currInterFace := TSCSInterface(SCSComponent.Interfaces[j]);
                if (currInterFace.IsBusy = biTrue) or (currInterFace.BusyPositions.Count > 0) then
                begin
                  sprInterf := F_ProjMan.GSCSBase.CurrProject.Spravochnik.GetInterfaceWithAssign(currInterFace.GUIDInterface, F_ProjMan.GSCSBase.NBSpravochnik, false, false);
                  if sprInterf <> nil then
                  begin
                    for k := 0 to sprInterF.InterfaceNorms.Count - 1 do
                    begin
                      if TNBInterFaceNorm(sprInterf.InterfaceNorms[k]).GuidNBNorm = currNormGuid then
                      begin
                        break;
                      end;
                    end;
                  end;
                end;
              end;
            end;
          end;
        end;



{        TF_Main(F_NormBase).F_CaseForm.GUseMemTable := TF_MAIN(F_NormBase).DM.MemTable_InterfaceRel;//AMemTable;
        TF_Main(F_NormBase).F_CaseForm.GIDToLocate := currInterFace.ID_Interface;
        TF_Main(F_NormBase).DM.SelectInterfaces(TF_Main(F_NormBase).Tree_Catalog.Selected);
        TF_Main(F_NormBase).F_CaseForm.Execute(vkInterface, fmView);   }

        TF_Main(F_NormBase).F_CaseForm.GUseMemTable := TF_MAIN(F_NormBase).DM.MemTable_InterfaceRel;//AMemTable;
        TF_Main(F_NormBase).F_CaseForm.GIDToLocate := sprInterf.ID;
        TF_Main(F_NormBase).DM.SelectInterfaces(TF_Main(F_NormBase).Tree_Catalog.Selected);
        TF_Main(F_NormBase).F_CaseForm.Execute(vkInterface, fmView);



      // ShowSpravochnikForInterface(TF_Main(F_NormBase), InterfPortMemTable);
          //TF_MAIN(F_NormBase).DM.MemTable_InterfaceRel.Refresh;
     { ShowSpravochnikForInterface(TF_Main(F_NormBase), InterfPortMemTable);
      TF_Main(F_NormBase).DM.SelectInterfaces(TF_Main(F_NormBase).Tree_Catalog.Selected);}
     //   end;
          //F_NormBase.F_CaseForm.Execute(vkInterface, fmView);
          {      F_NormBase.F_CaseForm.Execute(vkInterface, fmView);
          TF_Main(F_NormBase).DM.SelectInterfaces(TF_Main(F_NormBase).Tree_Catalog.Selected);}
      end;
    end;
  end;

 {  IDInterface: Integer;
  GUIDInterface: String;


  OldName: String;
  CurrSprInterface: TNBInterface;

  RecNo: Integer;
  i: Integer;

  DBMode: TDBKind;
begin
  Spravochnick := nil;

  IDInterface := -1;
  GUIDInterface := '';

  IDInterface := AMemTable.FieldByName(fnIDInterface).AsInteger;
  GUIDInterface := AMemTable.FieldByName(fnGuidInterface).AsString;
  OldName := AMemTable.FieldByName(fnName).AsString;

  //*** Показать справочник

  Spravochnick := TF_Main(F_NormBase).GSCSBase.NBSpravochnik;
  TF_Main(AForm).F_CaseForm.GUseMemTable := AMemTable;
  TF_Main(AForm).F_CaseForm.GIDToLocate := IDInterface;
  TF_Main(AForm).F_CaseForm.Execute(vkInterface, fmView);


  //*** Применить новое изменения справочника на AMemTable
  if Spravochnick <> nil then
  begin
    CurrSprInterface := nil;
    if GUIDInterface <> '' then
      CurrSprInterface := Spravochnick.GetInterfaceWithAssign(GUIDInterface, F_NormBase.GSCSBase.NBSpravochnik, false, false)
    else
      CurrSprInterface := Spravochnick.GetInterfaceByID(IDInterface);
    if CurrSprInterface <> nil then
      if CurrSprInterface.Name <> OldName then
      begin
        RecNo := AMemTable.RecNo;
        AMemTable.DisableControls;
        try
          for i := 0 to AMemTable.RecordCount - 1 do
          begin
            AMemTable.RecNo := i+1;
            if ((GUIDInterface <> '') and (AMemTable.FieldByName(fnGuidInterface).AsString = GUIDInterface)) or
               (AMemTable.FieldByName(fnIDInterface).AsInteger = IDInterface) then
            begin
              AMemTable.Edit;
              AMemTable.FieldByName(fnName).AsString := CurrSprInterface.Name;
              AMemTable.Post;
            end;
          end;
        finally
          AMemTable.RecNo := RecNo;
          AMemTable.EnableControls;
        end;
      end;
  end;  }
end;

end.

//IDCatalog := 0;
//  if GFormMode = fmMake then
//    IDCatalog := TF_Main(GForm).GSCSBase.SCSCatalog.ID
//  else
//    IDCatalog := TF_Main(GForm).DM.GetComponCatalogOwnerID(GIDComponent);
//  FNBCurrency := TF_Main(GForm).FNormBas

