unit U_Kalc;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, RzRadChk, RzButton, StdCtrls, Mask, RzEdit, RzSpnEdt, ExtCtrls,
  RzPanel, RzTabs, exgrid, RapTree, FlytreePro, ActnList, Menus, RzRadGrp,
  DB, kbmMemTable, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
  cxDataStorage, cxEdit, cxDBData, cxGridLevel, cxClasses, cxControls,
  cxGridCustomView, cxGridCustomTableView, cxGridTableView,
  cxGridDBTableView, cxGrid, cxSpinEdit, cxTextEdit, cxProgressBar,
  cxDBLookupComboBox, Buttons,
  U_Kalc_DM, U_BaseCommon, cxContainer, cxMaskEdit, cxDropDownEdit, cxLookupEdit,
  cxDBLookupEdit, cxDBExtLookupComboBox, RzCmboBx, cxCheckComboBox,
  cxCheckBox, cxCurrencyEdit, cxColorComboBox, cxMemo, xmldom, Provider,
 // QGrids,
  U_BaseConstants, U_SCSComponent,
  XMLIntf, {XMLDom, } XMLDoc,//MSXML2_TLB,
   ToolWin, ComCtrls, ImgList, RzGroupBar, siComp, siLngLnk,
  cxGridBandedTableView, cxGridDBBandedTableView, cxLookAndFeels,
  U_Common_Classes, cxLookAndFeelPainters, cxNavigator;
//const // for captions
//    strCalcCapt1 = 'Ширина этажа, ';
//    strCalcCapt2 = 'Длина этажа, ';
//    strCalcCapt3 = 'Высота этажа, ';
//    strCalcCapt4 = 'Общая площадь, ';
//    strCalcCapt5 = 'Рабочая площадь , ';
//    strCalcCapt6 = 'Средняя S комнаты, ';
//    strCalcCapt7 = 'Ср. ширина комнаты, ';
//    strCalcCapt8 = 'Ср. длина комнаты, ';
//    strCalcCapt9 = 'Площадь для 1 РМ, ';
//    strCalcCapt10 = 'Расстояние от кросса к самому близкому  РМ, ';
//    strCalcCapt11 = 'Расстояние от кросса к самому дальнему  РМ, ';
//    strCalcCapt12 = 'Расход короба на 1 РМ, ';
//    strCalcCapt13 = 'Расход короба на 1 комнату, ';
//    strCalcCapt14 = '=                          ';
//    strCalcCapt15 = 'К-во кабеля в упаковке, ';
//    strCalcCapt16 = 'Высота размещения РМ, ';
//    strCalcCapt17 = 'Запас для выполнения разделки кабеля, ';
//    strCalcCapt18 = 'Высота подвесного потолка, ';

const
    idwCC = 1;   //'Прокладка кабельных каналов (м)';
    idwCable  = 2; // 'Укладка кабеля (м)';
    idwRM = 3;  //'Установка робочего места (шт.)';
    idwShelf = 4; // 'Монтаж шкафа (шт.)';
    idwPP = 5; //'Монтаж патч-панели в шкаф/стойку (шт.)';
    idwOrg = 6; //'Монтаж организатора в шкаф /стойку (шт.) ';
    idwCrossPort = 7; //'Кроссировка (1 порт)';
    idwTestPort = 8; //'Тестирование соединений (1 порт)';
    idwProectPort = 9; //'Проектные работы  (1 порт)';
    idwTransport = 10; //'Транспортные расходы';
    idwAnother = 11; //'Другие пусконаладочные работы';
    idwKoef = 12; //'Коэфициент  на работы (согласно особому характеру работ)';
const //для типа отчётной строки
    idTypePozMaterial = '1';
    idTypePozWorks = '2';

type
  T_KalcDocument = class(TMyObject)
   // CoXML: CoDOMDocument;
    Xml: TXMLDocument;
    TopNode: IDOMDocument;
    RootNode: IDomNode;
//    FNodeList: IXMLDOMNodeList;
    FOwner: TForm;
  private
    //coXML: CoDOMDocument;
    FName: string;
    procedure InitXMl;
    procedure AddParamToXMl(AName: string; Value: string = '');
    procedure AddToXmlGrid(AGrid: TcxGridDBTableView);
    procedure LoadGridFromXML(AGrid: TcxGridDBTableView);

  public
    constructor Create(AOwner:  TObject; AFileName: string = '');
    destructor Destroy; override;
    procedure SaveComponentValue(AComponent: TComponent);
    procedure LoadComponentValue(AComponent: TComponent);
    procedure CreateXML(AFieldName: string);
    procedure SaveToFile(AFileName: string);
    procedure LoadFromFile(AFileName: string);

  end;

  TF_Kalc = class(TForm)
    Main_PageControl: TRzPageControl;
    TabProject: TRzTabSheet;
    TabComponent: TRzTabSheet;
    RMGroup: TRzGroupBox;
    BuildGroupBox5: TRzGroupBox;
    Label2: TLabel;
    vKolRM: TRzSpinEdit;
    Label1: TLabel;
    vKolPortForRM: TRzSpinEdit;
    vKKolDopMest: TRzSpinEdit;
    Label3: TLabel;
    Label4: TLabel;
    vKolFloor: TRzSpinEdit;
    Label5: TLabel;
    vWidthFloor: TRzSpinEdit;
    Label6: TLabel;
    vLengthFloor: TRzSpinEdit;
    Label7: TLabel;
    vSTotalPlase: TRzSpinEdit;
    vKSWorkPlase: TRzSpinEdit;
    Label8: TLabel;
    vSWorkPlase: TRzSpinEdit;
    Label9: TLabel;
    Label10: TLabel;
    vSKab_Edit: TRzSpinEdit;
    Label11: TLabel;
    vHeighFloor: TRzSpinEdit;
    Label13: TLabel;
    vSForRM: TRzSpinEdit;
    Label14: TLabel;
    vTotalKolRM: TRzSpinEdit;
    vTotalKolPort: TRzSpinEdit;
    Label15: TLabel;
    Label16: TLabel;
    StaticText1: TStaticText;
    StaticText2: TStaticText;
    vKolRMForFloor: TFlyTreeViewPro;
    pmForGrid: TPopupMenu;
    ActionList1: TActionList;
    actAddRecord: TAction;
    actAddRecord1: TMenuItem;
    actDelRecord: TAction;
    N1: TMenuItem;
    RzGroupBox3: TRzGroupBox;
    TypeConnectEuipment_RadioGroup: TRzRadioGroup;
    CableCanalSheet: TRzTabSheet;
    actAddCableCanal: TAction;
    actDelCableCanal: TAction;
    TabSheet1: TRzTabSheet;
    RzPanel1: TRzPanel;
    RzPanel2: TRzPanel;
    AllComponent_GridDBTableView1: TcxGridDBTableView;
    AllComponent_GridLevel1: TcxGridLevel;
    AllComponent_Grid: TcxGrid;
    AllComponent_Grid_Name: TcxGridDBColumn;
    AllComponent_Grid_Arcticul: TcxGridDBColumn;
    AllComponent_Grid_Kolvo: TcxGridDBColumn;
    AllComponent_Grid_Cost: TcxGridDBColumn;
    AllComponent_Grid_price: TcxGridDBColumn;
    RzGroupBox4: TRzGroupBox;
    Label36: TLabel;
    vKolReservCable: TRzSpinEdit;
    Label37: TLabel;
    vKolPortForMCable: TRzSpinEdit;
    actAddCable: TAction;
    actDelCable: TAction;
    vKolPKForRM: TRzSpinEdit;
    Label39: TLabel;
    TypeWayCC_Panel: TRzPanel;
    TypeWeyCC_PageControl: TRzPageControl;
    CableInFloor_Sheet: TRzTabSheet;
    CableUnderCeil_Sheet: TRzTabSheet;
    CableInCC_Sheet: TRzTabSheet;
    TypeWayCC_TopPanel: TRzPanel;
    FixCableWey_ComboBox: TRzComboBox;
    Label22: TLabel;
    CCForFloor_Grid: TcxGrid;
    CCForFloor_GridTableView: TcxGridDBTableView;
    CCForFloor_Grid_ID: TcxGridDBColumn;
    CCForFloor_Grid_Name: TcxGridDBColumn;
    CCForFloor_Grid_Articul: TcxGridDBColumn;
    CCForFloor_Grid_Price: TcxGridDBColumn;
    CCForFloor_Grid_Percent: TcxGridDBColumn;
    CCForFloor_GridLevel: TcxGridLevel;
    Label23: TLabel;
    RzGroupBox1: TRzGroupBox;
    ScrollBox1: TScrollBox;
    FormulaFloor_Group: TRzRadioGroup;
    FormulaFloor1_Panel: TRzPanel;
    Label43: TLabel;
    Label44: TLabel;
    vFormulaFloor1_X: TRzSpinEdit;
    vFormulaFloor1_Y: TRzSpinEdit;
    FormulaFloor2_Panel: TRzPanel;
    Label42: TLabel;
    Label45: TLabel;
    vFormulaFloor2_X: TRzSpinEdit;
    Label46: TLabel;
    vKolRooms: TRzSpinEdit;
    Label40: TLabel;
    vWidthRoom: TRzSpinEdit;
    Label41: TLabel;
    vLengthRoom: TRzSpinEdit;
    CCUnderCeil_Grid: TcxGrid;
    CCUnderCeil_GridTableView: TcxGridDBTableView;
    CCUnderCeil_Grid_id: TcxGridDBColumn;
    CCUnderCeil_Grid_Name: TcxGridDBColumn;
    CCUnderCeil_Grid_Articul: TcxGridDBColumn;
    CCUnderCeil_Grid_price: TcxGridDBColumn;
    CCUnderCeil_Grid_Percent: TcxGridDBColumn;
    CCUnderCeil_GridLevel: TcxGridLevel;
    vHeigthFalseCeil: TRzSpinEdit;
    Label12: TLabel;
    Label48: TLabel;
    FormulaUnderCail_Group: TRzGroupBox;
    ScrollBox2: TScrollBox;
    FormulaUnderCail_RadioGroup: TRzRadioGroup;
    FormulaUnderCail1_Panel: TRzPanel;
    Label49: TLabel;
    Label50: TLabel;
    vFormulaUnderCeil1_X: TRzSpinEdit;
    vFormulaUnderCeil1_Y: TRzSpinEdit;
    FormulaUnderCail2_Panel: TRzPanel;
    Label51: TLabel;
    vFormulaUnderCeil2_X: TRzSpinEdit;
    FormulaDekorCC_Group: TRzGroupBox;
    ScrollBox3: TScrollBox;
    FormulaDekorCC_RadioGroup: TRzRadioGroup;
    FormulaDekorCC1_Panel: TRzPanel;
    Label53: TLabel;
    Label54: TLabel;
    FormulaDekorCC2_Panel: TRzPanel;
    Label56: TLabel;
    vFormulaDekorCC2_X: TRzSpinEdit;
    Label55: TLabel;
    Label59: TLabel;
    vHeigthCC: TRzSpinEdit;
    RzGroupBox5: TRzGroupBox;
    ScrollBox4: TScrollBox;
    FormulaInCC_Group: TRzRadioGroup;
    FormulaInCC3_Panel: TRzPanel;
    Label65: TLabel;
    vFormulaInCC3_X: TRzSpinEdit;
    Label57: TLabel;
    Label66: TLabel;
    vFormulaInCC3_Y: TRzSpinEdit;
    FormulaInCC1_Panel: TRzPanel;
    Label63: TLabel;
    Label64: TLabel;
    Label17: TLabel;
    vFormulaInCC1_X: TRzSpinEdit;
    Openwir_Sheet: TRzTabSheet;
    ElPointFix_Grid: TcxGrid;
    ElPointFix_GridTableView: TcxGridDBTableView;
    ElPointFix_Grid_id: TcxGridDBColumn;
    ElPointFix_Grid_Name: TcxGridDBColumn;
    ElPointFix_Grid_Articul: TcxGridDBColumn;
    ElPointFix_Grid_Price: TcxGridDBColumn;
    ElPointFix_Grid_Percent: TcxGridDBColumn;
    ElPointFix_GridLevel: TcxGridLevel;
    Label60: TLabel;
    RzGroupBox6: TRzGroupBox;
    ScrollBox5: TScrollBox;
    OpenWir_RadioGroup: TRzRadioGroup;
    MetodOpenWir1_panel: TRzPanel;
    Label61: TLabel;
    vMetodOpenWir1_Rashod: TRzSpinEdit;
    Label70: TLabel;
    FormulaInCC2_Panel: TRzPanel;
    Label68: TLabel;
    Label69: TLabel;
    Label72: TLabel;
    vFormulaInCC2_X: TRzSpinEdit;
    Label31: TLabel;
    vDistShot: TRzSpinEdit;
    vDistLong: TRzSpinEdit;
    Label21: TLabel;
    Label47: TLabel;
    Label73: TLabel;
    Label74: TLabel;
    ZakazchikName_Edit: TRzEdit;
    PodradchikName_edit: TRzEdit;
    Curr_ComboBox: TcxComboBox;
    actExit: TAction;
    EIncludHarProj: TRzCheckBox;
    CC_PopupMenu: TPopupMenu;
    MenuItem1: TMenuItem;
    MenuItem2: TMenuItem;
    Cable_PopupMenu: TPopupMenu;
    MenuItem3: TMenuItem;
    MenuItem4: TMenuItem;
    OpenDialog1: TOpenDialog;
    SaveDialog1: TSaveDialog;
    ToolBar1: TToolBar;
    OpenFile_Btn: TRzBitBtn;
    SaveFile_Btn: TRzBitBtn;
    ClearProject_Btn: TRzBitBtn;
    gbFloorsProperties: TRzGroupBox;
    gbSquare: TRzGroupBox;
    gbRoomProperties: TRzGroupBox;
    ToolBar2: TToolBar;
    tbOpen: TToolButton;
    tbSave: TToolButton;
    tbClear: TToolButton;
    ImageList1: TImageList;
    pcComponentTypes: TRzPageControl;
    tsWorkPlaces: TRzTabSheet;
    CostRMGrid: TcxGrid;
    CostRMGridTableView: TcxGridDBTableView;
    ID_Column: TcxGridDBColumn;
    Name_Column: TcxGridDBColumn;
    Articul_Column: TcxGridDBColumn;
    Price_Column: TcxGridDBColumn;
    CostRMGrid_Kolvo: TcxGridDBColumn;
    CostRMGridLevel1: TcxGridLevel;
    tsPathCords: TRzTabSheet;
    CostPK_Grid: TcxGrid;
    CostPKDBTableView: TcxGridDBTableView;
    CostPKColumn_ID: TcxGridDBColumn;
    CostPKColumn_Name: TcxGridDBColumn;
    CostPKColumn_Articul: TcxGridDBColumn;
    CostPKColumn_Price: TcxGridDBColumn;
    CostPK_Missing: TcxGridDBColumn;
    CostPK_Persent: TcxGridDBColumn;
    CostPK_GridLevel1: TcxGridLevel;
    tsPathPanals: TRzTabSheet;
    CostPP_Grid: TcxGrid;
    CostPP_GridDBTableView: TcxGridDBTableView;
    CostPP_GridColumn_ID: TcxGridDBColumn;
    CostPP_GridColumn_Name: TcxGridDBColumn;
    CostPP_GridColumn_Articul: TcxGridDBColumn;
    CostPP_GridColumn_Price: TcxGridDBColumn;
    CostPP_GridLevel1: TcxGridLevel;
    tsOrganizator: TRzTabSheet;
    CostOrg_Grid: TcxGrid;
    GT_CostOrg: TcxGridDBTableView;
    CostOrg_GridColumn_ID: TcxGridDBColumn;
    CostOrg_GridColumn_Name: TcxGridDBColumn;
    CostOrg_GridColumn_Articul: TcxGridDBColumn;
    CostOrg_GridColumn_Price: TcxGridDBColumn;
    CostOrg_GridLevel1: TcxGridLevel;
    tsConsolidationPoints: TRzTabSheet;
    StaticText3: TStaticText;
    CostShelf_Grid: TcxGrid;
    CostShelf_GridDBTableView: TcxGridDBTableView;
    CostShelf_GridColumn_Id: TcxGridDBColumn;
    CostShelf_GridColumnName: TcxGridDBColumn;
    CostShelf_GridColumnArticul: TcxGridDBColumn;
    CostShelf_GridColumn_Price: TcxGridDBColumn;
    CostShelf_GridLevel: TcxGridLevel;
    RzPanel4: TRzPanel;
    Label29: TLabel;
    vCm_Shelf: TRzSpinEdit;
    OnceShelfCheck: TRzCheckBox;
    StaticText7: TStaticText;
    ServFloor_ComboBox: TcxLookupComboBox;
    RzPanel5: TRzPanel;
    ECostShelfGridCheck: TRzCheckBox;
    RzPanel6: TRzPanel;
    pnShelfForFloorOpt: TRzPanel;
    FixAllEcxeptSelCheck: TRzCheckBox;
    ShelfForFloor_Grid: TcxGrid;
    ShelfForFloor_GridDBTableView: TcxGridDBTableView;
    ShelfForFloor_GridColumn_Floor: TcxGridDBColumn;
    ShelfForFloor_GridColumn_id_Shelf: TcxGridDBColumn;
    ShelfForFloor_GridColumn_Price: TcxGridDBColumn;
    ShelfForFloor_Grid_Id: TcxGridDBColumn;
    ShelfForFloor_GridLevel: TcxGridLevel;
    Splitter1: TSplitter;
    tsAdditionalEquipment: TRzTabSheet;
    RzPanel7: TRzPanel;
    Label30: TLabel;
    vCostDopEq: TRzSpinEdit;
    RzPanel8: TRzPanel;
    EDopEqGrid_Check: TRzCheckBox;
    DopEq_Grid: TcxGrid;
    DopEq_TableView: TcxGridDBTableView;
    DopEq_Grid_id: TcxGridDBColumn;
    DopEq_Grid_Name: TcxGridDBColumn;
    DopEq_Grid_Articul: TcxGridDBColumn;
    DopEq_Grid_Price: TcxGridDBColumn;
    DopEq_Kolvo: TcxGridDBColumn;
    DopEq_Level: TcxGridLevel;
    RzPanel9: TRzPanel;
    Label20: TLabel;
    vCPK: TRzSpinEdit;
    eKalcPKForRM_Check: TRzCheckBox;
    RzPanel10: TRzPanel;
    ECostPKGridCheck: TRzCheckBox;
    RzPanel11: TRzPanel;
    Label19: TLabel;
    vCPP: TRzSpinEdit;
    Label34: TLabel;
    vKolPortPP: TRzSpinEdit;
    RzPanel12: TRzPanel;
    ECostPPGrid_Check: TRzCheckBox;
    RzPanel13: TRzPanel;
    Label28: TLabel;
    vCOrg: TRzSpinEdit;
    RzPanel14: TRzPanel;
    ECostOrgGrid_Check: TRzCheckBox;
    RzPanel15: TRzPanel;
    RzPanel16: TRzPanel;
    Label18: TLabel;
    vCRM: TRzSpinEdit;
    RzPanel17: TRzPanel;
    ECostRMGrid_Check: TRzCheckBox;
    RzGroupBar1: TRzGroupBar;
    grComponentTypes: TRzGroup;
    pcChannelComponTypes: TRzPageControl;
    TabSheet2: TRzTabSheet;
    RzPanel18: TRzPanel;
    StaticText4: TStaticText;
    CableCanalGrid: TcxGrid;
    CableCanalGrid_TableView1: TcxGridDBTableView;
    CableCanalGrid_NPP: TcxGridDBColumn;
    CableCanalGrid_Name: TcxGridDBColumn;
    CableCanalGrid_Articul: TcxGridDBColumn;
    CableCanalGrid_Price: TcxGridDBColumn;
    CableCanalGrid_Percent: TcxGridDBColumn;
    CableCanalGridLevel1: TcxGridLevel;
    TabSheet4: TRzTabSheet;
    RzPanel19: TRzPanel;
    StaticText5: TStaticText;
    Cable_Grid: TcxGrid;
    Cable_Grid_DBTableView: TcxGridDBTableView;
    Cable_Grid_Name: TcxGridDBColumn;
    Cable_Grid_Articul: TcxGridDBColumn;
    Cable_Grid_Price: TcxGridDBColumn;
    Cable_Grid_Percent: TcxGridDBColumn;
    Cable_Grid_TypeUse: TcxGridDBColumn;
    Cable_GridLevel1: TcxGridLevel;
    RzPanel20: TRzPanel;
    Label35: TLabel;
    vKolCableInPark: TRzSpinEdit;
    Label33: TLabel;
    vHeigthRM: TRzSpinEdit;
    Label32: TLabel;
    vKolTehreserv: TRzSpinEdit;
    Label26: TLabel;
    vKCableRezerv: TRzSpinEdit;
    Label24: TLabel;
    vCableEndRezerv: TRzSpinEdit;
    gbChannelComponTypes: TRzGroupBar;
    RzPanel21: TRzPanel;
    grChannelComponTypes: TRzGroup;
    RzPanel22: TRzPanel;
    btCalc: TSpeedButton;
    btPrintReport: TSpeedButton;
    btEditReport: TSpeedButton;
    Clear_Btn: TSpeedButton;
    FixBtn: TSpeedButton;
    KolRMBtn: TSpeedButton;
    cxStyleRepository1: TcxStyleRepository;
    cxBackNormal: TcxStyle;
    cxBackDisabled: TcxStyle;
    Splitter2: TSplitter;
    RzGroupBox2: TRzGroupBox;
    ElementOfCC_Grid: TcxGrid;
    ElementOfCC_Grid_DBTableView: TcxGridDBTableView;
    id: TcxGridDBColumn;
    Npp_CC: TcxGridDBColumn;
    Id_Type: TcxGridDBColumn;
    Articul: TcxGridDBColumn;
    price: TcxGridDBColumn;
    rashod: TcxGridDBColumn;
    cxGridLevel1: TcxGridLevel;
    lng_Forms: TsiLangLinked;
    TabSheet3: TRzTabSheet;
    RzPanel3: TRzPanel;
    RzPanel23: TRzPanel;
    btClearPriceWorks: TSpeedButton;
    PriceWorks_Grid: TcxGrid;
    PriceWorks_TableView: TcxGridDBTableView;
    PriceWorks_Grid_Name: TcxGridDBColumn;
    PriceWorks_Grid_Price: TcxGridDBColumn;
    cxGridLevel2: TcxGridLevel;
    AllComponent_Grid_TypePoz: TcxGridDBColumn;
    cxFoter: TcxStyle;
    Label25: TLabel;
    vKoefDistShot: TRzSpinEdit;
    Label27: TLabel;
    vKoefDistLong: TRzSpinEdit;
    Label38: TLabel;
    procedure vKSWorkPlaseChange(Sender: TObject);
    procedure vWidthFloorChange(Sender: TObject);
    procedure vLengthFloorChange(Sender: TObject);
    procedure vSTotalPlaseChange(Sender: TObject);
    procedure vKolFloorChange(Sender: TObject);
    procedure vKolPortForRMChange(Sender: TObject);
    procedure vTotalKolRMChange(Sender: TObject);
    procedure vKolRMChange(Sender: TObject);
    procedure KolRMBtnClick(Sender: TObject);
   { procedure vKolRMForFloorEdited(Sender: TObject; Node: TFlyNode;
      var S: String);}
    procedure ECostRMGrid_CheckClick(Sender: TObject);
    procedure ECostPPGrid_CheckClick(Sender: TObject);
    procedure actAddRecordExecute(Sender: TObject);
    procedure ECostPKGridCheckClick(Sender: TObject);
    procedure actDelRecordExecute(Sender: TObject);
    procedure ECostOrgGrid_CheckClick(Sender: TObject);
    procedure ECostShelfGridCheckClick(Sender: TObject);
    procedure Main_PageControlChanging(Sender: TObject; NewIndex: Integer;
      var AllowChange: Boolean);
    procedure actAddCableCanalExecute(Sender: TObject);
    function GetFreePercent(count: integer): integer;
    function GetFreePercentForCable: Integer;
 //   Procedure InitTypeOfElementCC_MemTable;
 //   Procedure InitTypeUseCable_MemTable;
    procedure actDelCableCanalExecute(Sender: TObject);
    procedure CableCanalMemTableChange(Sender: TField);
    procedure CableCanalGrid_TableView1EditValueChanged(
      Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
    procedure CableCanalMemTableAfterDelete(DataSet: TDataSet);
    procedure btCalcClick(Sender: TObject);
    procedure actAddCableExecute(Sender: TObject);
    procedure actDelCableExecute(Sender: TObject);
    procedure CableCanalGrid_TableView1KeyDown(Sender: TObject;
      var Key: Word; Shift: TShiftState);
    procedure Cable_Grid_DBTableViewKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure CostRMGridKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure FixBtnClick(Sender: TObject);
    procedure Clear_BtnClick(Sender: TObject);
    procedure EDopEqGrid_CheckClick(Sender: TObject);
    procedure DopEq_TableViewEditValueChanged(
      Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
    procedure CostPP_GridDBTableViewEditValueChanged(
      Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
    procedure GT_CostOrgEditValueChanged(
      Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
    procedure Cable_Grid_DBTableViewEditValueChanged(
      Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
    procedure vKKolDopMestChange(Sender: TObject);
    procedure FixCableWey_ComboBoxCloseUp(Sender: TObject);
    procedure FormulaFloor_GroupChanging(Sender: TObject;
      NewIndex: Integer; var AllowChange: Boolean);
    procedure FormulaUnderCail_RadioGroupChanging(Sender: TObject;
      NewIndex: Integer; var AllowChange: Boolean);
    procedure FormulaDekorCC_RadioGroupChanging(Sender: TObject;
      NewIndex: Integer; var AllowChange: Boolean);
    procedure FormulaInCC_GroupChanging(Sender: TObject; NewIndex: Integer;
      var AllowChange: Boolean);
    procedure ServFloor_ComboBoxPropertiesChange(Sender: TObject);
    procedure vWidthRoomChange(Sender: TObject);
    procedure vLengthRoomChange(Sender: TObject);
    procedure PrintClick(Sender: TObject);
    procedure actExitExecute(Sender: TObject);
    procedure btPrintReportClick(Sender: TObject);
    procedure btEditReportClick(Sender: TObject);
    procedure Curr_ComboBoxPropertiesChange(Sender: TObject);
    procedure vHeighFloorChange(Sender: TObject);
    procedure vSKab_EditChange(Sender: TObject);
    procedure vSForRMChange(Sender: TObject);
    procedure AllComponent_GridDBTableView1EditValueChanged(
      Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
    procedure OpenFile_BtnClick(Sender: TObject);
    procedure SaveFile_BtnClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure CostShelf_GridDBTableViewEditValueChanged(
      Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
    procedure CostRMGridTableViewDragOver(Sender, Source: TObject; X,
      Y: Integer; State: TDragState; var Accept: Boolean);
    procedure CostRMGridTableViewDragDrop(Sender, Source: TObject; X,
      Y: Integer);
    procedure CostPKDBTableViewDragDrop(Sender, Source: TObject; X,
      Y: Integer);
    procedure CostPP_GridDBTableViewDragDrop(Sender, Source: TObject; X,
      Y: Integer);
    procedure GT_CostOrgDragDrop(Sender, Source: TObject; X,
      Y: Integer);
    procedure CostShelf_GridDBTableViewDragDrop(Sender, Source: TObject; X,
      Y: Integer);
    procedure DopEq_TableViewDragDrop(Sender, Source: TObject; X,
      Y: Integer);
    procedure CableCanalGrid_TableView1DragDrop(Sender, Source: TObject; X,
      Y: Integer);
    procedure ElPointFix_GridTableViewDragDrop(Sender, Source: TObject; X,
      Y: Integer);
    procedure CCForFloor_GridTableViewDragDrop(Sender, Source: TObject; X,
      Y: Integer);
    procedure CCUnderCeil_GridTableViewDragDrop(Sender, Source: TObject; X,
      Y: Integer);
    procedure AllComponent_GridDBTableView1FocusedItemChanged(
      Sender: TcxCustomGridTableView; APrevFocusedItem,
      AFocusedItem: TcxCustomGridTableItem);
    procedure AllComponent_Grid_pricePropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure AllComponent_Grid_KolvoPropertiesValidate(Sender: TObject;
      var DisplayValue: Variant; var ErrorText: TCaption;
      var Error: Boolean);
    procedure Cable_Grid_DBTableViewDragDrop(Sender, Source: TObject; X,
      Y: Integer);
    procedure ClearProject_BtnClick(Sender: TObject);
    procedure grComponentTypesItems0Click(Sender: TObject);
    procedure grChannelComponTypesItems0Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure CostRMGridTableViewEditValueChanged(
      Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
    procedure Name_ColumnPropertiesEditValueChanged(Sender: TObject);
    procedure DopEq_GridExit(Sender: TObject);
    procedure btClearPriceWorksClick(Sender: TObject);
    procedure AllComponent_Grid_TypePozGetDisplayText(
      Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
      var AText: String);
    procedure vKolRMForFloorEdited(Sender: TObject; Node: TFlyNode;
      var S: WideString);
  private
    { Private declarations }
    TotalKolCable, TotalKolCC: integer;
//    FCountCC, FCountECC: integer;
    procedure CalculateCC;
    procedure PutHaracterProjectInMT;
    procedure AddCCElements;

    procedure EnableTableView(ATableView: TcxGridDBTableView; AEnabled: Boolean);
    function GetKoefForWorks: double;

    procedure FixLabeles;
  public
    { Public declarations }
    Kalc_DM: TKalc_DM;
    KoefForWorks: double;
    ServerFloor: integer;
    procedure ClearProject;
    procedure AutoKomplectFloorByRM;
    function CmpFloorsWithKolRM: integer;
    //constructor Create(AOwner: TComponent);
    destructor Destroy; override;
    function CalculateProject: double;
    procedure AddRecordInReport(AName: string; AArticul: String; AKol: integer;
                                APrice, ACost: double; AidTypePoz: string = idTypePozMaterial);
    Procedure AddRecordInHaracterProject_MemTable(AName, AZnach: string);
    Function getCostOfProjectReportParams: TCostOfProjectReportParams;

    procedure Execute;

    function GetPriceForKalcFromDragCompon(ACompon: TSCSComponent): double;

    procedure PutToReportWork(AIdWorks: integer; AKolWorks: integer; AKoef: double = 1);
  end;

Const
  TempFile = 'spe.tmp';

const
  //название полей
  fnPercent = 'Percent';
  fnArticul = 'Articul';

Const
  //название свойств
  pnPORTCOUNT  = 'PORTCOUNT';

var
  F_Kalc: TF_Kalc;



implementation

uses Math, U_SCSLists, Treecoll, U_Main, U_ResourceReport, DBConsts;
{$R *.dfm}
//***************************************************
function TF_Kalc.GetFreePercent(count: integer): integer;
var
  i: integer;
  RecNo: integer;
begin
  Result := 100;
//  RecNo := CableCanalMemTable.RecNo;
  Kalc_DM.CableCanalMemTable.First;
  for i := 0 to Count - 1 do
  begin
    Result := Result - Kalc_DM.CableCanalMemTable.FieldByName('Percent').AsInteger;
    if i = count then
    begin
    end
    else
      Kalc_DM.CableCanalMemTable.Next;
  end;
 end;
//****************************************************
//***************************************************
function TF_Kalc.GetFreePercentForCable: integer;
var
  i: integer;
  RecNo: integer;
  per1, per2: integer;
begin
  per1 := 100;
  per2 := 100;
  Result := -1;
//  RecNo := CableCanalMemTable.RecNo;
  Kalc_DM.Cable_MemTable.First;
  for i := 0 to Kalc_DM.Cable_MemTable.RecordCount - 1 do
  begin
    if Kalc_DM.Cable_MemTable.FieldByName('Id_Missing').AsInteger = tcuRaspred then
    begin
      Per1 := Per1 - Kalc_DM.Cable_MemTable.FieldByName('Percent').AsInteger;
    end
    else
      Per2 := Per2 - Kalc_DM.Cable_MemTable.FieldByName('Percent').AsInteger;
  Kalc_DM.Cable_MemTable.Next;
  end;
  if (per1 < 0) and ((Per2 >0) and (per2 <> 100))  then
  begin
    Result := 1;
  end
  else
  if (per1 > 0) and (Per2 < 0)  then
  begin
    Result := 2;
  end
  else
  if (per1 = 0) and ((Per2 = 0) or (per2 = 100)) then
  begin
    Result := 0;
  end;
  if (per1 < 0) and (per2 < 0) then
    Result := 3;
  if (per1 >0) and (result = -1) then
    result := 4;
  if (per2 >0) and (result = -1) then
    result := 5;
  if (per1 <0) and (result = -1) then
    result := 6;
  if (per2 <0) and (result = -1) then
    result := 7;
end;
//****************************************************

///*********------------------------******************
procedure TF_Kalc.CableCanalMemTableChange(Sender: TField);
begin
  if GetFreePercent(Kalc_DM.CableCanalMemTable.RecordCount)< 0 then
  begin
    StaticText4.Show;
  end
  else
  begin
    StaticText4.Hide;
  end;
end;
//****************************************************



procedure ValCostFromGrid(AEdit: TRzSpinEdit; ATable: TkbmMemTable);
var
  I, kolvo: integer;
  sum: double;
  val: double;
  KolvoFlag: boolean;
  Field: TField;
begin
   kolvo := 1;
   Field := ATable.FindField('Kolvo');
    if Field <> nil then
      KolvoFlag := true
    else
      KolvoFlag := false;
    Sum := 0;
    ATable.first;
    for i := 0 to ATable.RecordCount - 1 do
    begin
      if ATable.FieldByName('Price').AsString <> '' then
      begin
        if KolvoFlag then
          kolvo := ATable.FieldByName('Kolvo').AsInteger;
        if kolvo < 1 then
          kolvo := 1;
        val := ATable.FieldByName('Price').AsFloat;
        Sum := Sum +  Val * kolvo;
        kolvo := 1;
      end;
      ATable.Next;
    end;
  AEdit.Value := Sum;
end;

procedure TF_Kalc.DopEq_TableViewDragDrop(Sender, Source: TObject; X,
  Y: Integer);
var price: double;
begin
  price := GetPriceForKalcFromDragCompon(GDropComponent);
  U_Kalc_DM.AddRecordInMemTable(Kalc_DM.DopEq_MemTable, GDropComponent.Name, GDropComponent.ArticulProducer,Price,1);
 // TcxGridTableView(Sender).Refresh;
  ValCostFromGrid(vCostDopEq, Kalc_DM.DopEq_MemTable);
end;


function TF_Kalc.CmpFloorsWithKolRM: integer;
var
  KolRM, RMOfFloor, i: integer;
begin
  result := 0;
  KolRm := trunc(vTotalKolRM.Value);
  for i := 0 to vKolRMForFloor.Items.Count - 1 do
  begin
    if vKolRMForFloor.Items[i].Cells[1] = '' then
      RMOfFloor := 0
    else
      RMOfFloor := StrToInt(vKolRMForFloor.Items[i].Cells[1]);
    KolRM := KolRm - RMOfFloor;
  end;
  Result := KolRM; //* (-1);
end;

procedure TF_Kalc.AutoKomplectFloorByRM;
var
  KolRm,  KolFloor: integer;
  KolRmForFloor : integer;
  i, count: integer;
begin
  KolFloor := trunc(vKolFloor.Value);
  if KolFloor <= 0 then
    KolFloor := 1;
  KolRm := trunc(vTotalKolRM.Value);
  KolRmForFloor := trunc(KolRm / KolFloor);
  count := vKolRMForFloor.Items.Count -1;
  for i := 0 to Count do
  begin
    if i = Count then
    begin
      vKolRMForFloor.Items[i].Cells[1] := IntToStr(KolRmForFloor + KolRm mod KolFloor);
    end
    else
    begin
      vKolRMForFloor.Items[i].Cells[1] := IntToStr(KolRmForFloor);
    end;
  end;
end;
procedure TF_Kalc.vKSWorkPlaseChange(Sender: TObject);
var
  SVal: double;
begin
  If vSTotalPlase.Value <> 0 then
  begin
    SVal := vSTotalPlase.Value;
    vSWorkPlase.Value := SVal * vKSWorkPlase.Value / 100;
   // KolRMBtnClick(Self);
  end;
end;

procedure TF_Kalc.vWidthFloorChange(Sender: TObject);

begin
  vSTotalPlase.Value := vWidthFloor.Value * vLengthFloor.Value;
end;

procedure TF_Kalc.vLengthFloorChange(Sender: TObject);
begin
    vSTotalPlase.Value := vWidthFloor.Value * vLengthFloor.Value;
end;

procedure TF_Kalc.vSTotalPlaseChange(Sender: TObject);
begin
  vSWorkPlase.Value := vSTotalPlase.Value * vKSWorkPlase.Value / 100;
//  vKolRM.Value := vSWorkPlase.Value / vSKab_Edit.Value;
end;


procedure TF_Kalc.vKolFloorChange(Sender: TObject);
var
  RowCount, Val: integer;
  Count: integer;
begin
  if vKolFloor.Value <= vKolFloor.Max then
  begin
      vSTotalPlase.Value := vKolFloor.Value * vWidthFloor.Value * vLengthFloor.Value;
     // Sleep(100);
      vKolRooms.Value := trunc(vSWorkPlase.Value / vSKab_Edit.Value);
      //
      vKolRMForFloor.Items.BeginUpdate;
      try
        RowCount := vKolRMForFloor.Items.Count;
        Val := trunc(vKolFloor.Value);
        If VaL <= 0 then
          Val := 1;
        if RowCount < Val then
        begin
          For Count := RowCount to Val-1 do
          begin
            vKolRMForFloor.Items.Add(vKolRMForFloor.Items[count-1], IntToStr(Count+1) + cKalc_Msg1);
            Kalc_DM.AddShelfForFloor(IntToStr(Count+1) + cKalc_Msg1);
          end;
        end;
        if RowCount > Val then
        begin
          For Count := RowCount-1 downto Val do
          begin
            vKolRMForFloor.Items.Delete(vKolRMForFloor.Items[count]);
            Kalc_DM.ShelfForFloor_MemTable.Last;
            Kalc_DM.ShelfForFloor_MemTable.Delete;
          end;
        end;
        if vTotalKolRM.Value > 0 then
        begin
          AutoKomplectFloorByRM;
        end;
      finally
        vKolRMForFloor.Items.EndUpdate;
      end;
  end;
end;

procedure TF_Kalc.vKolPortForRMChange(Sender: TObject);
begin
  vTotalKolPort.Value := trunc(vTotalKolRM.Value * vKolPortForRM.Value);
 
end;

procedure TF_Kalc.vTotalKolRMChange(Sender: TObject);
begin
  vTotalKolPort.Value := trunc(vTotalKolRM.Value * vKolPortForRM.Value);
  AutoKomplectFloorByRM;
  if StaticText1.Visible then
  begin
    StaticText1.Hide;
    StaticText2.Hide;
  end;
end;

procedure TF_Kalc.vKolRMChange(Sender: TObject);
begin
 vTotalKolRM.Value := vKolRM.Value + trunc(vKolRM.Value * vKKolDopMest.Value/100);
end;

procedure TF_Kalc.vKolRMForFloorEdited(Sender: TObject; Node: TFlyNode;
  var S: WideString);
var razn: integer;
begin
  Node.Cells[1] := S;
  razn := CmpFloorsWithKolRM ;
  if razn <> 0 then
  begin
    StaticText1.Show;
    StaticText2.Caption := cKalc_Msg2 + IntToStr(razn);
    StaticText2.Show;
  end
  else
  begin
    StaticText1.Hide;
    StaticText2.Hide;
  end;
end;

procedure TF_Kalc.KolRMBtnClick(Sender: TObject);
begin
  vKolRM.Value := trunc(vKolRooms.Value *  trunc(vSKab_Edit.Value / vSForRM.Value));
end;

{procedure TF_Kalc.vKolRMForFloorEdited(Sender: TObject; Node: TFlyNode;
  var S: String);
var
  razn: integer;
begin
  Node.Cells[1] := S;
  razn := CmpFloorsWithKolRM ;
  if razn <> 0 then
  begin
    StaticText1.Show;
    StaticText2.Caption := cKalc_Msg2 + IntToStr(razn);
    StaticText2.Show;
  end
  else
  begin
    StaticText1.Hide;
    StaticText2.Hide;
  end;
end; }

procedure TF_Kalc.ECostRMGrid_CheckClick(Sender: TObject);
begin
  if ECostRMGrid_Check.Checked then
  begin
    CostRMGrid.Enabled := true;
    vCRM.Value := 0;
    vCRM.Enabled := False;
    if Kalc_DM.CostRM_MemTable.RecordCount > 0 then
      ValCostFromGrid(vCRM, Kalc_DM.CostRM_MemTable);

    //CostRMGridTableView.Styles.Background := nil; //cxBackNormal;
    EnableTableView(CostRMGridTableView, true);
  end
  else
  begin
    vCRM.Enabled := True;
    CostRMGrid.Enabled := false;

    //CostRMGridTableView.Styles.Background := cxBackDisabled;
    //CostRMGridTableView.Styles.Content := cxBackDisabled;
    EnableTableView(CostRMGridTableView, false);
  end;
end;

procedure TF_Kalc.ECostPPGrid_CheckClick(Sender: TObject);
begin
  if ECostPPGrid_Check.Checked then
  begin
    CostPP_Grid.Enabled := true;
    vCPP.Value := 0;
    vCPP.Enabled := false;
    if Kalc_DM.CostPP_MemTable.RecordCount > 0 then
      ValCostFromGrid(vCPP, Kalc_DM.CostPP_MemTable);

    EnableTableView(CostPP_GridDBTableView, true);
  end
  else
  begin
    CostPP_Grid.Enabled := false;
    vCPP.Enabled := true;

    EnableTableView(CostPP_GridDBTableView, false);
  end;
end;

procedure TF_Kalc.actAddRecordExecute(Sender: TObject);
var
  resultCmp, OstPer: integer;
begin
  if  CostRMGrid.IsFocused then
  begin
    U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CostRM_MemTable, 'Компонент ' + IntToStr(Kalc_DM.CostRM_MemTable.RecordCount + 1), '', 0, 1 );
    CostRMGrid.Refresh;
  end;
  if CostPK_Grid.IsFocused then
  begin
    resultCmp := Kalc_DM.CmpPerFromCostPk_MemTable(OstPer);
    case resultCmp of
      1 : U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CostPK_Memtable, cKalc_Msg4 + IntToStr(Kalc_DM.CostPK_MemTable.RecordCount + 1), '', 0, -1, OstPer, mpkCross);
      2,3 : U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CostPK_Memtable, cKalc_Msg4 + IntToStr(Kalc_DM.CostPK_MemTable.RecordCount + 1), '', 0, -1, OstPer, mpkRM);
    end;
  end;
  if CostPP_Grid.IsFocused  then
  begin
    if Kalc_DM.CostPP_MemTable.RecordCount = 0 then
      U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CostPP_MemTable, cKalc_Msg5 + IntToStr(Kalc_DM.CostPP_MemTable.RecordCount + 1));
  end;
  if CostOrg_Grid.IsFocused then
  begin
  if Kalc_DM.CostOrg_MemTable.RecordCount= 0 then
    U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CostOrg_MemTable, cKalc_Msg6 + IntToStr(Kalc_DM.CostOrg_MemTable.RecordCount + 1));
  end;
  if CostShelf_Grid.IsFocused then
  begin
    U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CostShelf_MemTable, cKalc_Msg7 + IntToStr(Kalc_DM.CostShelf_MemTable.RecordCount + 1));
  end;
  if DopEq_Grid.IsFocused then
  begin
    U_Kalc_DM.AddRecordInMemTable(Kalc_DM.DopEq_MemTable, cKalc_Msg8 + IntToStr(Kalc_DM.DopEq_MemTable.RecordCount + 1));
  end;
  if CCForFloor_Grid.IsFocused then
  begin
    OstPer := Kalc_DM.CmpPerFromCCFloor_MemTable;
    U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CCFloor_MemTable, cKalc_Msg9 + IntToStr(Kalc_DM.CCFLoor_MemTable.RecordCount + 1),
                                   '', 0, -1, OstPer);
  end;
  if CCUnderCeil_Grid.IsFocused then
  begin
    OstPer := Kalc_DM.CmpPerFromCCUnderCeil_MemTable;
    U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CCUnderCeil_MemTable, cKalc_Msg10 + IntToStr(Kalc_DM.CCUnderCeil_MemTable.RecordCount + 1),
                                   '', 0, -1, OstPer);
  end;
  if ElPointFix_Grid.IsFocused then
  begin
    OstPer := Kalc_DM.CmpPerFromElPointFix_MemTable;
    U_Kalc_DM.AddRecordInMemTable(Kalc_DM.ElPointFix_MemTable, cKalc_Msg11 + IntToStr(Kalc_DM.ElPointFix_MemTable.RecordCount + 1),
                                   '', 0, -1, OstPer);
  end;



end;

procedure TF_Kalc.ECostPKGridCheckClick(Sender: TObject);
begin
  if ECostPKGridCheck.Checked then
  begin
    CostPK_Grid.Enabled := true;
    vCPK.Value := 0;
    vCPK.Enabled := False;

    EnableTableView(CostPKDBTableView, true);
  end
  else
  begin
    CostPK_Grid.Enabled := false;
    vCPK.Enabled := True;

    EnableTableView(CostPKDBTableView, false);
  end;
end;

procedure TF_Kalc.actDelRecordExecute(Sender: TObject);
var
  price: double;
  id, i: integer;
  Kolvo: integer;
begin
  if CostRMGrid.IsFocused then
  begin
    Kolvo := 1;
    if Kalc_DM.CostRM_MemTable.RecordCount > 0 then
    begin
      if Kalc_DM.CostRM_MemTable.FieldByName('Price').AsString <> '' then
      begin
        price := Kalc_DM.CostRM_MemTable.FieldByName('Price').AsFloat;
        Kolvo := Kalc_DM.CostRM_MemTable.FieldByName('Kolvo').AsInteger;
        if Kolvo < 1 then
          Kolvo := 1;
      end;
      vCRM.Value := vCRM.Value - price * kolvo;
      Kalc_DM.CostRM_MemTable.Delete;
    end;
  end;
  if CostPK_Grid.IsFocused then
  begin
    if Kalc_DM.CostPK_MemTable.RecordCount > 0 then
    begin
      Kalc_DM.CostPK_MemTable.Delete;
    end;
  end;
  if CostPP_Grid.IsFocused  then
  begin
    if Kalc_DM.CostPP_MemTable.RecordCount > 0 then
    begin
      vCPP.Value := 0;
      Kalc_DM.CostPP_MemTable.Delete;
    end;
  end;
  if CostOrg_Grid.IsFocused  then
  begin
    if Kalc_DM.CostOrg_MemTable.RecordCount > 0 then
    begin
      vCOrg.Value := 0;
      Kalc_DM.CostOrg_MemTable.Delete;
    end;
  end;
  if CostShelf_Grid.IsFocused  then
  begin
    if Kalc_DM.CostShelf_MemTable.RecordCount > 0 then
    begin
      id := Kalc_DM.CostShelf_MemTable.FieldByName('Id').AsInteger;
      with  Kalc_DM.ShelfForFloor_MemTable do
      begin
        First;
        while Not Eof do
        begin
          if FieldbyName('id_shelf').AsInteger = id then
          begin
            Edit;
            FieldbyName('id_shelf').Clear;
            FieldbyName('price').Clear;
            Post;
          end;
          Next;
        end;
      end;
      Kalc_DM.CostShelf_MemTable.Delete;
    end;
  end;
  if DopEq_Grid.IsFocused then
  begin
    price := 0;
    kolvo := 1;
    if Kalc_DM.DopEq_MemTable.RecordCount > 0 then
    begin
      if Kalc_DM.DopEq_MemTable.FieldByName('price').AsString <> '' then
         price := Kalc_DM.DopEq_MemTable.FieldByName('price').AsFloat;
      Kolvo := Kalc_DM.DopEq_MemTable.FieldByName('Kolvo').AsInteger;
      if Kolvo < 1 then
        Kolvo := 1;
      vCostDopEq.Value := vCostDopEq.Value - price * kolvo;
      Kalc_DM.DopEq_MemTable.Delete;
    end;
  end;
  if CCForFloor_Grid.IsFocused then
  begin
    Kalc_DM.CCFloor_MemTable.Delete;
  end;
  if CCUnderCeil_Grid.IsFocused then
  begin
    Kalc_DM.CCUnderCeil_MemTable.Delete;
  end;
  if ElPointFix_Grid.IsFocused then
  begin
    Kalc_DM.ElPointFix_MemTable.Delete;
  end;
end;

procedure TF_Kalc.ECostOrgGrid_CheckClick(Sender: TObject);
begin
  if ECostOrgGrid_Check.Checked then
  begin
    CostOrg_Grid.Enabled := true;
    vCOrg.Value := 0;
    vCOrg.Enabled := false;
    if Kalc_DM.CostOrg_MemTable.RecordCount > 0 then
      ValCostFromGrid(vCOrg, Kalc_DM.CostOrg_MemTable);

    EnableTableView(GT_CostOrg, true);
  end
  else
  begin
    CostOrg_Grid.Enabled := false;
    vCOrg.Enabled := true;

    EnableTableView(GT_CostOrg, false);
  end;
end;

procedure TF_Kalc.ECostShelfGridCheckClick(Sender: TObject);
begin
  if ECostShelfGridCheck.Checked then
  begin
    vCm_Shelf.Value := 0;
    vCm_Shelf.Enabled := false;
    OnceShelfCheck.visible := false;
    CostShelf_Grid.Enabled := true;
    ShelfForFloor_Grid.Enabled := true;

    EnableTableView(CostShelf_GridDBTableView, true);
    EnableTableView(ShelfForFloor_GridDBTableView, true);
  end
  else
  begin
    vCm_Shelf.Enabled := true;
    OnceShelfCheck.Visible := true;
    CostShelf_Grid.Enabled := false;
    ShelfForFloor_Grid.Enabled := false;

    EnableTableView(CostShelf_GridDBTableView, false);
    EnableTableView(ShelfForFloor_GridDBTableView, false);
  end;
  CostShelf_Grid.Enabled := ECostShelfGridCheck.Checked;
  pnShelfForFloorOpt.Enabled := ECostShelfGridCheck.Checked;
end;

procedure TF_Kalc.Main_PageControlChanging(Sender: TObject;
  NewIndex: Integer; var AllowChange: Boolean);
var
  ActivePage: integer;
  OperTableView: TcxGridDBTableView;
begin
  //здесь нужно проверять контролы и заносить значения
  ActivePage := Main_PageControl.ActivePageIndex;
  OperTableView := Nil;
  if ActivePage = 4 then
  begin
    if AllComponent_Grid.Visible and F_Kalc.Visible then
      AllComponent_Grid.SetFocus;
    if AllComponent_GridDBTableView1.DataController.IsEditing then
      OperTableView := AllComponent_GridDBTableView1;
    //  AllowChange :=false;
  end;

  if ActivePage = 3 then
  begin
    if PriceWorks_Grid.Visible and F_Kalc.Visible then
      PriceWorks_Grid.SetFocus;
    if PriceWorks_TableView.DataController.IsEditing then
      OperTableView := PriceWorks_TableView;
      //AllowChange :=false;
  end;
  if ActivePage = 1 then
  begin
    if pcComponentTypes.Visible and F_Kalc.Visible then
    pcComponentTypes.SetFocus;
    if CostRMGridTableView.DataController.IsEditing then
     OperTableView := CostRMGridTableView;
    if CostPKDBTableView.DataController.IsEditing then
      OperTableView := CostPKDBTableView;
    if CostPP_GridDBTableView.DataController.IsEditing  then
      OperTableView := CostPP_GridDBTableView;
    if GT_CostOrg.DataController.IsEditing then
      OperTableView := GT_CostOrg;
    if CostShelf_GridDBTableView.DataController.IsEditing then
      OperTableView := CostShelf_GridDBTableView;
    if ShelfForFloor_GridDBTableView.DataController.IsEditing then
      OperTableView := ShelfForFloor_GridDBTableView;
    if DopEq_TableView.DataController.IsEditing then
      OperTableView := DopEq_TableView;


  end;
  if ActivePage = 2 then
  begin
    if  pcChannelComponTypes.Visible and F_Kalc.Visible then
      pcChannelComponTypes.SetFocus;
    if CCForFloor_GridTableView.DataController.IsEditing then
      OperTableView := CCForFloor_GridTableView;
    if CCUnderCeil_GridTableView.DataController.IsEditing then
      OperTableView := CCUnderCeil_GridTableView;
    if ElPointFix_GridTableView.DataController.IsEditing then
      OperTableView := CCUnderCeil_GridTableView;
    if CableCanalGrid_TableView1.DataController.IsEditing then
      OperTableView := CableCanalGrid_TableView1;
    if ElementOfCC_Grid_DBTableView.DataController.IsEditing then
      OperTableView := ElementOfCC_Grid_DBTableView;
    //then
//       AllowChange := false;
  end;
  if Assigned(OperTableView) then
    if OperTableView.DataController.IsEditing then
      begin
         AllowChange := false;
         OperTableView.DataController.Cancel;
         if not OperTableView.DataController.IsEditing then
           AllowChange := true;
      end;

  if ActivePage = 0 then
  begin
    if vKoefDistShot.Value + vKoefDistLong.Value > 100 then
    begin
      MessageModal(cKalc_Msg88, cKalc_Msg15, MB_ICONINFORMATION);
      AllowChange :=false;
      if vKoefDistShot.Visible and F_Kalc.Visible then
        vKoefDistShot.SetFocus;
    end;
  end;
end;


procedure TF_Kalc.actAddCableCanalExecute(Sender: TObject);
var
  FCountCC,Count: integer;
  Ost: integer;
  i, z : integer;
  NewCount: Integer;
begin
   FCountCC := 0;
   if Kalc_DM.CableCanalMemTable.RecordCount > 0 then
   begin
     Kalc_DM.CableCanalMemTable.Last;
     FCountCC := Kalc_DM.CableCanalMemTable.FieldbyName('Npp').AsInteger +1;
   end;


  with Kalc_DM.CableCanalMemTable  do
  begin
    Open;
    Ost := GetFreePercent(RecordCount);
    if Ost < 0 then
      Ost := 0;
    Append;
 //  FieldByName('Npp').AsInteger := FCountCC;
    if FCountCC = 0 then
      FieldByName('Name').AsString := cKalc_Msg12
    else
      FieldByName('Name').AsString := cKalc_Msg12 + ' ' + IntToStr(FCountCC);
    FieldByName('Price').AsFloat := 0;
    FieldByName('Percent').AsFloat := Ost;
    Post;
  end;
  AddCCElements;
end;

procedure TF_Kalc.actDelCableCanalExecute(Sender: TObject);
var
  npp: integer;
begin
  SetFocusToControl(CableCanalGrid);
  npp := Kalc_DM.CableCanalMemTable.FieldByName('Npp').AsInteger;
  Kalc_DM.ElemForCabcanal_MemTable.First;
  While not Kalc_DM.ElemForCabcanal_MemTable.Eof do
  begin
    if Kalc_DM.ElemForCabcanal_MemTable.FieldByName('Npp_CC').AsInteger = npp then Kalc_DM.ElemForCabcanal_MemTable.Delete
    else Kalc_DM.ElemForCabcanal_MemTable.Next;  end;Kalc_DM.CableCanalMemTable.Delete; end;
procedure TF_Kalc.CableCanalGrid_TableView1EditValueChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
begin
 // Kalc_DM.CableCanalMemTable.Refresh;
  if GetFreePercent(Kalc_DM.CableCanalMemTable.RecordCount)< 0 then
  begin
    StaticText4.Show;
  end
  else
  begin
    StaticText4.Hide;
  end;
end;

procedure TF_Kalc.CableCanalMemTableAfterDelete(DataSet: TDataSet);
begin
if GetFreePercent(Kalc_DM.CableCanalMemTable.RecordCount)< 0 then
  begin
    StaticText4.Show;
  end
  else
  begin
    StaticText4.Hide;
  end;
end;

procedure TF_Kalc.btCalcClick(Sender: TObject);
begin
  CalculateProject;
end;

function TF_Kalc.CalculateProject: double;
var
  i: integer;
  Nodecells: string;
  Node: TFlyNode;
  CostRM: double;
  KolRM, KolPort, KolPortForRM: integer;
  KRezervCable, DistShot, DistLong, RezervCableEnd, KoefShot, KoefLong: double;
  KolCableInPark, {KolCableForMagistral, }KolCableForRm, KolReservCable: integer;
  KolPortForMCable, LengthMagCable : double;
  KableShtuk, KableShtukForFlor, KolCable : integer;
  CableShtukList: TIntList;
  KolPP, KolPPforPort: integer;
  PointedMCable, PointedRaspredCable: boolean;
  KolOrg: integer;
  KolPKForPort, KolPKForRM, TotalKolPK: integer;
  Kolvo, id_Shelf, TotalKolShelf: integer;
  KolEq: integer;
  CostProject: double;
  NameOfElementCC: String;
  KoefWorks: double;
  ///расчёт кабеля
  SredLengthCable: double;
  KolWorkCable, KolWorkConduit: double;
  function GetSredLength(ADistShot, ADistLong, AKoefShot, AKoefLong: double): double;
  var
    koefForSred, SredDist: double;
  begin
    //коэфициенты подлаются в целом виде
    koefForSred := 0;    SredDist := 0;
    if AKoefShot + AKoefLong < 100 then
    begin
      koefForSred := 100 - AKoefShot - AKoefLong;
      SredDist := (ADistShot + ADistLong)/2;
    end;
    Result := (ADistShot*AKoefShot + ADistLong*AKoefLong + koefForSred*SredDist)/100
  end;

  function LengthMCable(AList: TIntList): double;
  var
    HeigthFloor: double;
    TotalLenght: double;
    TotalKolCable: integer;
    i: integer;
  begin
    Result := 0;
    HeigthFloor := vHeighFloor.Value;
    TotalLenght := 0;
    for i := 0 to Alist.Count-1 do
    begin
       TotalLenght := TotalLenght + abs(ServerFloor - i - 1) * HeigthFloor * Alist[i];
    end;
    Result := TotalLenght;
  end;

  Function PointOnceShelf: boolean;
  var
    Flag : boolean;
  begin
    Result := True;
    Flag := False;
    with Kalc_DM.ShelfForFloor_MemTable do
    begin
      if RecordCount > 0 then
      begin
        First;
        while Not Eof do
        begin
          if not FieldByName('id_shelf').IsNull then
          begin
            if flag then
            begin
              Result := false;
              Break;
            end
            else
              Flag := True;
          end
          else
            Next;
        end;
      end;

    end;
  end;

begin
  Result := 0;
  KoefForWorks := GetKoefForWorks;

  CableShtukList := TIntList.Create;
  try
    //Подсчет стоимости РМ
    Kalc_DM.AllComponent_MemTable.Active := False;
    Kalc_DM.AllComponent_MemTable.Active := True;
    CostRM := vCRM.Value;
    KolEq := 1;
    KolRM := trunc(vTotalKolRM.Value);
    //работы по монтажу рм
    PutToReportWork(idwRM, KolRm,KoefForWorks);
    If ECostRMGrid_Check.Checked and (Kalc_DM.CostRM_MemTable.RecordCount > 0)   then
    begin
      with Kalc_DM.CostRM_MemTable do
      begin
        First;
        while not eof do
        begin
          if FieldByName('Kolvo').AsString = '' then
            KolEq := 1
          else
            KolEq := FieldByName('Kolvo').AsInteger;
          if kolEq < 1 then
            KolEq := 1;
          KolEq :=  trunc(KolEq * KolRM);
          AddRecordInReport( FieldByName('Name').AsString,
                             FieldByName('Articul').AsString,
                             KolEq,
                             FieldByName('Price').AsFloat,
                             KolRM * FieldByName('Price').AsFloat);
          Next;
          KolEq := 1;
        end;
      end;
    end
    else
    begin
      AddRecordInReport( cKalc_Msg93, '', KolRM, CostRM, KolRM * CostRM);
    end;
    //Подсчёт стоимости кабеля
    KolPort := trunc(vTotalKolPort.Value);
    KolPortForRM := trunc(vKolPortForRM.Value);
    KolPortForMCable := vKolPortForMCable.Value;
    DistShot := vDistShot.Value;
    DistLong := vDistLong.Value;
    KRezervCable := 1 + trunc(vKCableRezerv.Value)/100;
    RezervCableEnd := vCableEndRezerv.Value;
    KolCableInPark := trunc(vKolCableInPark.Value);
    //кабель для РМ
    KoefShot := vKoefDistShot.Value;
    KoefLong := vKoefDistLong.Value;
    SredLengthCable := GetSredLength(DistShot, DistLong, KoefShot, KoefLong);
    KolCableForRm :=trunc(ceil(KolPort / trunc(KolCableInPark / (SredLengthCable * KRezervCable + RezervCableEnd))) * KolCableInPark);
    //Кабель для магистралей
    LengthMagCable := 0;
    KolReservCable := trunc(vKolReservCable.Value);
    Kalc_DM.ShelfForFloor_MemTable.First;
    for i := 0 to vKolRMForFloor.Items.Count - 1 do
    begin
      if vKolRMForFloor.Items[i].Cells[1] <> ''then
        KableShtukForFlor := ceil( StrToFloat(vKolRMForFloor.Items[i].Cells[1])*KolPortForRM/KolPortForMCable)
      else
        KableShtukForFlor := 0;
      if KableShtukForFlor > 0 then
      begin
        if not(OnceShelfCheck.Checked and OnceShelfCheck.Enabled) then
        begin
          if Kalc_DM.ShelfForFloor_MemTable.FieldByName('id_shelf').IsNull then
          begin
             MessageModal(cKalc_Msg13 +' ' + IntToStr(i + 1) +  ' ' + cKalc_Msg14, cKalc_Msg15, MB_ICONINFORMATION) ;
             KableShtukForFlor := 0;
          end
          else
            KableShtukForFlor := KableShtukForFlor + KolReservCable;
        end
        else
         KableShtukForFlor := KableShtukForFlor + KolReservCable;
      end;
      if not Kalc_DM.ShelfForFloor_MemTable.Eof then
        Kalc_DM.ShelfForFloor_MemTable.Next;
      CableShtukList.Add(KableShtukForFlor);
    end;
   
    //если всё работает не с одной серверной
    if ((not OnceShelfCheck.Checked) or (Not OnceShelfCheck.Enabled)) and (vKolFloor.Value > 1) then
    begin
      //находим общую длину магистрального  кабеля
      LengthMagCable :=  LengthMCable(CableShtukList);
      PointedMCable := False;
      with Kalc_DM.Cable_MemTable do
      begin
        First;
        for i := 0 to RecordCount - 1 do
        begin
          if FieldByName('Id_Missing').AsInteger = tcuMagistral then
          begin
            PointedMCable := true;
            break;
          end;
          Next;
        end;
        if not PointedMCable then
        begin
          KolCableForRm := ceil(LengthMagCable + KolCableForRm);
     
        end;
        PointedRaspredCable := false;
        First;
        while Not Eof do
        begin
          if FieldByName('Id_Missing').AsInteger = tcuMagistral then
          begin
            KolCable := round(LengthMagCable * fieldByname('Percent').AsFloat / 100);
          end
          else
          begin
            PointedRaspredCable := true;
            KolCable := round(ceil(KolCableForRm * fieldByname('Percent').AsFloat /100/KolCableInPark)* KolCableInPark);
          end;
          AddRecordInReport( FieldByName('Name').AsString,
                             FieldByName('Articul').AsString,
                             KolCable,
                             FieldByName('Price').AsFloat,
                             KolCable * FieldByName('Price').AsFloat);
          Next;
        end;
      end;
    end
    else
    begin
      PointedRaspredCable := false;
      with Kalc_DM.Cable_MemTable do
      begin
        First;
        while Not Eof do
        begin
          if FieldByName('Id_Missing').AsInteger = tcuRaspred then
          begin
            PointedRaspredCable := true;
            KolCable := round(ceil(KolCableForRm * fieldByname('Percent').AsFloat / 100/KolCableInPark)* KolCableInPark);
            AddRecordInReport( FieldByName('Name').AsString,FieldByName('Articul').AsString,
                             KolCable, FieldByName('Price').AsFloat,  KolCable * FieldByName('Price').AsFloat);
         end;
        Next;
        end;
      end;
    end;
    if not PointedRaspredCable then
      MessageModal(cKalc_Msg87, cKalc_Msg15, MB_ICONINFORMATION);
      //заносим значение сумы всехч кабелей в переменную формы
    TotalKolCable := round(LengthMagCable + KolPort * SredLengthCable);
    //работы по прокладке кабеля
    PutToReportWork(idwCable, TotalKolCable, KoefForWorks);
    //количество патч панелей для проекта
     Case TypeConnectEuipment_RadioGroup.ItemIndex of
        0 : KolPPforPort := 2;
        1 : KolPPforPort := 1;
        2 : KolPPforPort := 3;
      end;
    if (OnceShelfCheck.Checked and OnceShelfCheck.Enabled) or PointOnceShelf then
    begin     //для всего проекта
      KolPP := trunc(ceil(trunc(vTotalKolPort.Value) / trunc(vKolPortPP.Value)) * KolPPforPort);
    end
    else
    begin
      KolPP := 0;              //определяем ПП для этажей
      for i := 0 to vKolRMForFloor.Items.Count - 1 do
      begin
        KolPP := KolPP + ceil(StrToInt(vKolRMForFloor.Items[i].Cells[1]) / trunc(vKolPortPP.Value)) * KolPPforPort;
      end;
      //определим количество ПП для магистарльных ПП
      KableShtuk := 0;
      For i := 0 to CableShtukList.Count - 1 do
      begin
        KableShtuk := KableShtuk + CableShtukList[i];
      end;
      KolPP := KolPP + ceil(KableShtuk / vKolPortPP.Value);

    end;
    if ECostPPGrid_Check.Checked and (Kalc_DM.CostPP_MemTable.RecordCount > 0) then
    begin
      with Kalc_DM.CostPP_MemTable do
      begin
        First;
        AddRecordInReport( FieldByName('Name').AsString,
                           FieldByName('Articul').AsString,
                           KolPP,
                           FieldByName('Price').AsFloat,
                           KolPP * FieldByName('Price').AsFloat);
      end;
    end
    else
    begin
      AddRecordInReport(cKalc_Msg16, '', KolPP, vCPP.Value, KolPP * vCPP.Value);
    end;
    //работы по установке патч-панелей
    PutToReportWork(idwPP, KolPP, KoefForWorks);
    //количество организаторов для проекта
    KolOrg := KolPP;
    if ECostOrgGrid_Check.Checked and (Kalc_DM.CostOrg_MemTable.RecordCount > 0) then
    begin
      with Kalc_DM.CostOrg_MemTable do
      begin
        First;
        AddRecordInReport( FieldByName('Name').AsString,
                           FieldByName('Articul').AsString,
                           KolOrg,
                           FieldByName('Price').AsFloat,
                           KolOrg * FieldByName('Price').AsFloat);
      end;
    end
    else
    begin
      AddRecordInReport(cKalc_Msg17, '', KolOrg, vCOrg.Value, KolOrg * vCOrg.Value);
    end;
    //работы по установке организаторов
    PutToReportWork(idwOrg, KolOrg, KoefForWorks);
    //Количество патчкордов для проекта
    Case TypeConnectEuipment_RadioGroup.ItemIndex of
        0 : KolPKforPort := 1;
        1 : KolPKforPort := 1;
        2 : KolPKforPort := 1;
      end;
    TotalKolPK := trunc(KolPP / KolPPforPort * vKolPortPP.Value);
    if eKalcPKForRM_Check.Checked  then
    begin
      KolPKForRM := trunc(vKolPKForRM.Value);
      TotalKolPK := TotalKolPK + trunc(KolRM * KolPKForRM);
    end;
    if ECostPKGridCheck.Checked and (Kalc_DM.CostPK_MemTable.RecordCount > 0) then
    begin
      with Kalc_DM.CostPK_MemTable  do
      begin
        First;
        AddRecordInReport( FieldByName('Name').AsString,
                           FieldByName('Articul').AsString,
                           TotalKolPK,
                           FieldByName('Price').AsFloat,
                           TotalKolPK * FieldByName('Price').AsFloat);
      end;
    end
    else
    begin
      AddRecordInReport(cKalc_Msg18, '', TotalKolPK, vCPK.Value, TotalKolPK * vCPK.Value);
    end;
    //Количество шкафов по проекту
    TotalKolShelf := 0;
    if not ECostShelfGridCheck.Checked or (Kalc_DM.CostShelf_MemTable.RecordCount < 1) then
    begin
      if OnceShelfCheck.Checked and OnceShelfCheck.Enabled then
      begin
        AddRecordInReport(cKalc_Msg19, '', 1, vCm_Shelf.Value, vCm_Shelf.Value);
        TotalKolShelf := 1;
      end
      else
      begin
        AddRecordInReport(cKalc_Msg19, '', trunc(vKolFloor.Value), vCm_Shelf.Value, vCm_Shelf.Value * trunc(vKolFloor.Value));
        TotalKolShelf := trunc(vKolFloor.Value);
      end;
    end
    else
      if Kalc_DM.CostShelf_MemTable.RecordCount > 0 then
      begin
        with Kalc_DM.CostShelf_MemTable do
        begin
          First;
          while Not Eof do
          begin
            id_Shelf := FieldByName('id').asInteger;
            Kolvo := 0;
            begin
              Kalc_DM.ShelfForFloor_MemTable.First;
              while Not Kalc_DM.ShelfForFloor_MemTable.Eof do
              begin
                if (Not Kalc_DM.ShelfForFloor_MemTable.FieldByName('id_shelf').IsNull)
                    and (Kalc_DM.ShelfForFloor_MemTable.FieldByName('id_shelf').AsInteger = id_Shelf)
                then
                begin
                  inc(kolvo);
                end;
                Kalc_DM.ShelfForFloor_MemTable.Next;
              end;
            end;
            if kolvo > 0 then
            begin
               TotalKolShelf := TotalKolShelf + Kolvo;
              AddRecordInReport(FieldByName('Name').AsString,
                              FieldByName('Articul').AsString,
                              Kolvo,
                              FieldByName('Price').AsFloat,
                              Kolvo * FieldByName('Price').AsFloat);
            end;
            Next;
          end;
        end;
      end;
    //Работы по монтажу шкафов
    PutToReportWork(idwShelf, TotalKolShelf, KoefForWorks);
    // Количество дополнительного оборудования
    If EDopEqGrid_Check.Checked and (Kalc_DM.DopEq_MemTable.RecordCount > 0) then
    begin
      with Kalc_DM.DopEq_MemTable do
      begin
        First;
        while not Eof do
        begin
          if FieldByName('Kolvo').AsString = '' then
            KolEq := 1
          else
            KolEq := FieldByName('Kolvo').AsInteger;
          if kolEq < 1 then
            KolEq := 1;

          AddRecordInReport( FieldByName('Name').AsString,
                             FieldByName('Articul').AsString,
                             KolEq,
                             FieldByName('Price').AsFloat,
                             KolEq * FieldByName('Price').AsFloat);
            Next;
        end;
      end;
     end
     else
     begin
       AddRecordInReport(cKalc_Msg20, '', 1, vCostDopEq.Value, vCostDopEq.Value);
     end;

    //Количество кабельных каналов
    //if FixCableWey_ComboBox.ItemIndex = 3 then
//    begin
//      with Kalc_DM.CableCanalMemTable do
//      begin
//        First;
//        while Not Eof do
//          actDelCableCanalExecute(Self);
//      end;
//    end;
     CalculateCC;
    //Подсчёт стоимости всего проекта
    CostProject := 0;
    with Kalc_DM.AllComponent_MemTable do
    begin
      First;
      while Not Eof do
      begin
        KolEq := FieldByName('Kolvo').AsInteger;
        CostProject := CostProject + KolEq * FieldByName('price').AsFloat;
        Next;
      end;
    end;
    Result := CostProject;
    //добавим остальные работы
    PutToReportWork(idwCrossPort,KolPort, KoefForWorks); //'Кроссировка (1 порт)';
    PutToReportWork(idwTestPort,KolPort, KoefForWorks); //'Тестирование соединений (1 порт)';
    PutToReportWork(idwProectPort, KolPort, KoefForWorks); //'Проектные работы  (1 порт)';
    PutToReportWork(idwTransport, 1, KoefForWorks); //'Транспортные расходы';
    PutToReportWork(idwAnother,1, KoefForWorks); //'Другие пусконаладочные работы';
    ///idwKoef = 12; //'Коэфициент  на работы (согласно особому характеру работ)';
    /////////////////////////////
    PutHaracterProjectInMt;
  finally
    CableShtukList.Free;
  end;
end;

procedure TF_Kalc.AddRecordInReport(AName: string; AArticul: String; AKol: integer;
          APrice, ACost: double; AidTypePoz: string = idTypePozMaterial);
begin
  with Kalc_DM.AllComponent_MemTable do
  begin
    Open;
    Append;
    FieldByName('Name').AsString := AName;
    FieldByName('Articul').AsString := AArticul;
    FieldByName('Kolvo').AsInteger := AKol;
    FieldByName('Price').AsFloat := APrice;
    FieldByName('Cost').AsFloat := ACost;
    FieldByName('TypePoz').AsString := AidTypePoz;
    post;
  end;
end;

procedure TF_Kalc.actAddCableExecute(Sender: TObject);
var
  Count: integer;
  Ost: integer;
  i, z : integer;
begin
  with Kalc_DM.Cable_MemTable  do
  begin
    Open;
    Append;
    FieldByName('Name').AsString := cKalc_Msg21 + IntToStr(Kalc_DM.Cable_MemTable.RecordCount + 1);
    FieldByName('Price').AsFloat := 0;
    FieldByName('Percent').AsInteger := 100;
    FieldByName('Id_Missing').AsInteger := tcuRaspred;
    Post;
  end;
  Ost := GetFreePercentForCable;
  if Ost > 0 then
    StaticText5.Show
  else
    StaticText5.Hide;
end;

procedure TF_Kalc.actDelCableExecute(Sender: TObject);
begin
  Kalc_DM.Cable_MemTable.Delete;
  if GetFreePercentForCable > 0 then
    StaticText5.Show
  else
    StaticText5.Hide;
end;

procedure TF_Kalc.CableCanalGrid_TableView1KeyDown(Sender: TObject;
  var Key: Word; Shift: TShiftState);
begin
   if key = 45 then //Insert
  begin
    actAddCableCanalExecute(Sender);
  end;
  if key = 46 then
  begin
    actDelCableCanalExecute(Sender);
  end;
end;

procedure TF_Kalc.Cable_Grid_DBTableViewKeyDown(Sender: TObject;
  var Key: Word; Shift: TShiftState);
begin
   if key = 45 then //Insert
  begin
    actAddCableExecute(Sender);
  end;
  if key = 46 then
  begin
    actDelCableExecute(Sender);
  end;
end;

procedure TF_Kalc.CostRMGridKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if key = 45 then //Insert
  begin
    actAddRecordExecute(Sender);
  end;
  if key = 46 then
  begin
    actDelRecordExecute(Sender);
  end;
end;

procedure TF_Kalc.FixBtnClick(Sender: TObject);
var
  ID, id_Shelf: integer;
  Price: double;
begin
  id_Shelf := Kalc_DM.CostShelf_MemTable.FieldbyName('id').AsInteger;
  Price := Kalc_DM.CostShelf_MemTable.FieldbyName('price').AsFloat;
  if FixAllEcxeptSelCheck.Checked then
  begin
    with Kalc_DM.ShelfForFloor_MemTable do
    begin
      id := FieldbyName('id').AsInteger;
      First;
      while Not Eof do
      begin
        if id <> FieldbyName('id').AsInteger then
        begin
          Edit;
          FieldbyName('id_shelf').AsInteger := id_Shelf;
          FieldbyName('price').AsFloat :=  Price;
          Post;
        end;
        Next;
      end;
      First;
      MoveBy(ID);
    end;
    FixAllEcxeptSelCheck.Checked := false;
  end
  else
  begin
    with Kalc_DM.ShelfForFloor_MemTable do
    begin
      Edit;
      FieldbyName('Id_Shelf').AsInteger := id_Shelf;
      FieldbyName('price').AsFloat :=  Price;
      Post;
    end;
  end;
 ShelfForFloor_Grid.Refresh;
end;

procedure TF_Kalc.Clear_BtnClick(Sender: TObject);

begin
  with Kalc_DM.ShelfForFloor_MemTable do
    begin
      First;
      while Not Eof do
      begin
        Edit;
        FieldbyName('id_shelf').Clear;
        FieldbyName('price').Clear;
        Post;
        Next;
      end;
    end;
end;

procedure TF_Kalc.EDopEqGrid_CheckClick(Sender: TObject);
begin
  if EDopEqGrid_Check.Checked then
  begin
    DopEq_Grid.Enabled := true;
    vCostDopEq.Value := 0;
    if Kalc_DM.DopEq_MemTable.RecordCount > 0 then
      ValCostFromGrid(vCostDopEq, Kalc_DM.DopEq_MemTable);
  end
  else
    DopEq_Grid.Enabled := false;

  EnableTableView(DopEq_TableView, EDopEqGrid_Check.Checked);
end;

procedure TF_Kalc.DopEq_TableViewEditValueChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
begin
  ValCostFromGrid(vCostDopEq, Kalc_DM.DopEq_MemTable);
end;

procedure TF_Kalc.CostPP_GridDBTableViewEditValueChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
begin
  ValCostFromGrid(vCPP, Kalc_DM.CostPP_MemTable);
end;

procedure TF_Kalc.GT_CostOrgEditValueChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
begin
  ValCostFromGrid(vCOrg, Kalc_DM.CostOrg_MemTable);
end;

procedure TF_Kalc.Cable_Grid_DBTableViewEditValueChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
begin
 
  if GetFreePercentForCable > 0 then
    StaticText5.Show
  else
    StaticText5.Hide;
end;

procedure TF_Kalc.vKKolDopMestChange(Sender: TObject);
begin
   vTotalKolRM.Value := vKolRM.Value + trunc(vKolRM.Value * vKKolDopMest.Value/100);
end;

procedure TF_Kalc.FixCableWey_ComboBoxCloseUp(Sender: TObject);
begin
  case FixCableWey_ComboBox.ItemIndex of
    0: TypeWeyCC_PageControl.ActivePageIndex := 0;
    1: TypeWeyCC_PageControl.ActivePageIndex := 1;
    2: TypeWeyCC_PageControl.ActivePageIndex := 2;
    3: TypeWeyCC_PageControl.ActivePageIndex := 3;
  end;
end;

procedure TF_Kalc.FormulaFloor_GroupChanging(Sender: TObject;
  NewIndex: Integer; var AllowChange: Boolean);
begin
  Case NewIndex of
    0:begin
        FormulaFloor2_Panel.Enabled := False;
        FormulaFloor1_Panel.Enabled := true;
      end;
    1:begin
        FormulaFloor1_Panel.Enabled := False;
        FormulaFloor2_Panel.Enabled := true;
      end;
  end;

end;

procedure TF_Kalc.FormulaUnderCail_RadioGroupChanging(Sender: TObject;
  NewIndex: Integer; var AllowChange: Boolean);
begin
  Case NewIndex of
    0:begin
        FormulaUnderCail2_Panel.Enabled := False;
        FormulaUnderCail1_Panel.Enabled := true;
      end;
    1:begin
        FormulaUnderCail1_Panel.Enabled := False;
        FormulaUnderCail2_Panel.Enabled := true;
      end;
  end;
end;

procedure TF_Kalc.FormulaDekorCC_RadioGroupChanging(Sender: TObject;
  NewIndex: Integer; var AllowChange: Boolean);
begin
  Case NewIndex of
    0:begin
        FormulaDekorCC2_Panel.Enabled := False;
        FormulaDekorCC1_Panel.Enabled := true;
      end;
    1:begin
        FormulaDekorCC1_Panel.Enabled := False;
        FormulaDekorCC2_Panel.Enabled := true;
      end;
  end;
end;

procedure TF_Kalc.FormulaInCC_GroupChanging(Sender: TObject;
  NewIndex: Integer; var AllowChange: Boolean);
begin
  Case NewIndex of
    0:begin
        FormulaInCC2_Panel.Enabled := False;
        FormulaInCC3_Panel.Enabled := False;
        FormulaInCC1_Panel.Enabled := true;
      end;
    1:begin
        FormulaInCC1_Panel.Enabled := False;
        FormulaInCC3_Panel.Enabled := False;
        FormulaInCC2_Panel.Enabled := true;
      end;
    2:begin
        FormulaInCC1_Panel.Enabled := False;
        FormulaInCC2_Panel.Enabled := False;
        FormulaInCC3_Panel.Enabled := true;
      end;                     
  end;
end;

procedure TF_Kalc.ServFloor_ComboBoxPropertiesChange(Sender: TObject);
begin
  ServerFloor := ServFloor_ComboBox.EditValue;
end;

procedure TF_Kalc.CalculateCC;
var
  PerTehreservCC, KolCC, KolCCForRm: double;
  CCLength: integer;
  KolElemCC: integer;
  KoefWorks: double;
  KolDopCC: integer;
  procedure KalcElemOfCC(ACCLength: integer) ;
  var
    NameOfElementCC: string;
  begin
    while Not Kalc_DM.ElemForCabcanal_MemTable.Eof do
        begin
          KolElemCC := Ceil(ACCLength / 100 * Kalc_DM.ElemForCabcanal_MemTable.fieldByName('rashod').AsFloat);
          Kalc_DM.TypeOfElementCC_MemTable.First;
          Kalc_DM.TypeOfElementCC_MemTable.MoveBy(Kalc_DM.ElemForCabcanal_MemTable.FieldByName('id_type').AsInteger - 1);
          NameOfElementCC := Kalc_DM.TypeOfElementCC_MemTable.FieldByName('name').AsString + ' (' + Kalc_DM.CableCanalMemTable.FieldByName('Name').AsString + ')';
          AddRecordInReport(NameOfElementCC,
                            Kalc_DM.ElemForCabcanal_MemTable.FieldByName('Articul').AsString,
                            KolElemCC,
                            Kalc_DM.ElemForCabcanal_MemTable.FieldByName('price').AsFloat,
                            KolElemCC * Kalc_DM.ElemForCabcanal_MemTable.FieldByName('price').AsFloat);
          Kalc_DM.ElemForCabcanal_MemTable.Next;
        end;
  end;

  function CalcCCFloor: integer;
  var
    KolCCForFloor, Kolvo : integer;
    KolRM: integer;

    Function Metod1: integer;
    var
      LenghtRoom, WidthRoom, x, y: double;
      KolRooms: integer;
      KolRM: integer;
    begin
      Result := 0;
      KolRooms := trunc(vKolRooms.Value);
      LenghtRoom := vLengthRoom.Value;
      WidthRoom := vWidthRoom.Value;
      x := vFormulaFloor1_X.Value;
      y := vFormulaFloor1_Y.Value;
      Result := Ceil((LenghtRoom * x + WidthRoom * y) * KolRooms);
    end;

    Function Metod2: integer;
    var
      x: double;
      KolRooms: integer;
    begin
      Result := 0;
      x := vFormulaFloor2_X.Value;
      KolRooms := trunc(vKolRooms.Value);
      Result := Ceil(KolRooms * x );
    end;

  begin
    if Kalc_DM.CCFloor_MemTable.RecordCount > 0 then
    begin
      Case FormulaFloor_Group.ItemIndex of
        0: KolCCForFloor := Metod1;
        1: KolCCForFloor := Metod2;
      end;
      KolDopCC := KolCCForFloor;
      with Kalc_DM.CCFloor_MemTable do
      begin
        First;
        while Not Eof do
        begin
          Kolvo := ceil(KolCCForFloor * FieldByName('Percent').AsFloat / 100);
          AddRecordInReport( FieldByName('Name').AsString,
                           FieldByName('Articul').AsString,
                           Kolvo,
                           FieldByName('Price').AsFloat,
                           Kolvo * FieldByName('Price').AsFloat);
          Next;
        end;
      end;
      KolRM := trunc(vTotalKolRM.Value);
      Result := trunc(KolRM * vHeigthRM.Value);
    end;
  end;

  function CalcUndeCeil: integer;
  var
    Kolvo: integer;
    KolCCUnderCeil: integer;

    function Metod1ForUnderCeilCC: integer;
    var
      LenghtRoom, WidthRoom, x, y: double;
      KolRooms: integer;
      KolRM: integer;
    begin
      Result := 0;
      KolRooms := trunc(vKolRooms.Value);
      LenghtRoom := vLengthRoom.Value;
      WidthRoom := vWidthRoom.Value;
      x := vFormulaUnderCeil1_X.Value;
      y := vFormulaUnderCeil1_Y.Value;
      Result := Ceil(LenghtRoom * x + WidthRoom * y);
    end;

    Function Metod2ForUnderCeilCC: integer;
    var
      x: double;
      KolRooms: integer;
    begin
      Result := 0;
      x := vFormulaUnderCeil2_X.Value;
      KolRooms := trunc(vKolRooms.Value);
      Result := Ceil(KolRooms * x );
    end;

    Function Metod1ForDekorCC: integer;
    var
      KolRm: integer;
      HeigthFalseCeil, HeigthRM: Double;
    begin
      Result := 0;
      KolRm := trunc(vTotalKolRM.Value);
      HeigthFalseCeil := vHeigthFalseCeil.Value;
      HeigthRM := vHeigthRM.Value;
      Result := ceil(KolRm * (HeigthFalseCeil - HeigthRM));
    end;

    Function Metod2ForDekorCC: integer;
    var
      KolRooms: integer;
      LengthRoom, HeigthFalseCeil, HeigthRM: Double;
      x: double;
    begin
      Result := 0;
      x := vFormulaDekorCC2_X.Value;
      KolRooms := trunc(vKolRooms.Value);
      HeigthFalseCeil := vHeigthFalseCeil.Value;
      HeigthRM := vHeigthRM.Value;
      LengthRoom := vLengthRoom.Value;
      Result := ceil(KolRooms * (LengthRoom +  HeigthFalseCeil - HeigthRM));
    end;
  begin
    case FormulaUnderCail_RadioGroup.ItemIndex of
      0: KolCCUnderCeil := Metod1ForUnderCeilCC;
      1: KolCCUnderCeil := Metod2ForUnderCeilCC;
    end;
    case FormulaDekorCC_RadioGroup.ItemIndex of
      0: Result := Metod1ForDekorCC;
      1: Result := Metod2ForDekorCC;
    end;
    KolDopCC := KolCCUnderCeil;
    with Kalc_DM.CCUnderCeil_MemTable do
    begin
      First;
      while Not Eof do
      begin
        Kolvo := ceil(KolCCUnderCeil * FieldByName('Percent').AsFloat / 100);
        AddRecordInReport( FieldByName('Name').AsString,
                         FieldByName('Articul').AsString,
                         Kolvo,
                         FieldByName('Price').AsFloat,
                         Kolvo * FieldByName('Price').AsFloat);
        Next;
      end;
    end;
  end;
/////////////////////////////////////
  function CalcInCC: integer;
    function Metod1: integer;
     var
      x: double;
      KolRM: integer;
    begin
      Result := 0;
      x := vFormulaInCC1_X.Value;
      KolRM := trunc(vTotalKolRM.Value);
      Result := Ceil(KolRM * x );
    end;

    function Metod2: integer;
    var
      x: double;
      KolRooms: integer;
    begin
      Result := 0;
      x := vFormulaInCC2_X.Value;
      KolRooms := trunc(vKolRooms.Value);
      Result := Ceil(KolRooms * x);
    end;

    function Metod3: integer;
    var
      HeigthFalseCeil, HeigthRM: Double;
      LenghtRoom, WidthRoom, x, y: double;
      KolRooms: integer;
      KolRM: integer;
    begin
      Result := 0;
      HeigthFalseCeil := vHeigthFalseCeil.Value;
      HeigthRM := vHeigthRM.Value;
      KolRooms := trunc(vKolRooms.Value);
      LenghtRoom := vLengthRoom.Value;
      WidthRoom := vWidthRoom.Value;
      x := vFormulaInCC3_X.Value;
      y := vFormulaInCC3_Y.Value;
      Result := Ceil(LenghtRoom * y + WidthRoom * x + KolRm * (HeigthFalseCeil - HeigthRM));
    end;
  begin
    result := 0;
    Case FormulaInCC_Group.ItemIndex of
      0: Result := Metod1;
      1: Result := Metod2;
      2: Result := Metod3;
    end;
  end;
//////////////////////////////////////////////////
  function CalcOpenWir: integer;
   var
    KolPoint, kolvo: integer;

    function Metod1: integer;
    var
      Rashod,KolCableInBeam: double;

    begin
      Result := 0;
      Rashod := vMetodOpenWir1_Rashod.Value;
      //KolCableInBeam := vMetodOpenWir1_KolInBeam.Value;
      Result := ceil(TotalKolCable *  KolCableInBeam);
    end;
  begin
    result := 0;
    case OpenWir_RadioGroup.ItemIndex of
      0: KolPoint := Metod1;
    end;
    with Kalc_DM.ElPointFix_MemTable do
    begin
      First;
      while Not Eof do
      begin
        Kolvo := ceil(KolPoint * FieldByName('Percent').AsFloat / 100);
        AddRecordInReport( FieldByName('Name').AsString,
                         FieldByName('Articul').AsString,
                         KolPoint,
                         FieldByName('Price').AsFloat,
                         KolPoint * FieldByName('Price').AsFloat);
        Next;
      end;
    end;
  end;       
//////////////////////////////////////////////////
begin
  KolDopCC := 0;
  PerTehreservCC := vKolTehreserv.Value / 100;
  case FixCableWey_ComboBox.ItemIndex of
    0: CCLength := CalcCCFloor;
    1: CCLength := CalcUndeCeil;
    2: CCLength := CalcInCC;
    3: CCLength := CalcOpenWir;
  end;
  KolCC := CCLength + ceil(CCLength * PerTehreservCC);
  // работы по прокладке кабельного канала
  if FixCableWey_ComboBox.ItemIndex <> 3 then
  begin
    KoefWorks := KoefForWorks;
    TotalKolCC := CCLength + KolDopCC;
    PutToReportWork(idwCC, TotalKolCC,Koefworks);
  end;
  if FixCableWey_ComboBox.ItemIndex <> 3 then
    with Kalc_DM.CableCanalMemTable do
    begin
      First;
      while not Eof do
      begin
        CCLength := (Ceil(KolCC * FieldByName('percent').AsFloat / 100));
        AddRecordInReport( FieldByName('Name').AsString,
                           FieldByName('Articul').AsString,
                           CCLength,
                           FieldByName('Price').AsFloat,
                           CCLength * FieldByName('Price').AsFloat);
        KalcElemOfCC(CCLength);
        Next;
      end;
    end;
end;

procedure TF_Kalc.vWidthRoomChange(Sender: TObject);
var
  val: double;
begin
   val := vWidthRoom.Value;
  if val = 0 then
    val := 1;
  vSKab_Edit.Value := Val * vLengthRoom.Value;
end;

procedure TF_Kalc.vLengthRoomChange(Sender: TObject);
var
  val: double;
begin
  val := vLengthRoom.Value;
  if val = 0 then
    val := 1;
  vSKab_Edit.Value := vWidthRoom.Value * Val;
end;

procedure TF_Kalc.PrintClick(Sender: TObject);
var
  CostOfProjectReportParams: TCostOfProjectReportParams;
begin
  {PutHaracterProjectInMt;
  CostOfProjectReportParams := getCostOfProjectReportParams;
  F_ProjMan.F_ResourceReport.ShowPriorCostOfProjectReportWizard(Kalc_DM.AllComponent_MemTable, Kalc_DM.HaracterProject_MemTable,
    CostOfProjectReportParams, false);}
end;

procedure TF_Kalc.PutHaracterProjectInMT;
begin
    Kalc_DM.HaracterProject_MemTable.Active := False;
    Kalc_DM.HaracterProject_MemTable.Active := true;
    AddRecordInHaracterProject_MemTable(cKalc_Msg22, FloatToStr(vKolFloor.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg23 + GetNameUOM2(F_NormBase.FUOM), FloatToStr(vSTotalPlase.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg24, FloatToStr(vKSWorkPlase.Value)+ '%');
    AddRecordInHaracterProject_MemTable(cKalc_Msg25 + GetNameUOM2(F_NormBase.FUOM), FloatToStr(vKolFloor.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg26 + GetNameUOM(F_NormBase.FUOM, true), FloatToStr(vHeighFloor.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg27, FloatToStr(vKolRooms.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg28 + GetNameUOM(F_NormBase.FUOM, true), FloatToStr(vWidthRoom.Value) + ' x ' + FloatToStr(vLengthRoom.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg29 + GetNameUOM2(F_NormBase.FUOM), FloatToStr(vSKab_Edit.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg30 + GetNameUOM2(F_NormBase.FUOM), FloatToStr(vSForRM.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg31, FloatToStr(vKolRM.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg32, FloatToStr(vKKolDopMest.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg33, FloatToStr(vTotalKolRM.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg34, FloatToStr(vKolPortForRM.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg35, FloatToStr(vSKab_Edit.Value));
    if eKalcPKForRM_Check.Checked then
      AddRecordInHaracterProject_MemTable(cKalc_Msg36, FloatToStr(vKolPKForRM.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg37 + GetNameUOM(F_NormBase.FUOM, true), FloatToStr(vHeigthRM.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg38 + GetNameUOM(F_NormBase.FUOM, true), FloatToStr(vDistShot.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg39 + GetNameUOM(F_NormBase.FUOM, true), FloatToStr(vDistLong.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg91, FloatToStr(vKoefDistShot.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg92, FloatToStr(vKoefDistLong.Value));

    case TypeConnectEuipment_RadioGroup.ItemIndex of
      0: AddRecordInHaracterProject_MemTable(cKalc_Msg40, cKalc_Msg41);
      1: AddRecordInHaracterProject_MemTable(cKalc_Msg40, cKalc_Msg42);
      2: AddRecordInHaracterProject_MemTable(cKalc_Msg40, cKalc_Msg43);
    end;
    AddRecordInHaracterProject_MemTable(cKalc_Msg44, FloatToStr(vKolPortForRM.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg45, FloatToStr(vKolReservCable.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg46, IntToStr(ServerFloor));
    if OnceShelfCheck.Checked and (not ECostShelfGridCheck.Checked) then
       AddRecordInHaracterProject_MemTable(cKalc_Msg47, cKalc_Msg48);
    AddRecordInHaracterProject_MemTable(cKalc_Msg49 + GetNameUOM(F_NormBase.FUOM, true), FloatToStr(vKolCableInPark.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg50, FloatToStr(vKCableRezerv.Value) + '%');
    AddRecordInHaracterProject_MemTable(cKalc_Msg51 + GetNameUOM(F_NormBase.FUOM, true), FloatToStr(vCableEndRezerv.Value));
    AddRecordInHaracterProject_MemTable(cKalc_Msg52, FloatToStr(vKCableRezerv.Value) + '%');
    AddRecordInHaracterProject_MemTable(cKalc_Msg53, FixCableWey_ComboBox.Text);

    Case FixCableWey_ComboBox.ItemIndex of
      0:begin
          AddRecordInHaracterProject_MemTable(cKalc_Msg54,cKalc_Msg55);
          if Kalc_DM.CCFloor_MemTable.RecordCount > 0 then
            case FormulaFloor_Group.ItemIndex of
              0: AddRecordInHaracterProject_MemTable(cKalc_Msg56, cKalc_Msg57 + FloatToStr(vFormulaFloor1_X.Value) +
                                                       cKalc_Msg58 + FloatToStr(vFormulaFloor1_Y.Value) + cKalc_Msg59);
              1: AddRecordInHaracterProject_MemTable(cKalc_Msg56, cKalc_Msg60 + FloatToStr(vFormulaFloor2_X.Value) + cKalc_Msg61 + GetNameUOM(F_NormBase.FUOM, false));
            end;
        end;
      1:begin
          case FormulaDekorCC_RadioGroup.ItemIndex of
            0: AddRecordInHaracterProject_MemTable(cKalc_Msg54, cKalc_Msg62);
            1: AddRecordInHaracterProject_MemTable(cKalc_Msg54, cKalc_Msg63 + FloatToStr(vFormulaDekorCC2_X.Value) + cKalc_Msg64);
          end;
          if Kalc_DM.CCUnderCeil_MemTable.RecordCount > 0 then
            case FormulaUnderCail_RadioGroup.ItemIndex of
              0: AddRecordInHaracterProject_MemTable(cKalc_Msg65, cKalc_Msg66 + FloatToStr(vFormulaUnderCeil1_X.Value) +
                                                      cKalc_Msg67 + FloatToStr(vFormulaUnderCeil1_Y.Value) + cKalc_Msg68);
              1: AddRecordInHaracterProject_MemTable(cKalc_Msg65, cKalc_Msg69 + FloatToStr(vFormulaUnderCeil2_X.Value) + cKalc_Msg70 + GetNameUOM(F_NormBase.FUOM, false));
            end;
        end;
      2:begin
          case FormulaInCC_Group.ItemIndex of
            0: AddRecordInHaracterProject_MemTable(cKalc_Msg71, cKalc_Msg72);
            1: AddRecordInHaracterProject_MemTable(cKalc_Msg54, cKalc_Msg73 + FloatToStr(vFormulaInCC2_X.Value) + cKalc_Msg70);
            2: AddRecordInHaracterProject_MemTable(cKalc_Msg54, cKalc_Msg74 + FloatToStr(vFormulaInCC3_X.Value)
                                                    +  cKalc_Msg75 + FloatToStr(vFormulaInCC3_Y.Value) + ')' + #10#13 + cKalc_Msg76);
          end;
        end;
      3:begin
          case OpenWir_RadioGroup.ItemIndex of
            0: AddRecordInHaracterProject_MemTable(cKalc_Msg77, cKalc_Msg78 + cKalc_Msg79 + FloatToStr(vMetodOpenWir1_Rashod.Value) +')');
          end;
        end;
    end;
    if FixCableWey_ComboBox.ItemIndex <> 3 then
       AddRecordInHaracterProject_MemTable(cKalc_Msg90 + GetNameUOM(F_NormBase.FUOM, true), IntToStr(TotalKolCC));
    AddRecordInHaracterProject_MemTable(cKalc_Msg89+ GetNameUOM(F_NormBase.FUOM, true), IntToStr(TotalKolCable));
end;

procedure TF_Kalc.AddRecordInHaracterProject_MemTable(AName, AZnach: string);
begin
  with Kalc_DM.HaracterProject_MemTable do
  begin
    Append;
    FieldByName('Name').AsString := AName;
    FieldByName('Znach').AsString := AZnach;
    Post;
  end;
end;
//procedure TF_Kalc.Button2222Click(Sender: TObject);
//var
//  CostOfProjectReportParams: TCostOfProjectReportParams;
//begin
//  PutHaracterProjectInMt;
//  CostOfProjectReportParams := getCostOfProjectReportParams;
//  F_ProjMan.F_ResourceReport.ShowPriorCostOfProjectReportWizard(Kalc_DM.AllComponent_MemTable, Kalc_DM.HaracterProject_MemTable,
//    CostOfProjectReportParams, true);
//end;

procedure TF_Kalc.actExitExecute(Sender: TObject);
begin
   Self.Close;
end;

function TF_Kalc.getCostOfProjectReportParams: TCostOfProjectReportParams;
begin
  Result.ZakazchikName := ZakazchikName_Edit.Text;
  Result.PodradchikName := PodradchikName_edit.Text;
  Result.CurrencyName := Curr_ComboBox.Text;
end;

procedure TF_Kalc.btPrintReportClick(Sender: TObject);
var
  CostOfProjectReportParams: TCostOfProjectReportParams;
begin
  F_ProjMan.CreateFResourceReport;

  ValidateActiveFormControl(Self);
  CostOfProjectReportParams := getCostOfProjectReportParams;
  if EIncludHarProj.Checked then
    F_ProjMan.F_ResourceReport.ShowPriorCostOfProjectReportWizard(Kalc_DM.AllComponent_MemTable, Kalc_DM.HaracterProject_MemTable,
    CostOfProjectReportParams, true, false)
  else
    F_ProjMan.F_ResourceReport.ShowPriorCostOfProjectReportWizard(Kalc_DM.AllComponent_MemTable, Kalc_DM.HaracterProject_MemTable,
    CostOfProjectReportParams, false, false);

  ShowWindow(Handle, SW_MINIMIZE);
end;

procedure TF_Kalc.btEditReportClick(Sender: TObject);
var
  CostOfProjectReportParams: TCostOfProjectReportParams;
begin
  F_ProjMan.CreateFResourceReport;
  
  CostOfProjectReportParams := getCostOfProjectReportParams;
  if EIncludHarProj.Checked then
    F_ProjMan.F_ResourceReport.ShowPriorCostOfProjectReportWizard(Kalc_DM.AllComponent_MemTable, Kalc_DM.HaracterProject_MemTable,
    CostOfProjectReportParams, true, true)
  else
    F_ProjMan.F_ResourceReport.ShowPriorCostOfProjectReportWizard(Kalc_DM.AllComponent_MemTable, Kalc_DM.HaracterProject_MemTable,
    CostOfProjectReportParams, false, true);
end;


procedure TF_Kalc.Curr_ComboBoxPropertiesChange(Sender: TObject);
var
  FormatStr: string;
begin
 FormatStr :=  cKalc_Msg80 + Curr_ComboBox.EditText;
 AllComponent_GridDBTableView1.DataController.Summary.FooterSummaryItems[0].Format :=  FormatStr;
 AllComponent_GridDBTableView1.DataController.Summary.DefaultGroupSummaryItems[0].Format :=  FormatStr;
end;

procedure TF_Kalc.vHeighFloorChange(Sender: TObject);
var
  Heigth: double;
begin
  Heigth := vHeighFloor.Value;
  vHeigthCC.Max := Heigth;
  vHeigthRM.Max := Heigth;
  vHeigthFalseCeil.Max := Heigth;
end;

procedure TF_Kalc.vSKab_EditChange(Sender: TObject);
var
  val: double;
begin
   val := vSKab_Edit.Value;
   if val <= 0 then
     val := 1;
   vKolRooms.Value := trunc(vSWorkPlase.Value / val);
end;

procedure TF_Kalc.vSForRMChange(Sender: TObject);
begin
//  KolRMBtnClick(Self);
end;

procedure TF_Kalc.AllComponent_GridDBTableView1EditValueChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
begin
  //with Kalc_DM.AllComponent_MemTable do
//  begin
//   Post;
//    Edit;
//    FieldByName(fnCost).AsFloat := FieldByName(fnKolvo).AsFloat * FieldByName(fnPrice).AsFloat;
//    Post;
//  end;
end;

{ T_KalcDocument }

procedure T_KalcDocument.AddParamToXMl(AName: string; Value : string = '');
var
  Node, Atr: IDomNode;
  Str: IDOMCharacterData;
begin
  Node := TopNode.createElement(Aname);

  if Value <> '' then
  begin
    Atr :=  TopNode.createAttribute('value');
    Atr.nodeValue :=  Value;   // создание техстового узла
    Node.attributes.setNamedItem(Atr);
  end;

  RootNode.appendChild(Node);
end;

procedure T_KalcDocument.AddToXmlGrid(AGrid: TcxGridDBTableView);
var
  MT: TkbmMemTable;
  FieldDefs: TFieldDefs;
  NameField, Value, str: string;
  i, j: integer;
  fieldNode, Node, RecordNode: IDOMNode;
  Text: IDOMCharacterData;
  CountTime: integer;
begin
  MT := TkbmMemTable(AGrid.DataController.DataSource.DataSet);
  FieldDefs := MT.FieldDefs;
 // if mt.State <> dsBrowse then
//  begin
//   //AGrid.DataController.Cancel;
////    AGrid.DataController.Controller.EditingController.Edit.EditValue :=  AGrid.DataController.Controller.EditingController.Edit.  ;
//   // F_Kalc.Name_ColumnPropertiesEditValueChanged(AGrid.DataController.Controller.EditingController.Edit);
//
////    AGrid.DataController.UpdateData;
//
//   // mt.CheckBrowseMode;
//    //MT.CheckActive;
//  //  MT.DataEvent(deCheckBrowseMode, 0);
//   // case mt.State of
////    dsEdit, dsInsert:
////      begin
////        mt.UpdateRecord;
////        if mt.Modified then mt.Post else mt.Cancel;
////      end;
////    end;
//   // CountTime := 0;
//
//    //end;
//  end; 
  Node := TopNode.getElementsByTagName(Agrid.Name).item[0];
  if (Node <> NIL) and (MT.RecordCount > 0)  then
  with MT do
  begin
    First;
    j := 1;
    while Not Eof do
    begin
      str := 'Record' + IntTostr(j);
      RecordNode := TopNode.createElement(Str);
      if RecordNode <> Nil then
      begin
        For i := 0 to FieldDefs.Count -1 do
        begin
          NameField := FieldDefs[i].Name;
          fieldNode := TopNode.createAttribute(NameField);
          fieldNode.nodeValue := FieldByName(NameField).AsString;
          RecordNode.attributes.setNamedItem(fieldNode);
        end;
        Node.appendChild(RecordNode);
        inc(j);
        Next;
      end;
    end;
  end;
end;

constructor T_KalcDocument.Create(AOwner: TObject; AFileName: string = '');
begin
  inherited Create();
  FOwner := TForm(AOwner);
  if AFileName <> '' then
  begin
    LoadFromFile(AFileName);
  end
  else
  begin
    CreateXML(AFileName);
  end;
  end;

procedure T_KalcDocument.CreateXML(AFieldName: string);

begin
  Xml := TXMLDocument.Create(nil);
  XML.Active := false;
  Xml.XML.Text := ('');
  XML.Active := true;
  TopNode := XML.DOMDocument;
  RootNode := TopNode.appendChild(topNode.createElement('params'));
//  Xml.documentElement;
  InitXMl;



end;

destructor T_KalcDocument.Destroy;
begin
  Xml.Free;
  inherited;
end;

procedure T_KalcDocument.InitXMl;
var
  i, Count : integer;
  Control: TControl;
  procedure AddControlsToXML(AControl: TComponent);
  var
    i,j: integer;
    PageControl: TRzPageControl;
  begin
    if (Acontrol is TcxCustomEdit) or (AControl is TcxGridDBTableView)
       or(AControl is TRzCustomEdit) or (Acontrol is TRzCustomCheckBox)
       or(Acontrol is TcxCustomComboBox) or(AControl is TCustomComboBox)
       or(Acontrol is TFlyTreeViewPro) or(Acontrol is TRzRadioGroup)
    then
    begin
      AddParamToXML(Acontrol.Name);
    end
  end;
begin
  with FOwner do
  begin
    count := ComponentCount;
    for i := 0 to Count - 1 do
    begin
   //   if Components[i] is TCustomControl then
        AddControlsToXML(Components[i]);
    end;
  end;
//  SaveToFile('max.xml');
end;

procedure T_KalcDocument.LoadComponentValue(AComponent: TComponent);
var
  Node, childNode: IDOMNode;
  Text: IDOMCharacterData;
  Str: string;
  i: integer;
  FlyTreeView: TFlyTreeViewPro;
  FlyNode: TFlyNode;
begin
  Node := TopNode.getElementsByTagName(AComponent.Name).item[0];
  if (Node <> Nil) then
  if node.attributes.length > 0 then
  begin
    Str := '';
    if AComponent is TRzCheckBox then
      TRzCheckBox(AComponent).Checked := StrToBool(Node.attributes.item[0].nodeValue);
    if AComponent is TRzCustomEdit then
      TRzCustomEdit(AComponent).EditText := Node.attributes.item[0].nodeValue;
    if AComponent is TRzRadioGroup then
    begin
      if Node.attributes.item[0].nodeValue = '' then
        TRzRadioGroup(AComponent).ItemIndex := 0
      else
        TRzRadioGroup(AComponent).ItemIndex := StrToInt(Node.attributes.item[0].nodeValue);
    end;
   if AComponent is TcxCustomEdit then
    begin
      if AComponent is TcxSpinEdit then
      begin
        TcxSpinEdit(AComponent).Value := StrToFloatU(Node.attributes.item[0].nodeValue);
      end
      else
        if (AComponent is TcxComboBox) then
        begin
          TcxComboBox(AComponent).ItemIndex := StrToInt(Node.attributes.item[0].nodeValue)
        end
        else
          TcxCustomEdit(AComponent).EditValue := Node.attributes.item[0].nodeValue;
    end;
    if AComponent is TFlyTreeViewPro then
    begin
      FlyTreeView := TFlyTreeViewPro(AComponent);
      For i:= FlyTreeView.Items.Count - 1 downto 1 do
      begin
        FlyTreeView.Items.Delete(FlyTreeView.Items[i]);
      end;
      For i := 0 to Node.attributes.length - 1 do
      begin
        if i <> 0  then
          FlyTreeView.Items.Add(FlyNode, IntToStr(i+1) + cKalc_Msg1);
        FlyNode := FlyTreeView.Items[FlyTreeView.Items.Count - 1];
        FlyNode.Cells[1] := Node.attributes.item[i].nodeValue;

      end;
    end
  end
  else
  begin
    if AComponent is TcxGridDBTableView then
      LoadGridFromXML(TcxGridDBTableView(AComponent));
  end;
end;

procedure T_KalcDocument.LoadGridFromXML(AGrid: TcxGridDBTableView);
var
  MT: TDataSet;
  FieldDefs: TFieldDefs;
  NameField, Value, str: string;
  i, j: integer;
  fieldNode, Node, RecordNode: IDOMNode;
  Text: IDOMCharacterData;
  NodeList: IDOMNodeList;
  count: integer;
begin

  MT :=  AGrid.DataController.DataSource.DataSet;
  MT.Active := false;
  MT.Active := True;
  FieldDefs := MT.FieldDefs;
  NodeList :=  TopNode.getElementsByTagName(Agrid.Name);

  Node :=  NodeList.item[0];
  //MT.Active := false;
  //MT.Active := true;
  if (Node <> NIL) then
  begin
    RecordNode := Node.firstChild;
    j := 1;
    while RecordNode <> Nil do
    begin
      MT.Append;
      for i := 0 to RecordNode.attributes.length-1 do
      begin
        fieldNode := RecordNode.attributes.item[i];
        MT.FieldByName(fieldNode.nodeName).AsString := fieldNode.nodeValue;
      end;
      MT.Post;
      RecordNode := RecordNode.nextSibling;
    end;
  end;
end;


procedure T_KalcDocument.LoadFromFile(AFileName: string);
var
  i: integer;
  AControl: TComponent;
begin
  TF_Kalc(FOwner).Kalc_DM.DisebleMasterDetail;
  try
    Xml := TXMLDocument.Create(nil);
    Xml.LoadFromFile(AFileName);
    Xml.Active := true;
    TopNode := Xml.DOMDocument;
    RootNode := TopNode.documentElement;
    if RootNode <> nil then
    begin

      for i := 0 to FOwner.ComponentCount - 1 do
      begin
        AControl := FOwner.Components[i];
        if (Acontrol is TcxCustomEdit) or (AControl is TcxGridDBTableView)
           or(AControl is TRzCustomEdit) or (Acontrol is TRzCustomCheckBox)
           or(Acontrol is TcxCustomComboBox) or(AControl is TCustomComboBox)
           or(Acontrol is TFlyTreeViewPro) or(Acontrol is TRzRadioGroup)
        then
          LoadComponentValue(AControl);
      end;
      TF_Kalc(FOwner).Kalc_DM.AllComponent_MemTable.Active := False;
      TF_Kalc(FOwner).Kalc_DM.AllComponent_MemTable.Active := True;
    end;
  Finally
    TF_Kalc(FOwner).Kalc_DM.EnableMasterDetail;
  end;
end;

procedure T_KalcDocument.SaveComponentValue(AComponent: TComponent);
var
  Atr,Node, childNode: IDOMNode;
  Text: IDOMCharacterData;
  Str: string;
  i: integer;
  FlyTreeView: TFlyTreeViewPro;
begin
  Str := '';
  if AComponent is TRzCustomEdit then
    Str := TRzCustomEdit(AComponent).EditText;
   if AComponent is TRzCheckBox then
    Str := BoolToStr(TRzCheckBox(AComponent).Checked);
  if AComponent is TRzRadioGroup then
    Str := IntToStr(TRzRadioGroup(AComponent).ItemIndex);
  if AComponent is TcxCustomEdit then
  begin
    if AComponent is TcxSpinEdit then
      Str := FloatToStrU(TcxSpinEdit(AComponent).Value)
    else
      if TcxCustomEdit(AComponent).EditValue = Null then
        Str := ''
      else
        if (AComponent is TcxComboBox) then
        begin
         str := IntToStr(TcxComboBox(AComponent).ItemIndex);
        end
        else
          Str := TcxCustomEdit(AComponent).EditValue;
  end;
  
  if Str <> '' then
  begin
    Node := TopNode.getElementsByTagName(AComponent.Name).item[0];
    Atr := TopNode.createAttribute('Value');
    Atr.nodeValue := Str;
    Node.attributes.setNamedItem(Atr);
   //TopNode.getElementById(AComponent.Name);
  //  Text := Xml.DOMDocument.createTextNode(Str);
  //  Node.appendChild(Text);

  end
  else
  begin
    if AComponent is TFlyTreeViewPro then
    begin
      Node := TopNode.getElementsByTagName(AComponent.Name).item[0];
      FlyTreeView := TFlyTreeViewPro(AComponent);
      For i:= 0 to FlyTreeView.Items.Count - 1 do
      begin
        str := 'Floor' + IntToStr(i + 1);
        Atr := TopNode.createAttribute(Str);
        Atr.nodeValue := FlyTreeView.Items[i].Cells[1];
        Node.attributes.setNamedItem(Atr);
      end;
    end;
    if AComponent is TcxGridDBTableView then
      AddToXmlGrid(TcxGridDBTableView(AComponent));
  end;
end;

procedure T_KalcDocument.SaveToFile(AFileName: string);
var
  i: integer;
begin
  TF_Kalc(FOwner).Kalc_DM.DisebleMasterDetail;
  try
    for i := 0 to FOwner.ComponentCount - 1 do
    begin
      SaveComponentValue(FOwner.Components[i]);
    end;
  finally
    TF_Kalc(FOwner).Kalc_DM.EnableMasterDetail;
  end;
  Xml.SaveToFile(AFileName);

end;

procedure TF_Kalc.OpenFile_BtnClick(Sender: TObject);
var
  x: T_KalcDocument;
  Name: TFileName;
  razn : integer;
begin
  OpenDialog1.Filter := cKalc_Msg81;
  OpenDialog1.Title := cKalc_Msg82;
  if OpenDialog1.Execute then
  begin
    Name := OpenDialog1.FileName;
    x := T_KalcDocument.Create(Self, Name);
    x.Destroy;

     //проверяем и выносим предупреждения
    if GetFreePercentForCable > 0 then
      StaticText5.Show
    else
      StaticText5.Hide;
    if GetFreePercent(Kalc_DM.CableCanalMemTable.RecordCount)< 0 then
    begin
      StaticText4.Show;
    end
    else
    begin
      StaticText4.Hide;
    end;
    razn := CmpFloorsWithKolRM ;
    if razn <> 0 then
    begin
      StaticText1.Show;
      StaticText2.Caption := cKalc_Msg2 + IntToStr(razn);
      StaticText2.Show;
    end
    else
    begin
      StaticText1.Hide;
      StaticText2.Hide;
    end;

  end;
end;

procedure TF_Kalc.SaveFile_BtnClick(Sender: TObject);
var
  x: T_KalcDocument;
  Name: TFileName;
begin

  SaveDialog1.Filter := cKalc_Msg83;
  SaveDialog1.Title := cKalc_Msg84;
  SaveDialog1.DefaultExt := '*.spe';
  If SaveDialog1.Execute then
  begin
    Name := SaveDialog1.FileName;
    x := T_KalcDocument.Create(Self);
    x.SaveToFile(Name);
    x.Destroy;
  end;



end;

procedure TF_Kalc.FormClose(Sender: TObject; var Action: TCloseAction);
var
  x: T_KalcDocument;
  ActivePage: integer;
  Error: Boolean;
begin
  ValidateActiveFormControl(Self);
  Error := true;
  ActivePage := Main_PageControl.ActivePageIndex;
  if ActivePage = 4 then
  begin
    if AllComponent_GridDBTableView1.DataController.IsEditing then
      Error :=false;
  end;
  if ActivePage = 3 then
  begin
    if PriceWorks_TableView.DataController.IsEditing then
      Error :=false;
  end;
  if ActivePage = 1 then
  begin
    if CostRMGridTableView.DataController.IsEditing
       or CostPKDBTableView.DataController.IsEditing
       or CostPP_GridDBTableView.DataController.IsEditing
       or GT_CostOrg.DataController.IsEditing
       or CostShelf_GridDBTableView.DataController.IsEditing
       or ShelfForFloor_GridDBTableView.DataController.IsEditing
       or DopEq_TableView.DataController.IsEditing
    then
       Error := false;
  end;
  if ActivePage = 2 then
  begin
    if CCForFloor_GridTableView.DataController.IsEditing
       or CCUnderCeil_GridTableView.DataController.IsEditing
       or ElPointFix_GridTableView.DataController.IsEditing
       or CableCanalGrid_TableView1.DataController.IsEditing
       or ElementOfCC_Grid_DBTableView.DataController.IsEditing
    then
       Error := false;
  end;

  try
    if Error then
    begin
      x := T_KalcDocument.Create(Self);
      x.SaveToFile(TempFile);
      x.Destroy;
    end
    else
      Action := caNone;
  except
    on E: Exception do AddExceptionToLogEx('TF_Kalc.FormClose', E.Message);
  end;
end;

procedure TF_Kalc.CostShelf_GridDBTableViewEditValueChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
var
  price: double;
  id: integer;
begin
//  Kalc_DM.ShelfForFloor_MemTable.Refresh;
  Sender.DataController.Post;
  if AItem.Index = 3 then
  begin
    id := Kalc_DM.CostShelf_MemTable.FieldByName(fnID).AsInteger;
    price := Kalc_DM.CostShelf_MemTable.FieldByName(fnPrice).AsFloat;
    with Kalc_DM.ShelfForFloor_MemTable do
    begin
      First;
      while not Eof do
      begin
        if (not FieldByName('Id_Shelf').IsNull) and(id = FieldByName('Id_Shelf').AsInteger) then
        begin
          Edit;
          FieldByName(fnPrice).AsFloat := price;
          Post;
        end;
        Next;
      end;
    end;

  end;

end;

procedure TF_Kalc.CostRMGridTableViewDragOver(Sender, Source: TObject; X,
  Y: Integer; State: TDragState; var Accept: Boolean);
begin
  Accept := false;
  if Source is TTreeView then
    if TControl(Source).Owner is TF_Main then
    begin
      if TTreeView(Source).Selected <> nil then
      begin
        if IsComponentNode(TTreeView(Source).Selected) then
          if GDropComponent.ID <> 0 then
          begin
            Accept := true;
          end;
      end;
    end;
end;

procedure TF_Kalc.CostRMGridTableViewDragDrop(Sender, Source: TObject; X,
  Y: Integer);
var
  price: double;
  OldCurrency, NewCurrency: TCurrency;
begin
  if GDropComponent.IsLine = biFalse then
  begin
    with Kalc_DM.CostRM_MemTable do
    begin
      Append;
      FieldByName(fnName).AsString := GDropComponent.Name;
      FieldByName(fnArticul).AsString := GDropComponent.ArticulProducer;
      price := GetPriceForKalcFromDragCompon(GDropComponent);
      FieldByName(fnPrice).AsFloat := Price;
      FieldByName(fnKolvo).AsInteger := 1;
      Post;
    end;
//  TcxGridTableView(Sender).DataController.Refresh;
    ValCostFromGrid(vCRM, Kalc_DM.CostRM_MemTable);
  end;
end;

procedure TF_Kalc.CostPKDBTableViewDragDrop(Sender, Source: TObject; X,
  Y: Integer);
var
  OstPer,resultCmp: integer;
  price: double;
begin
  if GDropComponent.ComponentType.SysName = ctsnPatchCord then
  begin
    resultCmp := Kalc_DM.CmpPerFromCostPk_MemTable(OstPer);
    price := GetPriceForKalcFromDragCompon(GDropComponent);
    case resultCmp of
      1 :   U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CostPK_MemTable, GDropComponent.Name, GDropComponent.ArticulProducer, Price, -1, OstPer, mpkCross);
      2,3 :   U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CostPK_MemTable, GDropComponent.Name, GDropComponent.ArticulProducer, Price, -1,  OstPer, mpkRM);
    else
        U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CostPK_MemTable, GDropComponent.Name, GDropComponent.ArticulProducer, Price, -1, 0, mpkCross);
    end;
  end;
  TcxGridTableView(Sender).DataController.Refresh;
end;

procedure TF_Kalc.CostPP_GridDBTableViewDragDrop(Sender, Source: TObject;
  X, Y: Integer);
var
  Prop: PProperty;
  i: integer;
  price: double;
begin
  if GDropComponent.ComponentType.SysName = ctsnPatchPanel then
  begin
    if Kalc_DM.CostPP_MemTable.RecordCount < 1 then
    begin
      price := GetPriceForKalcFromDragCompon(GDropComponent);
      U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CostPP_MemTable, GDropComponent.Name, GDropComponent.ArticulProducer, Price);
      vCPP.Value := Price;
      For i := 0 to GDropComponent.Properties.Count - 1 do
      begin
        Prop := GDropComponent.Properties.Items[i];
        if prop.SysName = pnPORTCOUNT then
        begin
          vKolPortPP.Value := StrToInt(prop.Value);
          break;
        end;
      end;
    ValCostFromGrid(vCPP, Kalc_dm.CostPP_MemTable);
    //TcxGridTableView(Sender).DataController.Refresh;
   end;
 end;
end;

procedure TF_Kalc.GT_CostOrgDragDrop(Sender, Source: TObject;
  X, Y: Integer);
var
  price: double;
begin
  if GDropComponent.ComponentType.SysName = ctsnOrganizer then
  begin
    if Kalc_DM.CostOrg_MemTable.RecordCount < 1 then
    begin
      price := GetPriceForKalcFromDragCompon(GDropComponent);
      U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CostOrg_MemTable, GDropComponent.Name, GDropComponent.ArticulProducer, Price);
    end;
    //TcxGridTableView(Sender).DataController.Refresh;
    ValCostFromGrid(vCOrg, Kalc_dm.CostOrg_MemTable);
  end;
end;

procedure TF_Kalc.CostShelf_GridDBTableViewDragDrop(Sender,
  Source: TObject; X, Y: Integer);
var
 price: double;
begin
  if GDropComponent.ComponentType.SysName = ctsnCupboard then
  begin
    price := GetPriceForKalcFromDragCompon(GDropComponent);
    U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CostShelf_MemTable, GDropComponent.Name, GDropComponent.ArticulProducer, Price);
     TcxGridTableView(Sender).DataController.Refresh;
  end;
end;

procedure TF_Kalc.CableCanalGrid_TableView1DragDrop(Sender,
  Source: TObject; X, Y: Integer);
var
  per: integer;
  i: integer;
  CCConnector: PCableCanalConnector;
  Compon: TSCSComponent;
  price: double;

  Function GotoCableConnectorInMT(Id_typeCCConector: integer): boolean;
  var
   i: integer;
  begin
    result := true;
    Kalc_DM.ElemForCabcanal_MemTable.First;
    case Id_typeCCConector of
      contCork: begin
                  Kalc_DM.ElemForCabcanal_MemTable.MoveBy(4);
                end;
      contAnglePlane: begin
                      //  Kalc_DM.ElemForCabcanal_MemTable.MoveBy(2)
                      end;
      contAngleIn: begin
                     Kalc_DM.ElemForCabcanal_MemTable.MoveBy(1);
                   end;
      contAngleOut: begin
                      Kalc_DM.ElemForCabcanal_MemTable.MoveBy(2);
                    end;
      contConnector: begin
                        Kalc_DM.ElemForCabcanal_MemTable.MoveBy(3);
                      end;
      else
      begin
        Result := False;
      end;
    end;
  end;
begin
  If GDropComponent.ComponentType.SysName =  ctsnCableChannel then
  begin
    per := GetFreePercent(Kalc_DM.CableCanalMemTable.RecordCount);
   // inc(FCountCC);
    Kalc_DM.CableCanalMemTable.FieldByName(fnNpp);
    price := GetPriceForKalcFromDragCompon(GDropComponent);
    with Kalc_DM.CableCanalMemTable do
    begin
      Append;
     // FieldByName(fnNpp).AsInteger := FCountCC;
      FieldByName(fnName).AsString := GDropComponent.Name;
      FieldByName(fnArticul).AsString :=  GDropComponent.ArticulProducer;
      FieldByName(fnPrice).AsFloat := Price;
      FieldByName(fnPercent).AsInteger :=  per;
      Post;
    end;
    AddCCElements;
    Compon := TSCSComponent.Create(GDropComponent.ActiveForm);
    try
      for i := 0 to GDropComponent.CableCanalConnectors.Count - 1 do
      begin
        CCConnector := GDropComponent.CableCanalConnectors[i];
        if GotoCableConnectorInMT(CCConnector.ConnectorType) then
        begin
          Compon.LoadComponentByID(CCConnector.IDNBConnector);
          With Kalc_DM.ElemForCabcanal_MemTable do
          begin
            Edit;
            FieldByName(fnArticul).AsString := Compon.ArticulProducer;
            price := GetPriceForKalcFromDragCompon(Compon);
            FieldByName(fnPrice).AsFloat := price;
            Post;
          end;
        end;
      end;
    finally
      Compon.Free;
    end;
    if GetFreePercent(Kalc_DM.CableCanalMemTable.RecordCount)< 0 then
    begin
      StaticText4.Show;
    end
    else
    begin
      StaticText4.Hide;
    end;
  end;
end;

procedure TF_Kalc.AddCCElements;
var
  z: integer;
  FCountCC: integer;
begin
  Kalc_DM.TypeOfElementCC_MemTable.First;
  while not Kalc_DM.TypeOfElementCC_MemTable.Eof do
  begin
    FCountCC := Kalc_DM.CableCanalMemTable.FieldbyName(fnNpp).AsInteger;
    z := Kalc_DM.TypeOfElementCC_MemTable.FieldByName('ID').AsInteger;
    With Kalc_DM.ElemForCabcanal_MemTable do
    begin
      Append;
      //inc(FCountECC);
      // FieldByName('Id').AsInteger := FCountECC;
      FieldByName('Npp_CC').AsInteger := FCountCC;
      FieldByName('Id_Type').AsInteger := z;
      FieldByName('Price').AsFloat := 0;
      if z = 1 then
        FieldByName('Rashod').AsInteger := 6;
      if z = 2 then
        FieldByName('Rashod').AsFloat := 6;
      if z = 3 then
        FieldByName('Rashod').AsFloat := 2.5;
      if z = 4 then
        FieldByName('Rashod').AsFloat := 6;
      if z = 5 then
        FieldByName('Rashod').AsFloat := 7;
      post;
    end;
    Kalc_DM.TypeOfElementCC_MemTable.Next;
  end;
end;

procedure TF_Kalc.EnableTableView(ATableView: TcxGridDBTableView; AEnabled: Boolean);
begin
  if AEnabled then
  begin
    ATableView.Styles.Background := nil;
    ATableView.Styles.Content := nil;
  end
  else
  begin
    ATableView.Styles.Background := cxBackDisabled;
    ATableView.Styles.Content := cxBackDisabled;
  end;
end;

procedure TF_Kalc.ElPointFix_GridTableViewDragDrop(Sender, Source: TObject;
  X, Y: Integer);
var
  prop: PProperty;
  i: integer;
begin
  if GDropComponent.ComponentType.SysName = ctsnCableChannelAccessory then
  begin
    begin
      U_Kalc_DM.AddRecordInMemTable(Kalc_DM.ElPointFix_MemTable, GDropComponent.Name, GDropComponent.ArticulProducer, RoundX(GDropComponent.Price,2),-1, 0);
      For i := 0 to GDropComponent.Properties.Count - 1 do
      begin
        Prop := GDropComponent.Properties.Items[i];
        if prop.SysName = pnExpenseForMetr then
        begin
          vMetodOpenWir1_Rashod.Value := StrToFloatU(CorrectStrToFloat(prop.Value));
          break;
        end;
      end;
   
    //TcxGridTableView(Sender).DataController.Refresh;
   end;
 end;
end;

procedure TF_Kalc.CCForFloor_GridTableViewDragDrop(Sender, Source: TObject;
  X, Y: Integer);
begin
  if GDropComponent.ComponentType.SysName = ctsnCableChannel then
  begin
    U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CCFloor_MemTable, GDropComponent.Name, GDropComponent.ArticulProducer, RoundX(GDropComponent.Price,2),-1, 0);
  end;
end;

procedure TF_Kalc.CCUnderCeil_GridTableViewDragDrop(Sender,
  Source: TObject; X, Y: Integer);
begin
  if GDropComponent.ComponentType.SysName = ctsnCableChannel then
  begin
    U_Kalc_DM.AddRecordInMemTable(Kalc_DM.CCUnderCeil_MemTable, GDropComponent.Name, GDropComponent.ArticulProducer, RoundX(GDropComponent.Price,2),-1, 0);
  end;
end;

procedure TF_Kalc.AllComponent_GridDBTableView1FocusedItemChanged(
  Sender: TcxCustomGridTableView; APrevFocusedItem,
  AFocusedItem: TcxCustomGridTableItem);
begin
//
end;

procedure TF_Kalc.AllComponent_Grid_pricePropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
var
  price: Double;
begin
  price := DisplayValue;

  if price < 0 then
  begin
    Error := true;
  end
  else
  with Kalc_DM.AllComponent_MemTable do
  begin
    Edit;
    if FieldByName('TypePoz').AsString = idTypePozWorks then
      FieldByName(fnCost).AsFloat := FieldByName(fnKolvo).AsFloat * Price * getKoefForWorks
    else
      FieldByName(fnCost).AsFloat := FieldByName(fnKolvo).AsFloat * Price;
    FieldByName(fnPrice).AsFloat := price;
    Post;
  end;
end;

procedure TF_Kalc.AllComponent_Grid_KolvoPropertiesValidate(
  Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption;
  var Error: Boolean);
var
  kolvo: integer;
begin
  Kolvo := DisplayValue;
  if kolvo < 0 then
  begin
    Error := true;
  end
  else
    with Kalc_DM.AllComponent_MemTable do
    begin
      Edit;
      if FieldByName('TypePoz').AsString = idTypePozWorks then
        FieldByName(fnCost).AsFloat := FieldByName(fnPrice).AsFloat * Kolvo * getKoefForWorks
      else
        FieldByName(fnCost).AsFloat := FieldByName(fnPrice).AsFloat * Kolvo;
      FieldByName(fnKolvo).AsInteger := Kolvo;
      Post;
    end;
end;

procedure TF_Kalc.Cable_Grid_DBTableViewDragDrop(Sender, Source: TObject;
  X, Y: Integer);
var
  price: double;
begin
  if GDropComponent.ComponentType.SysName = ctsnCable then
  begin
    price := GetPriceForKalcFromDragCompon(GDropComponent);
    U_Kalc_DM.AddRecordInMemTable(Kalc_DM.Cable_MemTable, GDropComponent.Name, GDropComponent.ArticulProducer, Price,-1, 100, 0);
    if GetFreePercentForCable >= 0 then
      StaticText5.Show
    else
      StaticText5.Hide;
    end;
end;

destructor TF_Kalc.Destroy;
begin
  Kalc_DM.Free;
  inherited;
end;

procedure TF_Kalc.ClearProject_BtnClick(Sender: TObject);
begin
  ClearProject;
   //проверяем и выносим предупреждения
  StaticText5.Hide;
  StaticText4.Hide;
  StaticText1.Hide;
  StaticText2.Hide;

end;

procedure TF_Kalc.ClearProject;
var
  Component: TComponent;
  i, j, Count: integer;
  FlyTreeViewPro: TFlyTreeViewPro;
  Node: TFlyNode;
begin
  for i := 0 to ComponentCount - 1 do
  begin
    Component := Components[i];
    if (Component is TcxCustomEdit) then
    begin
      TcxCustomEdit(Component).EditValue := 0;
    end;
    if (Component is TcxGridDBTableView) then
    begin
      if (Component.Name <> 'PriceWorks_TableView' ) then
      begin
        TcxGridDBTableView(Component).DataController.DataSource.DataSet.Active := False;
        TcxGridDBTableView(Component).DataController.DataSource.DataSet.Active := True;
      end
      else
      begin
        btClearPriceWorksClick(Self)
      end;
    end;
    if (Component is TRzEdit) then
    begin
      TRzEdit(Component).EditText := '';
    end;

    if (Component is TRzSpinEdit) then
    begin
      TRzSpinEdit(Component).Value := 0;
    end;

    if (Component is TRzCheckBox) then
    begin
      TRzCheckBox(Component).Checked := False;
    end;

    if (Component is TcxComboBox) then
    begin
      TcxComboBox(Component).ItemIndex := 0;
    end;

    if (Component is TComboBox) then
    begin
      TComboBox(Component).ItemIndex := 0;
    end;

    if (Component is TFlyTreeViewPro) then
    begin
      FlyTreeViewPro := TFlyTreeViewPro(Component);
      Count := FlyTreeViewPro.Items.Count -1;
      For j := Count downto 1  do
      begin
        Node := FlyTreeViewPro.Items.GetLastNode;
        FlyTreeViewPro.Items.Delete(Node);
      end;
      FlyTreeViewPro.Items[0].Cells[1] := '1';
    end;
  end;
  Kalc_DM.AddShelfForFloor(cKalc_Msg85);
end;

procedure TF_Kalc.grComponentTypesItems0Click(Sender: TObject);
begin
  pcComponentTypes.ActivePage.TabVisible := false;
  pcComponentTypes.ActivePage := TRzTabSheet(TRzGroupItem(Sender).Tag);
  pcComponentTypes.ActivePage.TabVisible := true;
end;

procedure TF_Kalc.grChannelComponTypesItems0Click(Sender: TObject);
begin
  pcChannelComponTypes.ActivePage.TabVisible := false;
  pcChannelComponTypes.ActivePage := TRzTabSheet(TRzGroupItem(Sender).Tag);
  pcChannelComponTypes.ActivePage.TabVisible := true;
end;

procedure TF_Kalc.FormCreate(Sender: TObject);
//var
//  x : T_KalcDocument;


  procedure AddItemsToGroup(AGroup: TRzGroup; ASrcPageControl: TRzPageControl; AOnClick: TNotifyEvent);
  var
    i: Integer;
    TabSheet: TRzTabSheet;
    GroupItem: TRzGroupItem;
  begin
    AGroup.Items.Clear;
    for i := 0 to ASrcPageControl.PageCount - 1 do
    begin
      TabSheet := ASrcPageControl.Pages[i];
      TabSheet.TabVisible := false;

      GroupItem := AGroup.Items.Add;
      GroupItem.Caption := TabSheet.Caption;
      GroupItem.OnClick := AOnClick;
      GroupItem.Tag := Integer(TabSheet);
    end;
  //  if AGroup.Items.Count > 0 then
  //   pcComponentTypes.ActivePageIndex := 0;
     // AGroup.Items[0].Click;
  end;

begin
  try
    Kalc_DM :=TKalc_DM.Create(Self);
    
    //#From Oleg#
    if Main_PageControl.PageCount > 0 then
      Main_PageControl.ActivePage := Main_PageControl.Pages[0];
    AddItemsToGroup(grComponentTypes, pcComponentTypes, grComponentTypesItems0Click);

    //AddItemsToGroup(grChannelComponTypes, pcChannelComponTypes, grChannelComponTypesItems0Click);
    gbChannelComponTypes.Visible := false;
  except
    on E: Exception do AddExceptionToLogEx('TF_Kalc.Create', E.Message);
  end;
end;

procedure TF_Kalc.Execute;
var
  x : T_KalcDocument;
  StrList: TStringList;
  i, razn: integer;
  node : tflyNode;
  procedure SetDisplayFormat;
    function cutFormatToInt(AStr: string): string;
    //var len:integer;
    begin
      Result := AStr;
       delete(Result,3,4);
    end;

   begin
    {$IF Defined(SCS_PE) or Defined(SCS_SPA)}
     Node := vKolRMForFloor.Items.GetFirstNode;
     node.Cells[0] := strCalcCapt0;
    {$IFEND}
    TcxCurrencyEditProperties(Price_Column.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(CostPKColumn_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(CostPP_GridColumn_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(CostOrg_GridColumn_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(CostShelf_GridColumn_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(DopEq_Grid_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(PriceWorks_Grid_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(Cable_Grid_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(CableCanalGrid_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(CCForFloor_Grid_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(CCUnderCeil_Grid_price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(ElPointFix_Grid_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(AllComponent_Grid_price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(ShelfForFloor_GridColumn_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
    TcxCurrencyEditProperties(Cable_Grid_Percent.Properties).DisplayFormat := cutFormatToInt(GetDisplayFormatForFloat);
    TcxCurrencyEditProperties(CableCanalGrid_Percent.Properties).DisplayFormat := cutFormatToInt(GetDisplayFormatForFloat);
    TcxCurrencyEditProperties(rashod.Properties).DisplayFormat := cutFormatToInt(GetDisplayFormatForFloat);
    TcxCurrencyEditProperties(CostRMGrid_Kolvo.Properties).DisplayFormat := cutFormatToInt(GetDisplayFormatForFloat);
    TcxCurrencyEditProperties(CostPK_Persent.Properties).DisplayFormat := cutFormatToInt(GetDisplayFormatForFloat);
    TcxCurrencyEditProperties(DopEq_Kolvo.Properties).DisplayFormat := cutFormatToInt(GetDisplayFormatForFloat);
    TcxCurrencyEditProperties(CCUnderCeil_Grid_Percent.Properties).DisplayFormat := cutFormatToInt(GetDisplayFormatForFloat);
    TcxCurrencyEditProperties(ElPointFix_Grid_Percent.Properties).DisplayFormat := cutFormatToInt(GetDisplayFormatForFloat);
    TcxCurrencyEditProperties(CCForFloor_Grid_Percent.Properties).DisplayFormat := cutFormatToInt(GetDisplayFormatForFloat);
    TcxCurrencyEditProperties(AllComponent_Grid_Kolvo.Properties).DisplayFormat := cutFormatToInt(GetDisplayFormatForFloat);
//              TcxCurrencyEditProperties(Cable_Grid_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
//             TcxCurrencyEditProperties(Cable_Grid_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
//              TcxCurrencyEditProperties(Cable_Grid_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
//             TcxCurrencyEditProperties(Cable_Grid_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;
//              TcxCurrencyEditProperties(Cable_Grid_Price.Properties).DisplayFormat := GetDisplayFormatForFloat;

  end;
begin
  SetDisplayFormat;
  {$IF Defined(NORMSCS_PE) or Defined(SCS_SPA)}
    TabSheet3.TabVisible := false;
  {$IFEND}
  if Self.Visible then
  //Tolik 21/12/2019 --
  //  SetForegroundWindow(Self.Handle)
  begin
    SetForegroundWindow(Self.Handle);
    ShowWindow(Handle, SW_SHOWNORMAL); // после показа отчета -- сворачивается, при повторном вызове --
                                       // показывается уже свернутым, вот чтобы избежать такой фигни ...
                                       // нужно в любом случае показать в нормальном виде
  end
  //
  else
  begin
    Self.FormStyle := fsStayOnTop;
    try
      Screen.Cursor := crHourGlass;
      try
        FixLabeles;//установка подписей
        //установка названий столбцоа в vKolRMForFloor
        vKolRMForFloor.Columns[0].Caption := cKalc_Msg150;
        vKolRMForFloor.Columns[1].Caption := cKalc_Msg151;
        FixCableWey_ComboBox.ItemIndex := 2;
        TypeWeyCC_PageControl.ActivePage := CableInCC_Sheet;
        Curr_ComboBox.Properties.Items.Clear;
        StrList := GetCurrenciesNameBriefListFromNB;
        for i := 0 to StrList.Count - 1 do
        begin
          Curr_ComboBox.Properties.Items.AddObject(StrList.Strings[i], StrList.Objects[i]);
        end;
        Curr_ComboBox.ItemIndex := 0;
        ServFloor_ComboBox.EditValue := 0;
        ServerFloor := 0;
        //FCountCC := 0;
//        FCountECC := 0;
       // actAddCableCanalExecute(Self);
       // actAddCableExecute(Self);
        try
          if FileExists(TempFile) then
          begin
            x := T_KalcDocument.Create(Self, TempFile);
            x.Destroy;
          end
          else
          begin
            ClearProject;
          end;
        except
          MessageModal(cKalc_Msg86,cKalc_Msg15, MB_ICONWARNING );
          ClearProject;
        end;

        ECostRMGrid_CheckClick(ECostRMGrid_Check);
        ECostPKGridCheckClick(ECostPKGridCheck);
        ECostPPGrid_CheckClick(ECostPPGrid_Check);
        ECostOrgGrid_CheckClick(ECostOrgGrid_Check);
        ECostShelfGridCheckClick(ECostShelfGridCheck);
        EDopEqGrid_CheckClick(EDopEqGrid_Check);

       // if Main_PageControl.PageCount > 0 then
//          Main_PageControl.ActivePage := Main_PageControl.Pages[0];
        //проверяем и выносим предупреждения
        pcComponentTypes.ActivePage.TabVisible := True;
        if GetFreePercentForCable > 0 then
          StaticText5.Show
        else
          StaticText5.Hide;
        if GetFreePercent(Kalc_DM.CableCanalMemTable.RecordCount)< 0 then
        begin
          StaticText4.Show;
        end
        else
        begin
          StaticText4.Hide;
        end;
        razn := CmpFloorsWithKolRM ;
        if razn <> 0 then
        begin
          StaticText1.Show;
          StaticText2.Caption := cKalc_Msg2 + IntToStr(razn);
          StaticText2.Show;
        end
        else
        begin
          StaticText1.Hide;
          StaticText2.Hide;
        end;

      finally
        if Main_PageControl.PageCount > 0 then
          Main_PageControl.ActivePageIndex := 0;
        Screen.Cursor := crDefault;
      end;
    except
    end;
    Self.Show;
  end;
end;

procedure TF_Kalc.CostRMGridTableViewEditValueChanged(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
begin
   ValCostFromGrid(vCRM, Kalc_DM.CostRM_MemTable);
end;

procedure TF_Kalc.Name_ColumnPropertiesEditValueChanged(Sender: TObject);
var
  MemTable: TDataSet;
  Str: string;
  DBColumn: TcxGridDBColumn;
  GridTableView: TcxGridDBTableView;

begin
    Str := VarToStr(TcxCustomEdit(Sender).EditValue);
    GridTableView := TcxGridDBTableView(TCxGrid(TcxGridSite(TCxTextEdit(Sender).parent).Parent).ActiveView);
    MemTable := GridTableView.DataController.DataSet;
    dbColumn := TcxGridDBColumn(GridTableView.DataController.Controller.EditingItem);
   // GridTableView.DataController.FocusedRowIndex;
  //  Str := VarToStr(GridTableView.DataController.Controller.EditingController.Edit.EditValue);
    MemTable.FieldByName(DBColumn.DataBinding.FieldName).AsString := STr;
    GridTableView.DataController.Post;
end;

procedure TF_Kalc.DopEq_GridExit(Sender: TObject);
begin
  F_Kalc.DopEq_TableView.DataController.Post;
end;

function TF_Kalc.GetPriceForKalcFromDragCompon(ACompon: TSCSComponent): double;
var
  price: double;
  res1, res2: PObjectCurrencyRel;
  OldCurrency, NewCurrency: TCurrency;
  Index : integer;
begin
  try
    Result := RoundX(ACompon.Price, 2);
    index := Curr_ComboBox.ItemIndex;

    ZeroMemory(@OldCurrency, SizeOf(TCurrency));
    ZeroMemory(@NewCurrency, SizeOf(TCurrency));

    res1 := F_NormBase.DM.GetComponCurrencyByMainFld(ACompon.ID, ctMain);
    if Assigned(res1) then
    begin
      OldCurrency := res1^.Data;
    end;                         
    Res2 := F_NormBase.DM.GetComponCurrencyByCurrencyID(ACompon.id, Integer(Curr_ComboBox.Properties.Items.Objects[Index]) );
    if Assigned(Res2) then
    begin
      NewCurrency := Res2^.Data;
    end;
    if Assigned(res1) and Assigned(Res2) then
      Result := GetPriceAfterChangeCurrency(result, OldCurrency, NewCurrency, 2);
  finally
    FreeMem(res1);
    FreeMem(res2);
  end
end;

procedure TF_Kalc.btClearPriceWorksClick(Sender: TObject);
begin

 with Kalc_DM.PriceWorks_MemTable do
  begin
  //  if RecordCount = 0 then
      Kalc_DM.InitPriceWorks_MemTable;
    //else
//      while not Eof do
//      begin
//        First;
//        FieldByName('Price').AsFloat := 0;
//        Post;
//        Next;
//      end;
  end;
end;

procedure TF_Kalc.AllComponent_Grid_TypePozGetDisplayText(
  Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
  var AText: String);
begin
  if AText = idTypePozMaterial then
    AText := stTypePozMaterial
  else
    if AText = idTypePozWorks then
      AText := stTypePozWorks;
end;

procedure TF_Kalc.PutToReportWork(AIdWorks: integer; AKolWorks: integer; AKoef: double = 1);
var
  dNum: integer;
  NameWorks: string;
  CostWorks, PriceWorks: double;
  KOEF: double;
begin  
  {$IF NOT Defined(NORMSCS_PE) and NOT Defined(SCS_SPA)}
    PriceWorks := 0;
    with Kalc_DM.PriceWorks_MemTable do
    begin
      if Active then
      begin
        KOEF := FieldByName('Price').AsFloat;
        dNum := AIdWorks - RecNo;
        if dNum <> 0 then
           MoveBy(dNum);
        NameWorks := FieldByName('Name').AsString;
        PriceWorks := FieldByName('Price').AsFloat;
      end;
    end;
    if PriceWorks > 0 then
    begin
      CostWorks := PriceWorks * AKolWorks * Akoef;
      AddRecordInReport(NameWorks,'', AKolWorks, PriceWorks, CostWorks, idTypePozWorks);
    end;
  {$IFEND}  
end;

function TF_Kalc.GetKoefForWorks: double;
var
  KOEF: double;
begin
  try
    Koef := 0;
    with Kalc_DM.PriceWorks_MemTable do
    begin
      if Active then
      begin
        Last;
        KOEF := roundx(FieldByName('Price').AsFloat,3);
      end;
    end;
    if KOEF = 0 then
      Koef := 1;
    Result := KOEF;
  except
    on E: Exception do AddExceptionToLog('TF_Kalc.GetKoefForWorks: '+E.Message);
  end;
end;


procedure TF_Kalc.FixLabeles;
begin
  Label5.Caption := strCalcCapt1 + GetNameUOM(F_NormBase.FUOM, true, true);
  Label6.Caption := strCalcCapt2 + GetNameUOM(F_NormBase.FUOM, true, true);
  Label11.Caption := strCalcCapt3 + GetNameUOM(F_NormBase.FUOM, true, true);
  Label7.Caption := strCalcCapt4 + GetNameUOM2(F_NormBase.FUOM);
  Label9.Caption := strCalcCapt5 + GetNameUOM2(F_NormBase.FUOM);
  Label10.Caption := strCalcCapt6 + GetNameUOM2(F_NormBase.FUOM);
  Label40.Caption := strCalcCapt7 + GetNameUOM(F_NormBase.FUOM, true, true);
  Label41.Caption := strCalcCapt8 + GetNameUOM(F_NormBase.FUOM, true, true);
  Label13.Caption := strCalcCapt9 + GetNameUOM2(F_NormBase.FUOM);
  Label31.Caption := strCalcCapt10 + GetNameUOM(F_NormBase.FUOM, true, true);
  Label21.Caption := strCalcCapt11 + GetNameUOM(F_NormBase.FUOM, true, true);
  Label17.Caption := strCalcCapt12 + GetNameUOM(F_NormBase.FUOM, true, true);
  Label72.Caption := strCalcCapt13 + GetNameUOM(F_NormBase.FUOM, true, true);
 // Label52.Caption := GetNameUOM(F_NormBase.FUOM, true, false);
  Label12.Caption := strCalcCapt18 + GetNameUOM(F_NormBase.FUOM, true, true);
  Label35.Caption := strCalcCapt15 + GetNameUOM(F_NormBase.FUOM, true, true);
  Label45.Caption := strCalcCapt14 + GetNameUOM(F_NormBase.FUOM, true, false);
  Label33.Caption := strCalcCapt16 + GetNameUOM(F_NormBase.FUOM, true, true);
  Label24.Caption := strCalcCapt17 + GetNameUOM(F_NormBase.FUOM, true, true);
  Label59.Caption := strCalcCapt19 + GetNameUOM(F_NormBase.FUOM, true, true);
  Label38.Caption := GetNameUOM(F_NormBase.FUOM, true, false);
  Label70.Caption := strCalcCapt23 + GetNameUOM(F_NormBase.FUOM, true, false)+ strCalcCapt24; 
  ///таблички
  rashod.Caption := strCalcCapt20 + GetNameUOM(F_NormBase.FUOM, true, false)+strCalcCapt21;
  CableCanalGrid_Price.Caption := strCalcCapt22  + GetNameUOM(F_NormBase.FUOM, true, false);
  Cable_Grid_Price.Caption := strCalcCapt22  + GetNameUOM(F_NormBase.FUOM, true, false);

end;

end.
