unit MainUnit;

interface

uses
  Messages, SysUtils, Variants, Classes, Graphics, Windows, dateUtils,
  Controls, Forms, Dialogs, DeviceRd,
  AdvOfficeStatusBar, Menus, AdvMenus, XPMan, ExtCtrls, AdvPanel,
  ComCtrls, AdvPageControl, AdvGlowButton, AdvPicture, ActnList, StdCtrls,
  DBAdvGrid, DBCtrls, AdvEdit, Spin, StdActns, DB, AdvMemo,
  AdvDateTimePicker, DBAdvMemo, DBAdvLst, TeeProcs, TeEngine, Chart, DBChart,
  AdvGroupBox, Grids, BaseGrid, AdvGrid, AdvListV, ExtActns, ToolPanels,
  MySQLUniProvider, Uni, DBAccess, MemDS, AdvOfficeButtons, Series, AdvEdBtn, Mask, AdvSpin,
  AdvCombo, Lucombo, OleServer, ExcelXP, ComObj, user_types, class_patinet;

type
  TMainForm = class(TForm)
    Main_Menu: TAdvMainMenu;
    StatusBar: TAdvOfficeStatusBar;
    N1: TMenuItem;
    N2: TMenuItem;
    N3: TMenuItem;
    N4: TMenuItem;
    N5: TMenuItem;
    N6: TMenuItem;
    N8: TMenuItem;
    N9: TMenuItem;
    N10: TMenuItem;
    XPMan: TXPManifest;
    N11: TMenuItem;
    ActionList: TActionList;
    GoToNewMeasure: TAction;
    GoToLookResults: TAction;
    ImageFileOpen: TOpenPicture;
    Show_all_pat: TAction;
    new_patient: TAction;
    del_patient: TAction;
    red_patient: TAction;
    look_res_load_data: TAction;
    look_res_show_15: TAction;
    look_res_show_max: TAction;
    look_res_show_min: TAction;
    look_res_show_mean: TAction;
    look_res_hide_15: TAction;
    look_res_hide_max: TAction;
    look_res_hide_min: TAction;
    look_res_hide_mean: TAction;
    Begin_izm: TAction;
    MainPanel: TPanel;
    look_res_panel: TPanel;
    look_results_DB_Grid: TDBAdvGrid;
    look_results_pc: TAdvPageControl;
    look_results_choose_info_page: TAdvTabSheet;
    look_res_enter_panel: TPanel;
    look_res_choise_izm_label: TLabel;
    look_res_choise_opis_label: TLabel;
    look_res_choise_izm: TListView;
    look_res_info_panel: TPanel;
    look_res_choise_otch_znach: TLabel;
    look_res_choise_info_capt_label: TLabel;
    look_res_choise_fam: TLabel;
    look_res_choise_name: TLabel;
    look_res_choise_otch: TLabel;
    look_res_choise_date: TLabel;
    look_res_choise_prim: TLabel;
    look_res_choise_fam_znach: TLabel;
    look_res_choise_name_znach: TLabel;
    look_res_choise_izm_num: TLabel;
    look_res_choise_izm_kol: TLabel;
    look_res_choise_date_znach: TLabel;
    look_results_number_page: TAdvTabSheet;
    look_results_graphics_page: TAdvTabSheet;
    look_res_graph_params_GB: TAdvGroupBox;
    look_res_graph_points_GB: TAdvGroupBox;
    look_res_graph_points_forw: TButton;
    look_res_graph_points_back: TButton;
    look_results_diagnoz_page: TAdvTabSheet;
    New_izm_Panel: TPanel;
    New_izm_DB_Grid: TDBAdvGrid;
    New_izm_Add_pat: TAdvGlowButton;
    New_izm_red_pat: TAdvGlowButton;
    New_izm_del_pat: TAdvGlowButton;
    New_izm_pc: TAdvPageControl;
    izm_tab: TAdvTabSheet;
    New_izm_info_panel: TPanel;
    new_izm_pat_title_label: TLabel;
    new_izm_fam_label: TLabel;
    new_izm_name_label: TLabel;
    new_izm_otch_label: TLabel;
    new_izm_date_label: TLabel;
    new_izm_prim_label: TLabel;
    new_izm_fam_znach: TLabel;
    new_izm_name_znach: TLabel;
    new_izm_otch_znach: TLabel;
    new_izm_kol_label: TLabel;
    new_izm_kol_znach: TLabel;
    new_izm_date_znach: TLabel;
    new_izm_pat_id: TLabel;
    new_izm_warning_label: TLabel;
    new_izm_look_red_btn: TAdvGlowButton;
    new_izm_begin_izm_btn: TAdvGlowButton;
    New_izm_red_panel: TPanel;
    new_izm_prim_edit_label: TLabel;
    new_izm_fam_edit: TAdvEdit;
    new_izm_name_edit: TAdvEdit;
    new_izm_otch_edit: TAdvEdit;
    new_izm_save_btn: TAdvGlowButton;
    new_izm_reset_btn: TAdvGlowButton;
    izm_set_tab: TAdvTabSheet;
    top_panel: TAdvPanel;
    new_measure_btn: TAdvGlowButton;
    look_results_btn: TAdvGlowButton;
    new_izm_edit_memo: TMemo;
    Label1: TLabel;
    look_res_izm_description: TLabel;
    look_res_point_CB: TComboBox;
    look_res_graph_points_label: TLabel;
    look_res_point_num_label: TLabel;
    N12: TMenuItem;
    N13: TMenuItem;
    N14: TMenuItem;
    look_res_graph_options_GB: TAdvGroupBox;
    look_res_graph_options_15_CB: TCheckBox;
    look_res_graph_options_15_color: TShape;
    look_res_graph_options_max_color: TShape;
    look_res_graph_options_min_color: TShape;
    look_res_graph_options_average_color: TShape;
    look_res_diagnoz_info_panel: TAdvPanel;
    look_res_diagnoz_PC: TAdvPageControl;
    look_res_diagnoz_data_page: TAdvTabSheet;
    look_res_diagnoz_koeff_page: TAdvTabSheet;
    look_res_diagnoz_help_page: TAdvTabSheet;
    look_res_fio_capt_label: TLabel;
    look_res_iznmname_capt_label: TLabel;
    look_res_izm_capt_label: TLabel;
    look_res_fio_label: TLabel;
    look_res_izm_name_label: TLabel;
    look_res_izm_about_label: TLabel;
    look_res_diagnoz_data_top_panel: TPanel;
    look_res_diagnoz_DBPoints_panel: TPanel;
    look_res_diagnoz_data_panel: TPanel;
    look_res_diagnoz_data_bottom_panel: TPanel;
    look_res_diagnoz_data_name_label: TLabel;
    look_res_diagnoz_data_znach_label: TLabel;
    look_res_diagnoz_data_unit_label: TLabel;
    look_res_diagnoz_help_StringGrid: TAdvStringGrid;
    ColorDialog: TColorDialog;
    look_res_diagnoz_koeff_pat_shape2: TShape;
    look_res_diagnoz_koeff_neus_shape1: TShape;
    look_res_diagnoz_koeff_norma_shape: TShape;
    look_res_diagnoz_koeff_neus_shape2: TShape;
    look_res_diagnoz_koeff_pat_shape1: TShape;
    look_res_diagnoz_koeff_l1: TLabel;
    look_res_diagnoz_koeff_l2: TLabel;
    look_res_diagnoz_koeff_point1: TLabel;
    look_res_diagnoz_koeff_point2: TLabel;
    look_res_diagnoz_koeff_point3: TLabel;
    look_res_diagnoz_koeff_point4: TLabel;
    look_res_diagnoz_koeff_point5: TLabel;
    look_res_diagnoz_koeff_point6: TLabel;
    look_res_diagnoz_koeff_diagnoz_shape: TShape;
    look_res_diagnoz_koeff_l3: TLabel;
    look_res_diagnoz_koeff_l4: TLabel;
    look_res_diagnoz_koeff_l5: TLabel;
    look_res_diagnoz_koeff_l6: TLabel;
    look_res_diagnoz_koeff_l7: TLabel;
    look_res_diagnoz_koeff_top_panel: TPanel;
    look_res_diagnoz_koeff_bottom_panel: TPanel;
    look_res_make_report_btn: TAdvGlowButton;
    look_res_diagnoz_data_StringGrid: TAdvStringGrid;
    look_res_diagnoz_points_table_switch: TRadioButton;
    look_res_diagnoz_koeffs_table_switch: TRadioButton;
    checkTimer: TTimer;
    look_res_choise_load_data: TAdvGlowButton;
    del_izm: TAction;
    N15: TMenuItem;
    N16: TMenuItem;
    N17: TMenuItem;
    look_res_graph_chart: TChart;
    look_res_graph_choose: TAdvOfficeRadioGroup;
    look_res_graph_izm_id_CB: TComboBox;
    look_res_choise_memo: TDBAdvMemo;
    Izm_to_base_cb: TCheckBox;
    Izm_null_result_CB: TCheckBox;
    izm_write_ui: TCheckBox;
    izm_manual_switch: TCheckBox;
    new_izm_date_picker: TAdvMaskEdit;
    look_res_log_scale_CB: TCheckBox;
    look_res_log_scale: TAdvSpinEdit;
    look_res_choise_method_CB: TLUCombo;
    look_res_choise_koeffs_CB: TLUCombo;
    look_res_graph_options_max_CB: TCheckBox;
    Label2: TLabel;
    look_res_graph_options_min_CB: TCheckBox;
    look_res_graph_options_average_CB: TCheckBox;
    Label3: TLabel;
    look_res_graph_options_15_all_CB: TCheckBox;
    look_res_graph_options_15_all_color: TShape;
    look_res_graph_options_max_all_CB: TCheckBox;
    look_res_graph_options_max_all_color: TShape;
    look_res_graph_options_min_all_CB: TCheckBox;
    look_res_graph_options_min_all_color: TShape;
    look_res_graph_options_average_all_CB: TCheckBox;
    look_res_graph_options_average_all_color: TShape;
    Panel1: TPanel;
    Panel2: TPanel;
    look_res_graph_izm_CB: TLUCombo;
    look_res_graph_izm_desc: TLabel;
    look_res_choise_R_CB: TLUCombo;
    look_res_graph_data_DBGrid: TAdvStringGrid;
    look_res_numbers_filter_GB: TAdvGroupBox;
    look_res_number_filter_param_CB: TLUCombo;
    look_res_number_filter_point_CB: TLUCombo;
    look_res_number_filter_options_RG: TAdvOfficeRadioGroup;
    look_res_number_filter_genparam_CB: TCheckBox;
    look_res_number_genparam_panel: TAdvPanel;
    look_res_number_izm_info_GB: TAdvGroupBox;
    Label4: TLabel;
    Label5: TLabel;
    Label6: TLabel;
    Label7: TLabel;
    Label8: TLabel;
    look_res_diagnoz_numbers_grid: TAdvStringGrid;
    Label9: TLabel;
    Label10: TLabel;
    Label11: TLabel;
    Label12: TLabel;
    look_res_number_izm_CB: TLUCombo;
    look_res_number_fio_label: TLabel;
    look_res_number_izm_label: TLabel;
    look_res_number_desc_label: TLabel;
    look_res_number_izm_id_CB: TComboBox;
    look_res_del_izm: TAdvGlowButton;
    CheckBox1: TCheckBox;
    Button1: TButton;
    new_izm_DBMemo_prim: TMemo;
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure checkTimerTimer(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure GoToNewMeasureExecute(Sender: TObject);
    procedure GoToLookResultsExecute(Sender: TObject);
    procedure New_izm_pcChanging(Sender: TObject; var AllowChange: Boolean);
    procedure Show_all_patExecute(Sender: TObject);
    Procedure Col_resize(grid:TDBAdvGrid; name,header:string; width:integer);
    procedure New_izm_DB_GridSelectCell(Sender: TObject; ACol, ARow: Integer;
      var CanSelect: Boolean);
    procedure new_patientExecute(Sender: TObject);
    procedure enable_disable_new_izm_controls(dir:boolean);
    procedure new_izm_reset_btnClick(Sender: TObject);
    procedure new_izm_save_btnClick(Sender: TObject);
    procedure del_patientExecute(Sender: TObject);
    procedure red_patientExecute(Sender: TObject);
    procedure look_results_DB_GridSelectCell(Sender: TObject; ACol,
      ARow: Integer; var CanSelect: Boolean);
    procedure look_res_choise_izmExit(Sender: TObject);
    procedure look_res_load_dataExecute(Sender: TObject);
    procedure create_series(name,num,izm_num:string; x_array:array of integer;
        scale:extended);
    procedure look_res_graph_chooseClick(Sender: TObject);
    procedure look_res_show_15Execute(Sender: TObject);
    procedure new_izm_look_red_btnClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure N10Click(Sender: TObject);
    procedure Begin_izmExecute(Sender: TObject);
    procedure New_izm_DB_GridDblClickCell(Sender: TObject; ARow, ACol: Integer);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure New_izm_DB_GridUpdateColumnSize(Sender: TObject; ACol: Integer;
      var AWidth: Integer);
    procedure look_res_choise_izmDblClick(Sender: TObject);
    procedure look_res_graph_points_forwClick(Sender: TObject);
    procedure look_res_graph_points_backClick(Sender: TObject);
    procedure make_point_active(num:integer);
    procedure look_res_point_CBChange(Sender: TObject);
    procedure N12Click(Sender: TObject);
    procedure N13Click(Sender: TObject);
    procedure look_res_diagnoz_data_StringGridGetCellBorderProp(Sender: TObject;
      ARow, ACol: Integer; LeftPen, TopPen, RightPen, BottomPen: TPen);
    procedure look_res_diagnoz_data_StringGridGetAlignment(Sender: TObject;
      ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment);
    procedure look_res_diagnoz_data_StringGridGetDisplText(Sender: TObject;
      ACol, ARow: Integer; var Value: string);
    procedure look_res_diagnoz_points_table_switchClick(Sender: TObject);
    procedure look_res_diagnoz_koeffs_table_switchClick(Sender: TObject);
    procedure del_izmExecute(Sender: TObject);
    function Get_R (point:string; measure:string; type_of:integer):string;
    procedure look_res_diagnoz_data_StringGridGetFloatFormat(Sender: TObject;
      ACol, ARow: Integer; var IsFloat: Boolean; var FloatFormat: string);
    procedure N17Click(Sender: TObject);
    procedure New_izm_DB_GridGetCellBorderProp(Sender: TObject; ARow,
      ACol: Integer; LeftPen, TopPen, RightPen, BottomPen: TPen);
    procedure New_izm_DB_GridGetCellBorder(Sender: TObject; ARow, ACol: Integer;
      APen: TPen; var Borders: TCellBorders);
    procedure look_results_DB_GridGetCellBorder(Sender: TObject; ARow,
      ACol: Integer; APen: TPen; var Borders: TCellBorders);
    procedure look_results_DB_GridGetCellBorderProp(Sender: TObject; ARow,
      ACol: Integer; LeftPen, TopPen, RightPen, BottomPen: TPen);
    procedure new_izm_fam_editKeyPress(Sender: TObject; var Key: Char);
    procedure new_izm_name_editKeyPress(Sender: TObject; var Key: Char);
    procedure new_izm_otch_editKeyPress(Sender: TObject; var Key: Char);
    procedure new_izm_date_pickerKeyPress(Sender: TObject; var Key: Char);
    procedure New_izm_DB_GridKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure look_results_DB_GridKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure look_res_graph_chartClickSeries(Sender: TCustomChart;
      Series: TChartSeries; ValueIndex: Integer; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure look_res_log_scale_CBClick(Sender: TObject);
    function Sign(X:Extended):Integer;
    function In_power (x:extended; n:extended):extended;
    procedure look_res_log_scaleChange(Sender: TObject);
    function get_average_point():extended;
    function get_average_point_all():extended;
    procedure look_res_graph_options_average_CBClick(Sender: TObject);
    procedure look_res_graph_options_15_all_CBClick(Sender: TObject);
    procedure look_res_graph_options_average_all_CBClick(Sender: TObject);
    function get_max_min_point(sw:integer):extended;
    function get_max_min_point_all(sw:integer):extended;
    procedure delete_series(chart:TChart; name:string);
    procedure look_res_graph_options_max_CBClick(Sender: TObject);
    procedure create_series_point(chart:TChart; name_ser,type_of:string);
    procedure create_series_all(chart:TChart; name_ser,type_of:string);
    procedure look_res_graph_options_min_CBClick(Sender: TObject);
    procedure look_res_graph_options_max_all_CBClick(Sender: TObject);
    procedure look_res_graph_options_min_all_CBClick(Sender: TObject);
    procedure look_res_graph_izm_CBChange(Sender: TObject);
    procedure look_res_choise_izmSelectItem(Sender: TObject; Item: TListItem;
      Selected: Boolean);
    procedure look_res_graph_data_DBGridGetAlignment(Sender: TObject; ARow,
      ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment);
    procedure load_number_grid(izm_num:string);
    procedure look_results_pcChange(Sender: TObject);
    procedure look_res_make_report_btnClick(Sender: TObject);
    procedure look_res_number_filter_genparam_CBClick(Sender: TObject);
    procedure look_res_number_izm_CBChange(Sender: TObject);
    procedure look_res_number_fio_labelMouseEnter(Sender: TObject);
    procedure look_res_number_fio_labelMouseLeave(Sender: TObject);
    procedure look_res_fio_labelMouseEnter(Sender: TObject);
    procedure look_res_fio_labelMouseLeave(Sender: TObject);
    procedure look_res_fio_labelClick(Sender: TObject);
    procedure load_info_to_diagnoz_tables(create_files:boolean);
    procedure check_right_number_of_string_in_table;
    //procedure (izm_num:string)
  private
    { Private declarations }
  public
    var  device:   TDevice;{ Public declarations }
    patient:          TPatient;
    patient_info:     TPatinet_record;
  end;



Const NUMBER_OF_PARAMS=7;
      NUMBER_OF_POINTS=24;
      NUMBER_OF_REPEAT=5;
var
  MainForm: TMainForm;
  db_grid_cur_row_num:integer; //текцщий номер строки в гриде
  lock_pc:boolean;  //переменная включающая режим блокирования изменения всех pageconrol'ov
  act:string;   //действие для кнопки сохранить
                //варианты - сохранение и обновление
  db_grid_wid: array[0..8] of integer;
  gARow, gACol: integer; //текущие строка и столбец в таблице
  koeff: array [0..number_of_params] of extended; //массив коэфициентов для сжатия графика
  scales: array [0..number_of_params] of extended; //массив коэффициентов для уменьшения порядка
  resized: array [0..number_of_params] of boolean; //массив фактов сжатия графиков
  look_res_act_page: integer; //активная вкладка просмотре результатов

  
implementation
uses DataUnit, ConstUnit, IzmUnit, AdminUnit, AboutUnit;



{$R *.dfm}
//////////////////////////////////////////////////
/// ОБЩИЕ ПРОЦЕДУРЫ ФОРМЫ                       //
//////////////////////////////////////////////////
procedure TMainForm.checkTimerTimer(Sender: TObject);
begin
//Проверка на подключение к базе
if SQL_DM.mysql_con.Connected then
  begin
    MainForm.StatusBar.Panels[ 0 ].Text := status_bar_database_connection_exisits;
    MainForm.Enabled := TRUE;
  end
else
  begin
    MainForm.StatusBar.Panels[0].Text := status_bar_database_connection_not_exisits;
    MainForm.Enabled := FALSE;
  end;

//проверка на подключение к прибору
if Device.IsConnected then
  begin
     MainForm.StatusBar.Panels[ 5 ].Text := status_bar_device_connected;
     if ( New_izm_pc.ActivePageIndex = 0 ) then
        begin
             new_izm_warning_label.Hide;
             new_izm_begin_izm_btn.Enabled := TRUE;
        end;
  end
else
  begin
    MainForm.StatusBar.Panels[ 5 ].Text := status_bar_device_not_connected;
    if ( New_izm_pc.ActivePageIndex = 0 ) then
        begin
             new_izm_warning_label.Show;
             new_izm_begin_izm_btn.Enabled := FALSE;
        end;
  end;
end;

procedure TMainForm.check_right_number_of_string_in_table;
begin
//проверяем количество пациентов, если равно 0 то запрещаем действия
// редактирования и удаления
if ( New_izm_DB_Grid.RowCount = 2 ) then
  if ( New_izm_DB_Grid.Cells[ 1, 1 ] = '' ) then
      begin
         New_izm_red_pat.Enabled := FALSE;
         New_izm_del_pat.Enabled := FALSE;
         new_izm_begin_izm_btn.Enabled := FALSE;
      end;
end;

procedure TMainForm.FormShow(Sender: TObject);
begin
  act := '';
  //по умолчанию активен режим измерений
  MainForm.GoToNewMeasure.Execute;
  //проверяем устройство, в случае неподключения - показываем предупреждение
  // и делаем недоступным начинание нового измерения
  if not Device.IsConnected then
  begin
    new_izm_begin_izm_btn.Enabled := FALSE;
    new_izm_warning_label.Show;
  end;

  check_right_number_of_string_in_table;

  //Получаем количество проведенных иссдедований
  mysql_query(SQL_DM.mysql_query1, 'SELECT Count(*) FROM `'+table_izm_name + ';', 1 );
  MainForm.StatusBar.Panels[ 1 ].Text:=
  status_bar_number_of_measurments + SQL_DM.mysql_DSQ1.DataSet.FieldByName( 'Count(*)' ).AsString;
end;

procedure TMainForm.GoToLookResultsExecute(Sender: TObject);
begin
//доступность кнопок
MainForm.look_results_btn.Down := TRUE;
MainForm.new_measure_btn.Down := FALSE;

//видимость панелей и таблиц
look_res_panel.Show;
look_results_DB_Grid.Show;

New_izm_DB_Grid.SearchFooter.Visible := FALSE;
New_izm_Panel.Hide;
New_izm_DB_Grid.Hide;

look_results_DB_Grid.SearchFooter.Visible := TRUE;

//вкладки pagecontrol'a недоступны
look_results_pc.Pages[1].TabVisible := FALSE;
look_results_pc.Pages[2].TabVisible := FALSE;
look_results_pc.Pages[3].TabVisible := FALSE;

//Обновляем скроллы в мемо: все равно не отрисовывается(((
look_res_choise_memo.RefreshMemo;

//показываем всех пациентов
MainForm.Show_all_pat.Execute;
end;

procedure TMainForm.GoToNewMeasureExecute(Sender: TObject);
begin
  //доступность кнопок
  MainForm.look_results_btn.Down := FALSE;
  MainForm.new_measure_btn.Down := TRUE;

  //видимость панелей и таблиц
  look_res_panel.Hide;
  look_results_DB_Grid.Hide;

  look_results_DB_Grid.SearchFooter.Visible := FALSE;

  New_izm_Panel.Show;
  New_izm_DB_Grid.Show;

  New_izm_red_panel.Hide;

  //Обновляем скроллы в мемо: все равно не отрисовывается(((
  new_izm_edit_memo.Refresh;


  //проверяем устройство
  if ( not Device.IsConnected ) then
  begin
    new_izm_begin_izm_btn.Enabled := FALSE;
    new_izm_warning_label.Show;
  end;

  //показываем всех пациентов
  MainForm.Show_all_pat.Execute;

  New_izm_DB_Grid.SearchFooter.Visible := TRUE;
end;

//переход в режим продвинутого пользователя
procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
 begin
   if ( ( GetKeyState( VK_CONTROL ) AND 128 ) = 128 ) and
      ( ( GetKeyState( VK_MENU )    AND 128 ) = 128) and
      ( ( GetKeyState( VK_SHIFT )   AND 128 ) = 128) and
      ( ( GetKeyState( VK_F5 )      AND 128 ) = 128 )
     then
       ShowMessage( 'CTRL+Alt+Shift+F5 Pressed' );
  //при нажатии Crtl+Tab переходить между режимами просмотра и измерений
{If ((GetKeyState(VK_CONTROL) AND 128)=128) and
   ((GetKeyState(VK_TAB)     AND 128)=128)
   then
  begin

       if look_results_btn.Down then GoToNewMeasure.Execute
  else if new_measure_btn.Down then GoToLookResults.Execute;
    end;}
 end;

procedure TMainForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
//при нажатии Esc
if ( Key = #27 ) then
  //если находимся в редактировании пациента, то переходим обратно в просмотр
  if ( ( act <> '' ) and ( new_measure_btn.Down ) ) then
    enable_disable_new_izm_controls( TRUE );
end;

procedure TMainForm.FormCreate(Sender: TObject);
begin
  //создание экземпляра класса устройства для дальнейшей с ним работы
  Device := DeviceRD.TDevice.Create;
  // проверяем подключено ли устройство и если да, то открываем его
  if Device.IsConnected then
  begin
    Device.Open_device;
    Device.Start_waiting( 1 );
  end;

  //Создаем класс пациента с которым будем работать
  Patient := TPatient.Create;

  //задаем ширины колонок в таблицах информации о пользователях
  db_grid_wid[1] := 20;
  db_grid_wid[2] := 120;
  db_grid_wid[3] := 120;
  db_grid_wid[4] := 120;
  db_grid_wid[5] := 40;
  db_grid_wid[6] := 40;
  db_grid_wid[7] := 40;
  db_grid_wid[8] := 110;

  // загружаем информацию в таблицы справочной информации по методике Риодораку
  load_info_to_diagnoz_tables(FALSE);

  //задаем коэффициенты сжатия для графика
  koeff[0] := 5;
  koeff[1] := 7;
  koeff[2] := 9;
  koeff[3] := 11;
  koeff[4] := 9;
  koeff[5] := 11;
  koeff[6] := 5;
  //koeff[7]:=;


  //коэффициенты размерности
  scales[0] := 1E6;
  scales[1] := 1E-6;
  scales[2] := 1E-6;
  scales[3] := 1E-6;
  scales[4] := 1;
  scales[5] := 1E-9;
  scales[6] := 1;
//scales[7]:=;

  resized[0] := FALSE;
  resized[1] := FALSE;
  resized[2] := FALSE;
  resized[3] := FALSE;
  resized[4] := FALSE;
  resized[5] := FALSE;
  resized[6] := FALSE;
//resized[7] := FALSE;

end;

//главное меню
procedure TMainForm.N10Click(Sender: TObject);
begin
MainForm.Close;
end;
procedure TMainForm.N12Click(Sender: TObject);
begin
AdminForm.admin_db_cur_table := 'points';
AdminForm.ShowModal;
end;
procedure TMainForm.N13Click(Sender: TObject);
begin
AdminForm.admin_db_cur_table := 'params';
AdminForm.ShowModal;
end;
procedure TMainForm.N17Click(Sender: TObject);
begin
AboutBox.ShowModal;
end;



//пользовательские процедуры
procedure TMainForm.Col_resize(grid:TDBAdvGrid; name,header:string; width:integer);
begin
  grid.ColumnByFieldName[ name ].Width := width;
  grid.ColumnByFieldName[ name ].Header := header;
  grid.ColumnByFieldName[ name ].HeaderAlignment := taCenter;
  grid.ColumnByFieldName[ name ].Alignment := taCenter;
end;

////////////////////////////////////
/// Процедуры Нового измерения   ///
////////////////////////////////////
//начало измерения
procedure TMainForm.Begin_izmExecute(Sender: TObject);
begin
//в случае если устройство подключено
if Device.IsConnected then
begin
//называем форму измерений
   IzmForm.Caption:=izm_form_name;
   IzmForm.Izm_condition_label.Caption:=izm_device_ready;

  //запускаем поток
    Device.Start_waiting( 2 );
   //показываем форму измерений
   IzmForm.Update;
   IzmForm.ShowModal;
end;
end;

//Переход к просмотру результатов из информации о пользователе
procedure TMainForm.new_izm_look_red_btnClick(Sender: TObject);
begin
  //если результат 1 то напрямую на просмотр
  //если много, то на страницу выбора измерения
  if ( strtoint ( Patient.Get_current_patient_measure_count ) > 1 ) then
  begin
    //выбираем нужного пользователя
    GoToLookResults.Execute;
  end
  else
  begin
    with look_res_choise_izm do begin
      Items.clear;
      Items.Add;
      Items[ 0 ].Caption:=Patient.Get_current_patient_measures_array[ 0 ].date;
      Items[ 0 ].SubItems[ 0 ]:=Patient.Get_current_patient_measures_array[ 0 ].ID;
      Items[ 0 ].Selected := TRUE;
    end;
    //грузим информацию
    MainForm.look_res_load_data.Execute;
  end;
end;

//переход фокуса при вводе и редактировании пациентов
procedure TMainForm.new_izm_fam_editKeyPress(Sender: TObject; var Key: Char);
begin
  if ( Key = #13 ) then
  begin
    new_izm_name_edit.SetFocus;
  end;
end;
procedure TMainForm.new_izm_name_editKeyPress(Sender: TObject; var Key: Char);
begin
  if ( key = #13 ) then
  begin
    new_izm_otch_edit.SetFocus;
  end;
end;
procedure TMainForm.new_izm_otch_editKeyPress(Sender: TObject; var Key: Char);
begin
  if ( key = #13 ) then
  begin
    new_izm_date_picker.SetFocus;
  end;
end;
procedure TMainForm.new_izm_date_pickerKeyPress(Sender: TObject; var Key: Char);
begin
  if (key = #13) then
  begin
    new_izm_edit_memo.SetFocus;
  end;
end;
//служебные запрещающие процедуры
procedure TMainForm.New_izm_pcChanging(Sender: TObject; var AllowChange: Boolean);
begin
  if ( lock_pc ) then
    begin
      AllowChange := FALSE;
    end;
end;

//загрузка информации о всех пациентах
procedure TMainForm.Show_all_patExecute(Sender: TObject);
var sel:boolean;
begin
  mysql_query( SQL_DM.mysql_query2, 'SELECT * FROM ' + table_patient_name + ';', 1 );
  sel := TRUE;
  //загрузка дааных в таблицу в зависимости от того, какая из них видна
  if New_izm_DB_Grid.Visible then
    begin
      New_izm_DB_Grid.DataSource:=SQL_DM.mysql_DSQ2;
      Col_resize(New_izm_DB_Grid, 'id', new_izm_num_name, db_grid_wid[ 1 ] );
      Col_resize(New_izm_DB_Grid, 'fam', new_izm_fam_name, db_grid_wid[ 2 ] );
      Col_resize(New_izm_DB_Grid, 'name', new_izm_name_name, db_grid_wid[ 3 ] );
      Col_resize(New_izm_DB_Grid, 'otch', new_izm_otch_name, db_grid_wid[ 4 ] );
      Col_resize(New_izm_DB_Grid, 'day', new_izm_day_name, db_grid_wid[ 5 ] );
      Col_resize(New_izm_DB_Grid, 'mon', new_izm_mon_name, db_grid_wid[ 6 ] );
      Col_resize(New_izm_DB_Grid, 'year', new_izm_year_name, db_grid_wid[ 7 ] );
      Col_resize(New_izm_DB_Grid, 'opisanie', new_izm_opis_name, db_grid_wid[ 8 ] );

      New_izm_DB_Grid.Enabled:=TRUE;
      //выбираем нужную запись в таблице
      New_izm_DB_Grid.GotoCell( 1, patient.table_string_num );
      New_izm_DB_GridSelectCell( self, 1, patient.table_string_num, sel );
  end
else if look_results_DB_Grid.Visible then
  begin
    look_results_DB_Grid.DataSource:=SQL_DM.mysql_DSQ2;
    
    Col_resize( look_results_DB_Grid, 'id', new_izm_num_name, db_grid_wid[ 1 ] );
    Col_resize( look_results_DB_Grid, 'fam', new_izm_fam_name, db_grid_wid[ 2 ] );
    Col_resize( look_results_DB_Grid, 'name', new_izm_name_name, db_grid_wid[ 3 ] );
    Col_resize( look_results_DB_Grid, 'otch', new_izm_otch_name, db_grid_wid[ 4 ] );
    Col_resize( look_results_DB_Grid, 'day', new_izm_day_name, db_grid_wid[ 5 ] );
    Col_resize( look_results_DB_Grid, 'mon', new_izm_mon_name, db_grid_wid[ 6 ] );
    Col_resize( look_results_DB_Grid, 'year', new_izm_year_name, db_grid_wid[ 7 ] );
    Col_resize( look_results_DB_Grid, 'opisanie', new_izm_opis_name, db_grid_wid[ 8 ] );

    look_results_DB_Grid.Enabled:=TRUE;
    //выбираем первую запись
    look_results_DB_Grid.GotoCell( 1, patient.table_string_num );
    look_results_DB_GridSelectCell( self, 1, patient.table_string_num, sel );
  end;
end;

/// Служебные процедуры для таблицы
procedure TMainForm.New_izm_DB_GridGetCellBorder(Sender: TObject; ARow,
  ACol: Integer; APen: TPen; var Borders: TCellBorders);
begin
if ( act = SAVE_ACTION_UPDATE ) then
  if ( ARow = Patient.table_string_num ) then
  begin
    APen.Width := 2;
    if ( ACol <> 0 ) then
    begin
      Borders := [ cbTop, cbBottom];
    end;
    if ( ACol = 1 ) then
    begin
      Borders:=[ cbLeft, cbTop, cbBottom ];
    end
    else if ( ACol = 8 )  then
      begin
        Borders := [ cbRight, cbTop, cbBottom ];
      end;
  end;
end;
procedure TMainForm.New_izm_DB_GridGetCellBorderProp(Sender: TObject; ARow,
  ACol: Integer; LeftPen, TopPen, RightPen, BottomPen: TPen);
begin
 LeftPen.Color := clRed;
 RightPen.Color := clRed;
 BottomPen.Color := clRed;
 TopPen.Color := clRed;
end;
procedure TMainForm.New_izm_DB_GridUpdateColumnSize(Sender: TObject;
  ACol: Integer; var AWidth: Integer);
var
  i,wid: Integer;
begin
  wid:=0;

  for i := 0 to New_izm_DB_Grid.ColCount - 1 do
    wid := wid + New_izm_DB_Grid.ColWidths[ i ];

  if ( wid > New_izm_DB_Grid.Width - New_izm_Add_pat.Width - 25 ) then
    AWidth := db_grid_wid[ ACol ];
end;
procedure TMainForm.New_izm_DB_GridDblClickCell(Sender: TObject; ARow,
  ACol: Integer);
var sel:boolean;
begin
  sel := TRUE;
  MainForm.New_izm_DB_GridSelectCell( self, Acol, ARow, sel );
  MainForm.red_patient.Execute;
end;

//обновление
procedure TMainForm.New_izm_DB_GridKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
     if (GetKeyState(vk_f5) AND 128)=128 then
        begin
             Show_all_pat.Execute;
        end;
end;

//выбор пациента
procedure TMainForm.New_izm_DB_GridSelectCell(Sender: TObject; ACol,
  ARow: Integer; var CanSelect: Boolean);
begin
if ( MainForm.New_izm_DB_Grid.Cells[ 1, Arow ] <> '' ) then
  begin
   //Доступны кнопки редактирования и удаления
   New_izm_red_pat.Enabled := TRUE;
   New_izm_del_pat.Enabled := TRUE;

   with Patient do
    begin
      Set_current_patient_by_id( New_izm_DB_Grid.Cells[ 1, Arow ] );

      //фамилия имя отчество
      new_izm_fam_znach.Caption := Get_current_patient_sirname;
      new_izm_name_znach.Caption :=Get_current_patient_first_name;
      new_izm_otch_znach.Caption :=Get_current_patient_middle_name;
      //дата рождения
      MainForm.new_izm_date_znach.Caption := make_date( Get_current_patient_birth_day,
                                                        Get_current_patient_birth_month,
                                                        Get_current_patient_birth_year);
      //примечания:
      new_izm_DBMemo_prim.Lines := Get_current_patient_description;
      //количество измерений
      new_izm_kol_znach.Caption := Get_current_patient_measure_count;
      //номер в табличке
      table_string_num := ARow;
    end;

// в зависимости от количества приведенных измерений
   //активируем просмотр результатов
   if ( strtoint( Patient.Get_current_patient_measure_count ) > 0 ) then
      begin
        new_izm_look_red_btn.Enabled := TRUE;
      end
   else
      begin
        new_izm_look_red_btn.Enabled := FALSE;
      end;

   // позволяеем запустить новое измерение
   if Device.IsConnected then
      begin
        new_izm_begin_izm_btn.Enabled := TRUE;
      end
   else
      begin
        new_izm_begin_izm_btn.Enabled := FALSE;
      end;
  end;
end;

//действия над пациентами
procedure TMainForm.new_patientExecute(Sender: TObject);
begin
  //открываем панель редактирования
  enable_disable_new_izm_controls( FALSE );
  //устанавливаем действие в положение добавления информации
  act := SAVE_ACTION_ADD;
  //фокус на поле ввода фамилии
  new_izm_fam_edit.SetFocus;
  // номер строчки в таблице, ВНИМАНИЕ присваивается RowCount без вычитания 1!
  // это нормально, поскольку потом станет на 1 ряд больше
  patient.table_string_num := New_izm_DB_Grid.RowCount;

end;
procedure TMainForm.red_patientExecute(Sender: TObject);
var str: string;
begin
  //доступная только панель ввода
  enable_disable_new_izm_controls( FALSE );

  //Действие кнопки сохранить - обновление
  act := SAVE_ACTION_UPDATE;
  with patient do
  begin
    //Переносим значения полей
    new_izm_fam_edit.Text := Get_current_patient_sirname;
    new_izm_name_edit.Text := Get_current_patient_first_name;
    new_izm_otch_edit.Text := Get_current_patient_middle_name;

    //для даты: удаляем "г."
    str := new_izm_date_znach.Caption;
    delete( str, length( str ) - 1, 2);
    new_izm_date_picker.text := str;

    //мемо - комментарии
    new_izm_edit_memo.Lines := Get_current_patient_description;

    new_izm_fam_edit.SetFocus;

    // номер строчки в таблице
    patient.table_string_num := New_izm_DB_Grid.SelectedRow[0];
  end;
end;
procedure TMainForm.del_patientExecute(Sender: TObject);
var patient_delete_success:boolean;
begin
  //удаление пациента
  if MessageBox(0,
               PChar(del_patient_question_mes),
               PChar(mess_caption),
               MB_ICONQUESTION or MB_OKCANCEL
              ) = mrOK then
  begin
    //удаление пациента
    patient_delete_success := patient.Delete_current_patient;
    if patient_delete_success then
    begin
      //ставим указатель на начало таблицы
      Patient.table_string_num := 1;
      MainForm.Show_all_pat.Execute;
      MessageBox(0,
             PChar(del_pat_from_database_mes),
             PChar(mess_caption),
             MB_ICONINFORMATION or MB_OK
            );
      check_right_number_of_string_in_table;
    end;
  end;
end;

//удаление измерения
procedure TMainForm.del_izmExecute(Sender: TObject);
begin
  if MessageBox(0,
               PChar(del_measure_question_mes),
               PChar(mess_caption),
               MB_ICONQUESTION or MB_OKCANCEL
              )=mrOK then

  begin
    mysql_query( SQL_DM.mysql_query1, 'DELETE FROM `'+table_izm_name+
        '` WHERE `id`='+look_res_choise_izm.Selected.SubItems.Strings[0]+';',2);

    look_res_choise_load_data.Enabled := FALSE;
    look_res_del_izm.Enabled := FALSE;
    look_res_izm_description.Caption := '';

    Show_all_pat.Execute;
  end;
end;

//Кнопки сохранить и отменить
procedure TMainForm.new_izm_reset_btnClick(Sender: TObject);
begin
  enable_disable_new_izm_controls( TRUE );
end;
procedure TMainForm.new_izm_save_btnClick(Sender: TObject);
var day,mon,year:string;
begin
  // Получаем дату из поля
  day := ( new_izm_date_picker.text )[ 1 ]+( new_izm_date_picker.text )[ 2 ];
  mon := ( new_izm_date_picker.text )[ 4 ]+( new_izm_date_picker.text )[ 5 ];
  year := ( new_izm_date_picker.text )[ 7 ]+( new_izm_date_picker.text )[ 8 ]+( new_izm_date_picker.text )[ 9 ]+( new_izm_date_picker.text )[ 10 ];

  if ( act = SAVE_ACTION_ADD ) then
  begin
    try
      with patient do
        begin
          Set_current_patient_sirname( new_izm_fam_edit.Text );
          Set_current_patient_first_name( new_izm_name_edit.Text );
          Set_current_patient_middle_name( new_izm_otch_edit.Text );
          Set_current_patient_birth_day( day );
          Set_current_patient_birth_month( mon );
          Set_current_patient_birth_year( year );
          Set_current_patient_description( new_izm_edit_memo.Lines );

          Insert_current_patient;
        end;
    finally
      MainForm.enable_disable_new_izm_controls( TRUE );
      //ставим номер строчки на 1 больше чем количество строк в таблице
      patient.table_string_num := New_izm_DB_Grid.RowCount;
      MainForm.Show_all_pat.Execute;
      MessageBox(0,
                        PChar( add_pat_to_database_mes ),
                        PChar( mess_caption ),
                        MB_ICONINFORMATION or MB_OK
                       );
      //делаем доступными действия редактирования и удаления
      New_izm_red_pat.Enabled := TRUE;
      New_izm_del_pat.Enabled := TRUE;

      // а также проведения измерений
      if Device.IsConnected then
      begin
        new_izm_begin_izm_btn.Enabled := TRUE;
        new_izm_warning_label.hide;
      end;
    end;
  end
  else if ( act = SAVE_ACTION_UPDATE ) then
  begin
    try
      with patient do
        begin
          Set_current_patient_sirname( new_izm_fam_edit.Text );
          Set_current_patient_first_name( new_izm_name_edit.Text );
          Set_current_patient_middle_name( new_izm_otch_edit.Text );
          Set_current_patient_birth_day( day );
          Set_current_patient_birth_month( mon );
          Set_current_patient_birth_year( year );
          Set_current_patient_description( new_izm_edit_memo.Lines );

          Update_current_patient;
        end;
    finally
          MainForm.enable_disable_new_izm_controls( TRUE );
          MainForm.Show_all_pat.Execute;
          MessageBox(0,
                        PChar( red_pat_in_database_mes ),
                        PChar( mess_caption ),
                        MB_ICONINFORMATION or MB_OK
                       );
    end;
  end;
end;

//Пользовательские процедуры
procedure TMainForm.enable_disable_new_izm_controls(dir:boolean);
begin
  //скрываем панель информации
  New_izm_info_panel.Visible := dir;
  //показываем панель редактирования
  New_izm_red_panel.Visible := not dir;
  //инициализируем поля ввода
  new_izm_fam_edit.Clear;
  new_izm_name_edit.Clear;
  new_izm_otch_edit.Clear;
  new_izm_date_picker.text := DEFAULT_PAIENT_BIRTH_DATE;
  new_izm_edit_memo.Clear;

  //блокируем выход пользователя из вкладки
  lock_pc:=not dir;
  // и с помощью кнопок
  New_izm_DB_Grid.Enabled := dir;
  New_izm_Add_pat.Enabled := dir;
  New_izm_red_pat.Enabled := dir;
  New_izm_del_pat.Enabled := dir;

  //если выходим на первый контекст обнуляем действие
  if dir then act:='';

  look_results_btn.Enabled := dir;
  new_measure_btn.Enabled :=  dir;
end;


////////////////////////////////////////////////////////////////////////////////
//процедуры панели ПРОСМОТР РЕЗУЛЬТАТОВ                                       //
////////////////////////////////////////////////////////////////////////////////
procedure TMainForm.look_results_pcChange(Sender: TObject);
begin
 if ( look_results_pc.ActivePageIndex = 0 ) then
 begin
    //закладки делаем видимыми
    look_results_pc.Pages[ 1 ].TabVisible := FALSE;
    look_results_pc.Pages[ 2 ].TabVisible := FALSE;
    look_results_pc.Pages[ 3 ].TabVisible := FALSE;

    //снимаем выделение с измерений
    look_res_choise_izm.Selected:=nil;

    //по умолчанию устанавливаем опции подсчета значений
    look_res_choise_method_CB.ItemIndex:=0;
    look_res_choise_koeffs_CB.ItemIndex:=1;
    look_res_choise_R_CB.ItemIndex:=0;
 end;
look_res_act_page:=look_results_pc.ActivePageIndex;
end;

//загрузка данных
procedure TMainForm.look_res_load_dataExecute(Sender: TObject);
var
  //znach_kol, povtor, points_kol,
  i,k: Integer;
  izm_num, tmp1,tmp2:string;
  x_array: array [0..120] of integer;
  ser, ser1:TPointSeries;
  type_of_count: Integer;
begin
//закладки делаем видимыми
look_results_pc.Pages[1].TabVisible:=TRUE;
look_results_pc.Pages[2].TabVisible:=TRUE;
look_results_pc.Pages[3].TabVisible:=TRUE;

//забираем номер измерения
izm_num:=look_res_choise_izm.Selected.SubItems[0];
//начинаем загрузку данных в график
  //очищаем все что есть
  look_res_graph_chart.SeriesList.Clear;
  look_res_graph_choose.Items.Clear;

//определяем количество отсчетов по х, то есть сколько точек и сколько повторов
mysql_query(SQL_DM.mysql_query1, 'SELECT Count(*) FROM `'+table_znacheniya_name+
                '` WHERE `izm_num`='+izm_num,1);
//znach_kol:= SQL_DM.mysql_DSQ1.DataSet.FieldByName('Count(*)').AsInteger;
mysql_query(SQL_DM.mysql_query1, 'SELECT MAX(povtor_num) FROM `'+table_znacheniya_name+
                '` WHERE `izm_num`='+izm_num,1);
//povtor:=SQL_DM.mysql_DSQ1.DataSet.FieldByName('MAX(povtor_num)').AsInteger;
//points_kol:=round(znach_kol/povtor/6);


//Численные значения
load_number_grid(izm_num);

//формируем массив по х
for i:=0 to 120 do x_array[i]:=i;

look_res_graph_chart.SeriesList.Clear;

//определяем состав группы управления графиками, а также добавляем серии
create_series('R','3',izm_num,x_array,1/scales[0]);
create_series('G0','4',izm_num,x_array,1/scales[1]);
create_series('G1','5',izm_num,x_array,1/scales[2]);
create_series('G2','6',izm_num,x_array,1/scales[3]);
create_series('G3','7',izm_num,x_array,1/scales[4]);
create_series('C','8',izm_num,x_array,1/scales[5]);
create_series('Uсм','9',izm_num,x_array,1/scales[6]);

//инициализация resized
resized[0]:=FALSE;
resized[1]:=FALSE;
resized[2]:=FALSE;
resized[3]:=FALSE;
resized[4]:=FALSE;
resized[5]:=FALSE;
resized[6]:=FALSE;
//resized[7]:=FALSE;


// видимо блок для custom axes... хз...
//создаем серию
   ser:=TPointSeries.Create(self);
   ser.AddXY(0,0,'',clRed);

//задаем необходимые свойства серии
   ser.ParentChart:=look_res_graph_chart;
   ser.ColorEachPoint:=TRUE;
   ser.Pointer.Style:=psCircle;
   ser.Pointer.VertSize:=1;
   ser.Pointer.HorizSize:=1;
   ser.Visible:=TRUE;

//добавляем серию к графику
   look_res_graph_chart.AddSeries(ser);

//создаем серию
   ser1:=TPointSeries.Create(self);
   ser1.AddXY(0,0,'',clRed);

//задаем необходимые свойства серии
   ser1.ParentChart:=look_res_graph_chart;
   ser1.ColorEachPoint:=TRUE;
   ser1.Pointer.Style:=psCircle;
   ser1.Pointer.VertSize:=1;
   ser1.Pointer.HorizSize:=1;
   ser1.Visible:=TRUE;

//добавляем серию к графику
   look_res_graph_chart.AddSeries(ser1);

look_res_graph_choose.ItemIndex:=0;
look_res_graph_chart.Axes.Left.Automatic:=TRUE;
look_res_point_num_label.Caption:='1';
look_res_graph_points_back.Enabled:=FALSE;

look_res_point_CB.Items.Clear;
mysql_query(SQL_DM.mysql_query1, 'SELECT `name` FROM `'+table_points_name+';',1);
  SQL_DM.mysql_DSQ1.DataSet.First;
  i:=0;k:=0;
  //for i:=0 to 23 do
  repeat
    look_res_point_CB.Items.Add(
                inttostr(i+1)+'. '+SQL_DM.mysql_DSQ1.DataSet.FieldByName('name').AsString);
    if i=11 then
       begin
            SQL_DM.mysql_DSQ1.DataSet.Next;
            k:=0;
            inc(i);
       end
    else
    begin
    if k=0 then
     begin
          inc(k);
          SQL_DM.mysql_DSQ1.DataSet.Next;
          SQL_DM.mysql_DSQ1.DataSet.Next;
          SQL_DM.mysql_DSQ1.DataSet.Next;
          SQL_DM.mysql_DSQ1.DataSet.Next;
          SQL_DM.mysql_DSQ1.DataSet.Next;
          SQL_DM.mysql_DSQ1.DataSet.Next;
     end
    else
        if k=1 then
           begin
                dec(k);
                SQL_DM.mysql_DSQ1.DataSet.Prior;
                SQL_DM.mysql_DSQ1.DataSet.Prior;
                SQL_DM.mysql_DSQ1.DataSet.Prior;
                SQL_DM.mysql_DSQ1.DataSet.Prior;
                SQL_DM.mysql_DSQ1.DataSet.Prior;
           end;
    inc(i);
    end;
  until i=24;
look_res_point_CB.Text:=look_res_point_CB.Items[0];

// степень сжатия для 0 серии:
look_res_log_scale.Value:=round(koeff[0]);
look_res_log_scale.Enabled:=TRUE;

look_res_point_CB.ItemIndex:=0;

//чек-боксы
look_res_graph_options_15_CB.State:=cbUnchecked;
look_res_graph_options_max_CB.State:=cbUnchecked;
look_res_graph_options_min_CB.State:=cbUnchecked;
look_res_graph_options_average_CB.State:=cbUnchecked;
look_res_graph_options_15_all_CB.State:=cbUnchecked;
look_res_graph_options_max_all_CB.State:=cbUnchecked;
look_res_graph_options_min_all_CB.State:=cbUnchecked;
look_res_graph_options_average_all_CB.State:=cbUnchecked;

look_res_graph_chart.Axes.Bottom.Automatic:=FALSE;
look_res_graph_chart.Axes.Bottom.Maximum:=24;
look_res_graph_chart.Axes.Bottom.Minimum:=0;

//комбо-бокс измерений на закладке графиков и чисел:
look_res_graph_izm_CB.Items.Clear;
look_res_number_izm_CB.Items.Clear;
look_res_graph_izm_id_CB.Items.Clear;
look_res_number_izm_id_CB.Items.Clear;
for i := 0 to look_res_choise_izm.Items.Count - 1 do
begin
  look_res_graph_izm_CB.Items.Add(look_res_choise_izm.Items[i].Caption);
  look_res_graph_izm_id_CB.Items.Add(look_res_choise_izm.Items[i].SubItems[0]);

  look_res_number_izm_CB.Items.Add(look_res_choise_izm.Items[i].Caption);
  look_res_number_izm_id_CB.Items.Add(look_res_choise_izm.Items[i].SubItems[0]);
end;
look_res_graph_izm_CB.ItemIndex:=look_res_choise_izm.Selected.Index;
look_res_number_izm_CB.ItemIndex:=look_res_choise_izm.Selected.Index;

//Описание измерения сверху графика:
if strlen(PCHAR(look_res_izm_description.Caption))<50 then
   look_res_graph_izm_desc.Caption:=look_res_izm_description.Caption
else
begin
  look_res_graph_izm_desc.Caption:=copy(look_res_izm_description.Caption,0,47)+'...';
end;

//Описание пациента и измерения на закладке диагноза:
tmp1:=look_res_choise_name_znach.Caption;
tmp2:=look_res_choise_otch_znach.Caption;
tmp2:=look_res_choise_fam_znach.Caption+' '+tmp1[1]+'.'+tmp2[1]+'.';
look_res_fio_label.Caption:=tmp2;
look_res_izm_name_label.Caption:=look_res_choise_izm.Selected.Caption;
look_res_izm_about_label.Caption:=look_res_izm_description.Caption;

//Описание пациента и измерения на закладке чисел:
look_res_number_fio_label.Caption:=look_res_fio_label.Caption;
look_res_number_izm_label.Caption:=look_res_izm_name_label.Caption;
look_res_number_desc_label.Caption:=look_res_izm_about_label.Caption;


//////////////////////////////////
//Закладка результаты и диагноз //
//////////////////////////////////
with look_res_diagnoz_data_StringGrid do
begin
DefaultRowHeight:=16;
//получаем способ расчета сопротивления
type_of_count:=look_res_choise_R_CB.ItemIndex;

 Cells[0,3]:='PL1';
 Cells[1,3]:=Get_R('PL1_l',izm_num,type_of_count);

 Cells[0,4]:='MC9';
 Cells[1,4]:=Get_R('MC9_l',izm_num,type_of_count);

 Cells[0,5]:='C9';
 Cells[1,5]:=Get_R('C9_l',izm_num,type_of_count);

 Cells[3,3]:='PL1';
 Cells[4,3]:=Get_R('PL1_r',izm_num,type_of_count);

 Cells[3,4]:='MC9';
 Cells[4,4]:=Get_R('MC9_r',izm_num,type_of_count);

 Cells[3,5]:='C9';
 Cells[4,5]:=Get_R('C9_r',izm_num,type_of_count);

 //рука левая Инь и Ян
 Cells[1,6]:=floattostr(strtofloat(Cells[1,3])+strtofloat(Cells[1,4])+strtofloat(Cells[1,5]));
 Cells[4,6]:=floattostr(strtofloat(Cells[4,3])+strtofloat(Cells[4,4])+strtofloat(Cells[4,5]));

 Cells[0,8]:='GL1';
 Cells[1,8]:=Get_R('GL1_l',izm_num,type_of_count);

 Cells[0,9]:='TR1';
 Cells[1,9]:=Get_R('TR1_l',izm_num,type_of_count);

 Cells[0,10]:='IG1';
 Cells[1,10]:=Get_R('IG1_l',izm_num,type_of_count);

 Cells[3,8]:='GL1';
 Cells[4,8]:=Get_R('GL1_r',izm_num,type_of_count);

 Cells[3,9]:='TR1';
 Cells[4,9]:=Get_R('TR1_r',izm_num,type_of_count);

 Cells[3,10]:='IG1';
 Cells[4,10]:=Get_R('IG1_r',izm_num,type_of_count);

 //рука правая Инь и Ян
 Cells[1,11]:=floattostr(strtofloat(Cells[1,8])+strtofloat(Cells[1,9])+strtofloat(Cells[1,10]));
 Cells[4,11]:=floattostr(strtofloat(Cells[4,8])+strtofloat(Cells[4,9])+strtofloat(Cells[4,10]));

 Cells[1,12]:=summ_left_hands+floattostr(rounder(strtofloat(Cells[1,11])+strtofloat(Cells[1,6]),2))+'МОм';
 Cells[4,12]:=summ_right_hands+floattostr(rounder(strtofloat(Cells[4,11])+strtofloat(Cells[4,6]),2))+'МОм';

 Cells[4,13]:=summ_hands+floattostr(
        rounder(
          strtofloat(Cells[4,11])+
          strtofloat(Cells[4,6])+
          strtofloat(Cells[1,11])+
          strtofloat(Cells[1,6]),
          2))+'МОм';



 Cells[6,3]:='F1';
 Cells[7,3]:=Get_R('F1_l',izm_num,type_of_count);

 Cells[6,4]:='RP1';
 Cells[7,4]:=Get_R('RP1_l',izm_num,type_of_count);

 Cells[6,5]:='R0';
 Cells[7,5]:=Get_R('R0_l',izm_num,type_of_count);

 Cells[9,3]:='F1';
 Cells[10,3]:=Get_R('F1_r',izm_num,type_of_count);

 Cells[9,4]:='RP1';
 Cells[10,4]:=Get_R('RP1_r',izm_num,type_of_count);

 Cells[9,5]:='R0';
 Cells[10,5]:=Get_R('R0_r',izm_num,type_of_count);

 Cells[7,6]:=floattostr(strtofloat(Cells[7,3])+strtofloat(Cells[7,4])+strtofloat(Cells[7,5]));
 Cells[10,6]:=floattostr(strtofloat(Cells[10,3])+strtofloat(Cells[10,4])+strtofloat(Cells[10,5]));

 Cells[6,8]:='E45';
 Cells[7,8]:=Get_R('E45_l',izm_num,type_of_count);

 Cells[6,9]:='VB44';
 Cells[7,9]:=Get_R('VB44_l',izm_num,type_of_count);

 Cells[6,10]:='V67';
 Cells[7,10]:=Get_R('V67_l',izm_num,type_of_count);

 Cells[9,8]:='E45';
 Cells[10,8]:=Get_R('E45_r',izm_num,type_of_count);

 Cells[9,9]:='VB44';
 Cells[10,9]:=Get_R('VB44_r',izm_num,type_of_count);

 Cells[9,10]:='V67';
 Cells[10,10]:=Get_R('V67_r',izm_num,type_of_count);

 Cells[7,11]:=floattostr(strtofloat(Cells[7,8])+strtofloat(Cells[7,9])+strtofloat(Cells[7,10]));
 Cells[10,11]:=floattostr(strtofloat(Cells[10,8])+strtofloat(Cells[10,9])+strtofloat(Cells[10,10]));

 Cells[7,12]:=summ_left_legs+floattostr(rounder(strtofloat(Cells[7,11])+strtofloat(Cells[7,6]),2))+'МОм';
 Cells[10,12]:=summ_right_legs+floattostr(rounder(strtofloat(Cells[10,11])+strtofloat(Cells[10,6]),2))+'МОм';

 Cells[11,13]:=summ_legs+floattostr(
        rounder(
          strtofloat(Cells[10,11])+
          strtofloat(Cells[10,6])+
          strtofloat(Cells[7,11])+
          strtofloat(Cells[7,6]),
          2))+'МОм';
case look_res_choise_koeffs_CB.ItemIndex of
  0: begin //Руки + Ноги
        look_res_diagnoz_data_znach_label.Caption:=floattostr(rounder(
          (strtofloat(Cells[10,11])+
          strtofloat(Cells[10,6]) +
          strtofloat(Cells[7,11]) +
          strtofloat(Cells[7,6])  +
          strtofloat(Cells[4,11]) +  //рука правая Инь и Ян
          strtofloat(Cells[4,6])  +  //рука левая Инь и Ян
          strtofloat(Cells[1,11]) +  //рука правая Инь и Ян
          strtofloat(Cells[1,6])     //рука левая Инь и Ян
          )/24
 ,3));
     end;
  1: begin //Только руки
        look_res_diagnoz_data_znach_label.Caption:=floattostr(rounder(
          (strtofloat(Cells[4,11]) +  //рука правая Инь и Ян
          strtofloat(Cells[4,6])  +  //рука левая Инь и Ян
          strtofloat(Cells[1,11]) +  //рука правая Инь и Ян
          strtofloat(Cells[1,6])     //рука левая Инь и Ян
          )/12
          ,3));
     end;
  2: begin  //Только ноги
         look_res_diagnoz_data_znach_label.Caption:=floattostr(rounder(
          (strtofloat(Cells[10,11])+
          strtofloat(Cells[10,6]) +
          strtofloat(Cells[7,11]) +
          strtofloat(Cells[7,6]))/12 
 ,3));
     end;
end;

end;

//индикация на графике сопротивлений
look_res_diagnoz_koeff_diagnoz_shape.Left:=142+
    round(strtofloat(look_res_diagnoz_data_znach_label.Caption)*100);

//активная закладка графиков
if look_res_act_page<>0 then
    look_results_pc.ActivePageIndex:=look_res_act_page
else look_results_pc.ActivePageIndex:=2;
end;
//Создание серии с выборкой значений из базы
procedure TMainForm.create_series(name,num,izm_num:string;
x_array:array of integer; scale:extended);
var i,j,k:integer;

y_arrays: array [0..number_of_params-1,
                 1..number_of_points,
                 1..number_of_repeat] of double;
name_array: array [0..number_of_points-1] of string;
ser:TPointSeries;
  i1: Integer;
  kk:boolean;
begin
//инициализация y_arrays
for i:=0 to number_of_params-1 do
    for j:=1 to number_of_points do
      for k:=1 to number_of_repeat do
        y_arrays[i,j,k]:=0;

//добавляем параметр в окно выбора
  look_res_graph_choose.Items.Add(name);
//загружаем значения для параметра
//в формате PL1_r PL1_l и т.д.
  i:=1;k:=0;i1:=1; kk:=FALSE;
  //for i:=1 to 24 do
  repeat
       //пока упрощенно на все точки
    mysql_query(SQL_DM.mysql_query1, 'SELECT `znach` FROM `'+table_znacheniya_name+
                '` WHERE (`izm_num`='+izm_num+' AND `param_num`='+num+' AND `point_num`='+
                inttostr(i)+') ORDER BY `rd_znacheniya`.`povtor_num` ASC',1);
    SQL_DM.mysql_DSQ1.DataSet.First;
    for j:=1 to number_of_repeat do
      begin
        if SQL_DM.mysql_DSQ1.DataSet.RecordCount>0 then
        y_arrays[strtoint(num)-3,i1,j]:=
                SQL_DM.mysql_DSQ1.DataSet.FieldByName('znach').AsFloat*scale
        else y_arrays[strtoint(num)-3,i1,j]:=0;
        SQL_DM.mysql_DSQ1.DataSet.Next;
      end;
    if i=12 then begin kk:=TRUE; k:=-1; end;
    if k<=0 then
       begin

             if kk then begin inc(i); kk:=FALSE; end else i:=i+6;
             inc(k);
       end
    else if k=1 then 
         begin
               i:=i-5; 
               dec(k); 
         end;
         inc(i1);
  until i1=25;

  //выбираем имена точек
  mysql_query(SQL_DM.mysql_query1, 'SELECT `name` FROM `'+table_points_name+';',1);
  SQL_DM.mysql_DSQ1.DataSet.First;
  i:=0;k:=0;
  //for i:=0 to 23 do
  repeat
    name_array[i]:=SQL_DM.mysql_DSQ1.DataSet.FieldByName('name').AsString;
    if i=11 then
       begin
            SQL_DM.mysql_DSQ1.DataSet.Next;
            k:=0;
            inc(i);
       end
    else
    begin
    if k=0 then
     begin
          inc(k);
          SQL_DM.mysql_DSQ1.DataSet.Next;
          SQL_DM.mysql_DSQ1.DataSet.Next;
          SQL_DM.mysql_DSQ1.DataSet.Next;
          SQL_DM.mysql_DSQ1.DataSet.Next;
          SQL_DM.mysql_DSQ1.DataSet.Next;
          SQL_DM.mysql_DSQ1.DataSet.Next;
     end
    else
        if k=1 then
           begin
                dec(k);
                SQL_DM.mysql_DSQ1.DataSet.Prior;
                SQL_DM.mysql_DSQ1.DataSet.Prior;
                SQL_DM.mysql_DSQ1.DataSet.Prior;
                SQL_DM.mysql_DSQ1.DataSet.Prior;
                SQL_DM.mysql_DSQ1.DataSet.Prior;
           end;
    inc(i);
    end;
  until i=24;


//создаем серию
ser:=TPointSeries.Create(self);
ser.Title:=name;
for i:=1 to number_of_points do
  for j:=1 to number_of_repeat do
  begin
    //загружаем в нее значения из массива
    ser.AddXY(j/5+i-1,y_arrays[strtoint(num)-3,i,j],'',clRed);
  end;

//загружаем названия точек
look_res_graph_chart.Axes.Bottom.Items.Clear;
  for i := 0 to ser.Count - 1 do
    if ((i-2) mod 5=0) and (i>0) then
        look_res_graph_chart.Axes.Bottom.Items.Add(ser.XValue[i], name_array[i div 5])
    else look_res_graph_chart.Axes.Bottom.Items.Add(ser.XValue[i], ' ');

//задаем необходимые свойства серии
ser.ParentChart:=look_res_graph_chart;
ser.ColorEachPoint:=TRUE;
ser.Pointer.Style:=psCircle;
ser.Pointer.VertSize:=3;
ser.Pointer.HorizSize:=3;
ser.Visible:=FALSE;

//добавляем серию к графику
look_res_graph_chart.AddSeries(ser);

end;

//Выбор измерений
procedure TMainForm.look_res_choise_izmDblClick(Sender: TObject);
begin
if look_res_choise_izm.Selected<>nil then
  begin
     look_res_load_data.Execute;
  end;
end;
procedure TMainForm.look_res_choise_izmExit(Sender: TObject);
begin
look_res_izm_description.Caption:='';
look_res_choise_load_data.Enabled:=FALSE;
end;
procedure TMainForm.look_res_choise_izmSelectItem(Sender: TObject;
  Item: TListItem; Selected: Boolean);
begin
if Selected then begin
   mysql_query(SQL_DM.mysql_query4, 'SELECT `opisanie` FROM `'+table_izm_name+
                '` WHERE `id`='+look_res_choise_izm.Selected.SubItems[0],1);
   SQL_DM.mysql_DSQ4.DataSet:=SQL_DM.mysql_query4;
   look_res_izm_description.Caption:=SQL_DM.mysql_DSQ4.DataSet.FieldByName('opisanie').AsString;

   /// проблема с выходом из листа и входом в панель действий, в панели
   ///  действий пришлось убрать дествие "загрузить данные"
      look_res_choise_load_data.Enabled:=TRUE;
      look_res_del_izm.Enabled:=TRUE;
  end;
end;


//служебные процедуры таблицы пациентов
procedure TMainForm.look_results_DB_GridGetCellBorder(Sender: TObject; ARow,
  ACol: Integer; APen: TPen; var Borders: TCellBorders);
begin
  APen.Width:=2;
if (ARow<>0) and (look_results_pc.Pages[1].TabVisible) and (db_grid_cur_row_num=ARow) then
  begin
    APen.Width := 2;
    if ACol<>0 then Borders:=[cbTop, cbBottom];
    if ACol=1  then Borders:=[cbLeft,cbTop, cbBottom]
    else if ACol=8  then Borders:=[cbRight,cbTop, cbBottom];
  end;
end;
procedure TMainForm.look_results_DB_GridGetCellBorderProp(Sender: TObject; ARow,
  ACol: Integer; LeftPen, TopPen, RightPen, BottomPen: TPen);
begin
 LeftPen.Color := clRed;
 RightPen.Color := clRed;
 BottomPen.Color := clRed;
 TopPen.Color := clRed;
end;
//Обновление
procedure TMainForm.look_results_DB_GridKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
if (GetKeyState(vk_f5) AND 128)=128 then
   begin
        Show_all_pat.Execute;
   end;
end;

//Выбор пациента
procedure TMainForm.look_results_DB_GridSelectCell(Sender: TObject; ACol,
  ARow: Integer; var CanSelect: Boolean);
var i:integer;
var measure_info: TMeasure_info_record;
begin
//если в клетке что-то есть то
if MainForm.look_results_DB_Grid.Cells[1,Arow]<>'' then
  begin
    //Загружаем информацию
    //фамилия имя отчество
    with Patient do
    begin
      Set_current_patient_by_id(New_izm_DB_Grid.Cells[1,Arow]);

      //фамилия имя отчество
      look_res_choise_fam_znach.Caption:=Get_current_patient_sirname;
      look_res_choise_name_znach.Caption:=Get_current_patient_first_name;
      look_res_choise_otch_znach.Caption:=Get_current_patient_middle_name;

      //дата рождения
      look_res_choise_date_znach.Caption:= make_date(Get_current_patient_birth_day,
                                                     Get_current_patient_birth_month,
                                                     Get_current_patient_birth_year);
      //примечания:
      look_res_choise_memo.Lines.Clear;
      look_res_choise_memo.Lines.AddStrings(Get_current_patient_description);
      //количество измерений
      look_res_choise_izm_kol.Caption:=Get_current_patient_measure_count;


   //загрузка дат измерений даты измерений:
      look_res_choise_izm.Items.Clear;
      i:=0;
      for measure_info in Get_current_patient_measures_array do
      begin
        look_res_choise_izm.Items.Add;
        look_res_choise_izm.Items[i].Caption:=measure_info.date;
        look_res_choise_izm.Items[i].SubItems.Add(measure_info.ID);
        inc(i);
      end;

    end;

    //обнуляем описание измерений
    look_res_izm_description.Caption:=MAIN_UNIT_MEASURE_CHOISE_NOT_SELECTED;

    //активным в любом случае становится закладка выбора информации
    look_results_pc.ActivePageIndex:=0;
    //Остальные закладки делаем невидимыми
    look_results_pc.Pages[1].TabVisible:=FALSE;
    look_results_pc.Pages[2].TabVisible:=FALSE;
    look_results_pc.Pages[3].TabVisible:=FALSE;

    //Опции расчета
    look_res_choise_method_CB.ItemIndex:=0;
    look_res_choise_koeffs_CB.ItemIndex:=1;
    look_res_choise_R_CB.ItemIndex:=0;
  end;
end;


//Клики на метке о пациенте, отображается информация
procedure TMainForm.look_res_fio_labelClick(Sender: TObject);
begin
//show_patient_info_from_izm_num(izm_num);
end;
procedure TMainForm.look_res_fio_labelMouseEnter(Sender: TObject);
begin
look_res_fio_label.Font.Style:=[fsUnderline];
end;
procedure TMainForm.look_res_fio_labelMouseLeave(Sender: TObject);
begin
look_res_fio_label.Font.Style:=[];
end;
procedure TMainForm.look_res_number_fio_labelMouseEnter(Sender: TObject);
begin
look_res_number_fio_label.Font.Style:=[fsUnderline];
end;
procedure TMainForm.look_res_number_fio_labelMouseLeave(Sender: TObject);
begin
look_res_number_fio_label.Font.Style:=[];
end;


/////////////////////////////////
/// Закладка графиков          //
////////////////////////////////
//Клики на чекбоксы линий
procedure TMainForm.look_res_graph_options_15_all_CBClick(Sender: TObject);
begin
look_res_log_scale_CB.Checked:=FALSE;
look_res_log_scale_CBClick(self);
if look_res_graph_options_15_all_CB.Checked then
begin
   create_series_all(look_res_graph_chart, 'average_up_all', 'average_15+');
   create_series_all(look_res_graph_chart, 'average_down_all', 'average_15-');
end
else
begin
   delete_series(look_res_graph_chart,'average_up_all');
   delete_series(look_res_graph_chart,'average_down_all');
end;
end;
procedure TMainForm.look_res_show_15Execute(Sender: TObject);
begin
look_res_log_scale_CB.Checked:=FALSE;
look_res_log_scale_CBClick(self);
if look_res_graph_options_15_CB.Checked then
begin
    create_series_point(look_res_graph_chart, 'average_up', 'average_15+');
    create_series_point(look_res_graph_chart, 'average_down', 'average_15-');
end
else
begin
    delete_series(look_res_graph_chart,'average_up');
    delete_series(look_res_graph_chart,'average_down');
end;
end;
procedure TMainForm.look_res_graph_options_average_all_CBClick(Sender: TObject);
begin
look_res_log_scale_CB.Checked:=FALSE;
look_res_log_scale_CBClick(self);
if look_res_graph_options_average_all_CB.Checked then
begin
   create_series_all(look_res_graph_chart, 'average_all', 'average');
end
else
begin
   delete_series(look_res_graph_chart,'average_all');
end;

end;
procedure TMainForm.look_res_graph_options_average_CBClick(Sender: TObject);
begin
look_res_log_scale_CB.Checked:=FALSE;
look_res_log_scale_CBClick(self);
if look_res_graph_options_average_CB.Checked then
  begin
    create_series_point(look_res_graph_chart, 'average', 'average');
  end
else
  begin
    delete_series(look_res_graph_chart,'average');
  end;
end;
procedure TMainForm.look_res_graph_options_max_all_CBClick(Sender: TObject);
begin
look_res_log_scale_CB.Checked:=FALSE;
look_res_log_scale_CBClick(self);
if look_res_graph_options_max_all_CB.Checked then
begin
   create_series_all(look_res_graph_chart, 'max_all', 'max');
end
else
begin
   delete_series(look_res_graph_chart,'max_all');
end;
end;
procedure TMainForm.look_res_graph_options_max_CBClick(Sender: TObject);
begin
look_res_log_scale_CB.Checked:=FALSE;
look_res_log_scale_CBClick(self);
if look_res_graph_options_max_CB.Checked then
  begin
    create_series_point(look_res_graph_chart, 'max', 'max');
  end
else
  begin
    delete_series(look_res_graph_chart,'max');
  end;
end;
procedure TMainForm.look_res_graph_options_min_all_CBClick(Sender: TObject);
begin
look_res_log_scale_CB.Checked:=FALSE;
look_res_log_scale_CBClick(self);
if look_res_graph_options_min_all_CB.Checked then
begin
   create_series_all(look_res_graph_chart, 'min_all', 'min');
end
else
begin
   delete_series(look_res_graph_chart,'min_all');
end;
end;
procedure TMainForm.look_res_graph_options_min_CBClick(Sender: TObject);
begin
look_res_log_scale_CB.Checked:=FALSE;
look_res_log_scale_CBClick(self);
if look_res_graph_options_min_CB.Checked then
  begin
    create_series_point(look_res_graph_chart, 'min', 'min');
  end
else
  begin
    delete_series(look_res_graph_chart,'min');
  end;
end;

//Создание и удаление серий с прямыми
procedure TMainForm.create_series_point(chart: TChart; name_ser,type_of: string);
var i,point_num:integer;
    value:extended;
    shape:TShape;
    ser:TLineSeries;
begin
value:=0;
shape:=nil;
     if type_of='average_15+' then
      begin
        value:=get_average_point;
        value:=value+0.15*value;
        shape:=look_res_graph_options_15_color;
      end
else if type_of='average_15-' then
      begin
        value:=get_average_point;
        value:=value-0.15*value;
        shape:=look_res_graph_options_15_color;
      end
else if type_of='average' then
      begin
        value:=get_average_point;
        shape:=look_res_graph_options_average_color;
      end
else if type_of='max' then
      begin
        value:=get_max_min_point(1);
        shape:=look_res_graph_options_max_color;
      end
else if type_of='min' then
      begin
        value:=get_max_min_point(0);
        shape:=look_res_graph_options_min_color;
      end;


point_num:=0;
for I := 0 to chart.Axes.Bottom.Items.Count - 1 do
      if (chart.Axes.Bottom.Items[i].Font.Style=[fsBold]) and
         (chart.Axes.Bottom.Items[i].Font.Height=-11) then
            begin
              point_num:=(i div 5) +1;
            end;

ser:=TLineSeries.Create(self);
with ser do
begin
  Color:=shape.Brush.Color;
  LinePen.Width:=2;
  Title:=name_ser;
  Visible:=TRUE;
  ParentChart:=chart;
  if not(point_num in [1,24]) then
    begin
        AddXY(point_num-1.15,value,floattostr(value));
        AddXY(point_num+0.3,value,'');
    end
  else
    if point_num=1 then
      begin
          AddXY(point_num-1,value,floattostr(value));
          AddXY(point_num+0.3,value,'');
      end
  else
      begin
          AddXY(point_num-1.1,value,floattostr(value));
          AddXY(point_num+0,value,'');
      end;
end;
end;
procedure TMainForm.create_series_all(chart: TChart; name_ser,type_of: string);
var value:extended;
    shape:TShape;
    ser:TLineSeries;
begin
value:=0;
shape:=nil;
     if type_of='average_15+' then
      begin
        value:=get_average_point_all;
        value:=value+0.15*value;
        shape:=look_res_graph_options_15_all_color;
      end
else if type_of='average_15-' then
      begin
        value:=get_average_point_all;
        value:=value-0.15*value;
        shape:=look_res_graph_options_15_all_color;
      end
else if type_of='average' then
      begin
        value:=get_average_point_all;
        shape:=look_res_graph_options_average_all_color;
      end
else if type_of='max' then
      begin
        value:=get_max_min_point_all(1);
        shape:=look_res_graph_options_max_all_color;
      end
else if type_of='min' then
      begin
        value:=get_max_min_point_all(0);
        shape:=look_res_graph_options_min_all_color;
      end;

ser:=TLineSeries.Create(self);
with ser do
begin
  Color:=shape.Brush.Color;
  LinePen.Width:=2;
  Title:=name_ser;
  Visible:=TRUE;
  ParentChart:=chart;

        AddXY(0,value,floattostr(value));
        AddXY(24,value,'');
end;
end;
procedure TMainForm.delete_series(chart: TChart; name: string);
var
  I: Integer;
begin
for I := 0 to chart.SeriesList.Count - 1 do
  if (chart.SeriesList.Items[i].Title=name) then
   begin
      chart.SeriesList.Items[i].Visible:=FALSE;
      chart.SeriesList.Items[i].Free;
   end;
end;
//вытаскивание средних, +/-15%, макс. и мин. значений
function TMainForm.get_average_point():extended;
var i:integer;
    point_name, param_name, izm_num:string;
    tmp:extended;
begin
//При расчетах нулевые-ошибочные значения выкидываются и не учитываются!!!

     //выясняем какая точка активная настоящий момент:
    for I := 0 to look_res_graph_chart.Axes.Bottom.Items.Count - 1 do
      if (look_res_graph_chart.Axes.Bottom.Items[i].Font.Style=[fsBold]) and
         (look_res_graph_chart.Axes.Bottom.Items[i].Font.Height=-11) then
            begin
            point_name:=look_res_graph_chart.Axes.Bottom.Items[i].Text;
           
            end;
    //параметр
    param_name:=look_res_graph_choose.Items[look_res_graph_choose.ItemIndex];
    //Номер измерения
    izm_num:=look_res_choise_izm.Selected.SubItems[0];
    mysql_query(SQL_DM.mysql_query4,
      'SELECT `znach` FROM `'+table_znacheniya_name+'` WHERE '+
      '(`izm_num`='+izm_num+') AND'+
      '(`param_num`=(SELECT `id` FROM '+table_param_name+' WHERE `name`='''+param_name+''')) AND'+
      '(`point_num`=(SELECT `num` FROM '+table_points_name+' WHERE `name`='''+point_name+'''))',2);
try
SQL_DM.mysql_DSQ4.DataSet.First;
tmp:=0;i:=0;
while not SQL_DM.mysql_DSQ4.DataSet.Eof do
begin
  if SQL_DM.mysql_DSQ4.DataSet.FieldByName('znach').AsFloat<>0 then
    begin
      inc(i);
      tmp:=tmp+SQL_DM.mysql_DSQ4.DataSet.FieldByName('znach').AsFloat;
    end;
  SQL_DM.mysql_DSQ4.DataSet.Next;
end;
if i<>0 then
result:=tmp/i/scales[look_res_graph_choose.ItemIndex]
else result:=0;
except
result:=0;
end;
end;
function TMainForm.get_average_point_all():extended;
var i:integer;
    param_name, izm_num:string;
    tmp:extended;
begin
//При расчетах нулевые-ошибочные значения выкидываются и не учитываются!!!

    //параметр
    param_name:=look_res_graph_choose.Items[look_res_graph_choose.ItemIndex];
    //Номер измерения
    izm_num:=look_res_choise_izm.Selected.SubItems[0];
    mysql_query(SQL_DM.mysql_query4,
      'SELECT `znach` FROM `'+table_znacheniya_name+'` WHERE '+
      '(`izm_num`='+izm_num+') AND'+
      '(`param_num`=(SELECT `id` FROM '+table_param_name+' WHERE `name`='''+param_name+'''))',2);
try
   SQL_DM.mysql_DSQ4.DataSet.First;
   tmp:=0;i:=0;
   while not SQL_DM.mysql_DSQ4.DataSet.Eof do
         begin
              if SQL_DM.mysql_DSQ4.DataSet.FieldByName('znach').AsFloat<>0 then
                 begin
                      inc(i);
                      tmp:=tmp+SQL_DM.mysql_DSQ4.DataSet.FieldByName('znach').AsFloat;
                 end;
              SQL_DM.mysql_DSQ4.DataSet.Next;
         end;
         if i<>0 then
            result:=tmp/i/scales[look_res_graph_choose.ItemIndex]
         else result:=0;
except
      result:=0;
end;
end;
function TMainForm.get_max_min_point(sw:integer):extended;
var i:integer;
    point_name, param_name, izm_num:string;
begin
 //При расчетах нулевые-ошибочные значения выкидываются и не учитываются!!!
    //выясняем какая точка активная настоящий момент:
    for I := 0 to look_res_graph_chart.Axes.Bottom.Items.Count - 1 do
      if (look_res_graph_chart.Axes.Bottom.Items[i].Font.Style=[fsBold]) and
         (look_res_graph_chart.Axes.Bottom.Items[i].Font.Height=-11) then
            begin
            point_name:=look_res_graph_chart.Axes.Bottom.Items[i].Text;
           
            end;
    //параметр
    param_name:=look_res_graph_choose.Items[look_res_graph_choose.ItemIndex];
    //Номер измерения
    izm_num:=look_res_choise_izm.Selected.SubItems[0];
case sw of
0:
    mysql_query(SQL_DM.mysql_query4,
      'SELECT MIN(`znach`) FROM `'+table_znacheniya_name+'` WHERE '+
      ' (`izm_num`='+izm_num+') AND'+
      ' (`znach` != 0) AND'+
      ' (`param_num`=(SELECT `id` FROM '+table_param_name+' WHERE `name`='''+param_name+''')) AND'+
      ' (`point_num`=(SELECT `num` FROM '+table_points_name+' WHERE `name`='''+point_name+'''))',2);
1:
    mysql_query(SQL_DM.mysql_query4,
      'SELECT MAX(`znach`) FROM `'+table_znacheniya_name+'` WHERE '+
      ' (`izm_num`='+izm_num+') AND'+
      ' (`znach` != 0) AND'+
      ' (`param_num`=(SELECT `id` FROM '+table_param_name+' WHERE `name`='''+param_name+''')) AND'+
      ' (`point_num`=(SELECT `num` FROM '+table_points_name+' WHERE `name`='''+point_name+'''))',2);

end;
try
case sw of
1:
    result:=SQL_DM.mysql_DSQ4.DataSet.FieldByName('MAX(`znach`)').AsFloat/scales[look_res_graph_choose.ItemIndex];
0:
    result:=SQL_DM.mysql_DSQ4.DataSet.FieldByName('MIN(`znach`)').AsFloat/scales[look_res_graph_choose.ItemIndex];
else
    result:=0;
end;
except
result:=0;
end;
end;
function TMainForm.get_max_min_point_all(sw:integer):extended;
var param_name, izm_num:string;
begin
//При расчетах нулевые-ошибочные значения выкидываются и не учитываются!!!
    //параметр
    param_name:=look_res_graph_choose.Items[look_res_graph_choose.ItemIndex];
    //Номер измерения
    izm_num:=look_res_choise_izm.Selected.SubItems[0];
case sw of
0:
    mysql_query(SQL_DM.mysql_query4,
      ' SELECT MIN(`znach`) FROM `'+table_znacheniya_name+'` WHERE '+
      ' (`izm_num`='+izm_num+') AND '+
      ' (`znach` != 0) AND '+
      ' (`param_num`=(SELECT `id` FROM '+table_param_name+' WHERE `name`='''+param_name+'''))',2);
1:
          mysql_query(SQL_DM.mysql_query4,
      ' SELECT MAX(`znach`) FROM `'+table_znacheniya_name+'` WHERE '+
      ' (`izm_num`='+izm_num+') AND'+
      ' (`znach` != 0) AND'+
      ' (`param_num`=(SELECT `id` FROM '+table_param_name+' WHERE `name`='''+param_name+'''))',2);
end;
    try
case sw of
1:
    result:=SQL_DM.mysql_DSQ4.DataSet.FieldByName('MAX(`znach`)').AsFloat/scales[look_res_graph_choose.ItemIndex];
0:
    result:=SQL_DM.mysql_DSQ4.DataSet.FieldByName('MIN(`znach`)').AsFloat/scales[look_res_graph_choose.ItemIndex];
else
    result:=0;
end;
except
result:=0;
end;
end;

//Навигация по точкам
procedure TMainForm.look_res_graph_points_backClick(Sender: TObject);
var
  num: Integer;
begin
look_res_point_num_label.Caption:=inttostr(strtoint(look_res_point_num_label.Caption)-1);
num:=strtoint(look_res_point_num_label.Caption);
if num-1=0 then look_res_graph_points_back.Enabled:=FALSE
else look_res_graph_points_back.Enabled:=TRUE;
look_res_graph_points_forw.Enabled:=TRUE;
make_point_active(num);
look_res_point_CB.ItemIndex:=look_res_point_CB.ItemIndex-1;

//сбрасываем чек-боксы для точек:
if look_res_graph_options_15_CB.Checked then look_res_graph_options_15_CB.Checked:=FALSE;
if look_res_graph_options_max_CB.Checked then look_res_graph_options_max_CB.Checked:=FALSE;
if look_res_graph_options_min_CB.Checked then look_res_graph_options_min_CB.Checked:=FALSE;
if look_res_graph_options_average_CB.Checked then look_res_graph_options_average_CB.Checked:=FALSE;

look_res_graph_chart.Repaint;
end;
procedure TMainForm.look_res_graph_points_forwClick(Sender: TObject);
var
  num:integer;
begin
look_res_point_num_label.Caption:=inttostr(strtoint(look_res_point_num_label.Caption)+1);
num:=strtoint(look_res_point_num_label.Caption);
if num+1>24 then look_res_graph_points_forw.Enabled:=FALSE
else look_res_graph_points_forw.Enabled:=TRUE;
look_res_graph_points_back.Enabled:=TRUE;
make_point_active(num);
look_res_point_CB.ItemIndex:=look_res_point_CB.ItemIndex+1;

//сбрасываем чек-боксы для точек:
if look_res_graph_options_15_CB.Checked then look_res_graph_options_15_CB.Checked:=FALSE;
if look_res_graph_options_max_CB.Checked then look_res_graph_options_max_CB.Checked:=FALSE;
if look_res_graph_options_min_CB.Checked then look_res_graph_options_min_CB.Checked:=FALSE;
if look_res_graph_options_average_CB.Checked then look_res_graph_options_average_CB.Checked:=FALSE;

//look_res_graph_chart.Repaint;
end;
procedure TMainForm.look_res_point_CBChange(Sender: TObject);
begin
make_point_active(look_res_point_CB.ItemIndex+1);
end;
//Выбор активной точки
procedure TMainForm.make_point_active(num: Integer);
var
  i: integer;
begin
look_res_point_num_label.Caption:=inttostr(num);
with look_res_graph_chart do begin
  for i := 0 to Series[0].Count - 1 do
      if ((i-2) mod 5=0) and (i>0) then
        Axes.Bottom.Items.Item[i].Font.Height:=-9;

 with Axes.Bottom.Items.Item[(num-1)*5+2].Font do
  begin
    Height:=-11;
    style:=[fsBold];
  end;
for i:= 0 to Series[0].Count - 1 do
Series[look_res_graph_choose.ItemIndex].ValueColor[i]:=clRed;

for i:= (num-1)*5 to (num-1)*5+4 do
Series[look_res_graph_choose.ItemIndex].ValueColor[i]:=clYellow;

//Series[SeriesList.Count-1].CustomVertAxis:=CustomAxes[1];
//Series[SeriesList.Count-1].Visible:=TRUE;
//Series[SeriesList.Count-2].CustomVertAxis:=CustomAxes[0];
//Series[SeriesList.Count-2].Visible:=TRUE;

CustomAxes[1].Visible:=TRUE;
//CustomAxes[1].
CustomAxes[1].PositionPercent:=100/24*num;
CustomAxes[0].Visible:=TRUE;
CustomAxes[0].PositionPercent:=100/24*(num-1)+100/24/5;

end;
end;

//сжатие графиков
procedure TMainForm.look_res_log_scaleChange(Sender: TObject);
var
  act_ser: Integer;
begin
act_ser:=0;
      if look_res_graph_chart.Series[0].Visible then act_ser:=0
 else if look_res_graph_chart.Series[1].Visible then act_ser:=1
 else if look_res_graph_chart.Series[2].Visible then act_ser:=2
 else if look_res_graph_chart.Series[3].Visible then act_ser:=3
 else if look_res_graph_chart.Series[4].Visible then act_ser:=4
 else if look_res_graph_chart.Series[5].Visible then act_ser:=5;

koeff[act_ser]:=look_res_log_scale.Value;    
end;
procedure TMainForm.look_res_log_scale_CBClick(Sender: TObject);
var i, act_ser,sign2:integer;
tmp:extended;
begin
with look_res_graph_chart do
begin
//определяем активную серию
act_ser:=0;
      if Series[0].Visible then act_ser:=0
 else if Series[1].Visible then act_ser:=1
 else if Series[2].Visible then act_ser:=2
 else if Series[3].Visible then act_ser:=3
 else if Series[4].Visible then act_ser:=4
 else if Series[5].Visible then act_ser:=5;
//else if Series[6].Visible then act_ser:=6
//else if Series[7].Visible then act_ser:=7;
//для случая сжатия:
      if look_res_log_scale_CB.Checked then
        begin
          look_res_graph_options_15_CB.Enabled:=FALSE;
          look_res_graph_options_15_all_CB.Enabled:=FALSE;
          look_res_graph_options_max_CB.Enabled:=FALSE;
          look_res_graph_options_max_all_CB.Enabled:=FALSE;
          look_res_graph_options_min_CB.Enabled:=FALSE;
          look_res_graph_options_min_all_CB.Enabled:=FALSE;
          look_res_graph_options_average_CB.Enabled:=FALSE;
          look_res_graph_options_average_all_CB.Enabled:=FALSE;
          //изменяем массив сжатий
          resized[act_ser]:=TRUE;
          //проходим все значения серии
          for i:=0 to Series[act_ser].Count-1 do
            begin
              //если 0, то так и оставляем, если нет
              if Series[act_ser].YValue[i]<>0 then
              begin
              //получаем знак
               sign2:=sign(Series[act_ser].YValue[i]);
               //избавляемся от знака
                tmp:=sign(Series[act_ser].YValue[i])*Series[act_ser].YValue[i];
                //сжимаем
                tmp:=in_power(tmp*scales[act_ser],1/koeff[act_ser]);
                     //in_power(scales[act_ser],koeff[act_ser]);
               //возвращаем знак
               Series[act_ser].YValue[i]:=sign2*tmp;
              end;
            end;
            Title.Text.add(main_unit_graphics_compress+
                           floattostr(koeff[act_ser])+
                           main_unit_graphics_compress_unit);
        end
        else
        begin
           look_res_graph_options_15_CB.Enabled:=TRUE;
          look_res_graph_options_15_all_CB.Enabled:=TRUE;
          look_res_graph_options_max_CB.Enabled:=TRUE;
          look_res_graph_options_max_all_CB.Enabled:=TRUE;
          look_res_graph_options_min_CB.Enabled:=TRUE;
          look_res_graph_options_min_all_CB.Enabled:=TRUE;
          look_res_graph_options_average_CB.Enabled:=TRUE;
          look_res_graph_options_average_all_CB.Enabled:=TRUE;
           if resized[act_ser] then begin
           
           resized[act_ser]:=FALSE;
           for i:=0 to Series[act_ser].Count-1 do
            begin
              if Series[act_ser].YValue[i]<>0 then
              begin
              sign2:=sign(Series[act_ser].YValue[i]);
                tmp:=sign(Series[act_ser].YValue[i])*Series[act_ser].YValue[i];

                tmp:=in_power(tmp,koeff[act_ser])/scales[act_ser];

                Series[act_ser].YValue[i]:=sign2*tmp;
              end;
            end;
          look_res_log_scale.Enabled:=TRUE;
          Title.Text.Delete(1);
        end;
        end;
end;
end;

//выбор параметра для отображения
procedure TMainForm.look_res_graph_chooseClick(Sender: TObject);
var i:integer;
begin
with look_res_graph_chart do
    begin
      //Axes.Left.AdjustMaxMin;
      Title.Visible:=TRUE;
      Title.Text.Clear;
      for i:=0 to number_of_params-1 do
        if i=look_res_graph_choose.ItemIndex then
                SeriesList.Items[i].Visible:=TRUE
        else SeriesList.Items[i].Visible:=FALSE;

      case look_res_graph_choose.ItemIndex of
          0:begin
              Title.Text.Append(main_unit_graphics_title_R);
          end;
          1:begin
              Title.Text.Append(main_unit_graphics_title_G0);
            end;
          2:begin
              Title.Text.Append(main_unit_graphics_title_G1);
            end;
          3:begin
              Title.Text.Append(main_unit_graphics_title_G2);
          end;
          4:begin
              Title.Text.Append(main_unit_graphics_title_G3);
          end;
          5:begin
              Title.Text.Append(main_unit_graphics_title_C);
          end;
          6:begin
              Title.Text.Append(main_unit_graphics_title_Usm);
          end;
      end;
      //установка коэффициента сжатия
      look_res_log_scale.Value:=round(koeff[look_res_graph_choose.ItemIndex]);

      //сжатия
      if resized[look_res_graph_choose.ItemIndex] then
      begin
        look_res_log_scale.Enabled:=FALSE;
        look_res_log_scale_CB.Checked:=TRUE;
      end
      else
      begin
        look_res_log_scale.Enabled:=TRUE;
        look_res_log_scale_CB.Checked:=FALSE;
      end;

//Axes.Left.AdjustMaxMin;

//цвета и шрифты значений
 for i:=0 to Series[0].Count - 1 do
  begin
      if ((i-2) mod 5=0) and (i>0) then
        Axes.Bottom.Items.Item[i].Font.Height:=-9;
        Series[look_res_graph_choose.ItemIndex].ValueColor[i]:=clRed;
  end;
 with Axes.Bottom.Items.Item[2].Font do
  begin
    Height:=-11;
    style:=[fsBold];
  end;
for i:= 0 to 4 do
Series[look_res_graph_choose.ItemIndex].ValueColor[i]:=clYellow;


Series[SeriesList.Count-1].CustomVertAxis:=CustomAxes[1];
Series[SeriesList.Count-1].Visible:=TRUE;
Series[SeriesList.Count-2].CustomVertAxis:=CustomAxes[0];
Series[SeriesList.Count-2].Visible:=TRUE;

CustomAxes[1].Visible:=TRUE;
CustomAxes[1].PositionPercent:=100/24;
CustomAxes[0].Visible:=TRUE;
CustomAxes[0].PositionPercent:=100/24/5;

look_res_point_CB.Text:=look_res_point_CB.Items[0];
look_res_point_num_label.Caption:='1';
look_res_graph_points_back.Enabled:=FALSE;
look_res_graph_points_forw.Enabled:=TRUE;
//Axes.Left.AdjustMaxMin;

look_res_point_CB.ItemIndex:=0;

//look_res_log_scale_CB.Checked:=FALSE;
//look_res_log_scale_CBClick(self);
end;
end;
//Выбор измерения
procedure TMainForm.look_res_graph_izm_CBChange(Sender: TObject);
begin
look_res_choise_izm.
  Items[strtoint(look_res_graph_izm_id_CB.Items[look_res_graph_izm_CB.ItemIndex])
                          -1].Selected:=TRUE;

look_res_load_data.Execute;
end;
//клик на графике
procedure TMainForm.look_res_graph_chartClickSeries(Sender: TCustomChart;
  Series: TChartSeries; ValueIndex: Integer; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
//showmessage('value: '+inttostr(ValueIndex));
//showmessage('x: '+inttostr(x));
//showmessage('y: '+inttostr(y));
end;


/////////////////////////////////
/// Закладка численные значения//
////////////////////////////////
//загрузка закладки численные значения
procedure TMainForm.load_number_grid(izm_num:string);
var
  i: integer;
  tmp1: string;
  tmp2: string;
  i1: integer;
begin
  mysql_query(SQL_DM.mysql_query6, 'SELECT '+
'(SELECT `name` FROM '+table_points_name+' WHERE `num`=`point_num`) as point_name, '+
'(SELECT `name` FROM '+table_param_name+' WHERE `id`=`param_num`) as param_name, '+
'(SELECT `id` FROM '+table_izm_name+' WHERE `id`=`izm_num`) as izm_name, '+
'znach FROM `'+table_znacheniya_name+
                '` WHERE `izm_num`='+izm_num +
' ORDER BY `rd_znacheniya`.`param_num`, `point_num` ASC;',1);
with look_res_graph_data_DBGrid do
begin
  ColWidths[0]:=102;
  ColWidths[1]:=65;
  ColWidths[2]:=110;
  ColWidths[3]:=80;

i:=0;i1:=0;
RowCount:=2;
SQL_DM.mysql_DSQ6.DataSet.First;
while not SQL_DM.mysql_DSQ6.DataSet.Eof do
begin
  inc(i);
  AddRow;
   Cells[0,i+i1]:=SQL_DM.mysql_DSQ6.DataSet.FieldByName('point_name').AsString;
   Cells[1,i+i1]:=SQL_DM.mysql_DSQ6.DataSet.FieldByName('param_name').AsString;
   Cells[2,i+i1]:=SQL_DM.mysql_DSQ6.DataSet.FieldByName('izm_name').AsString;

   if Cells[1,i]='R' then
      Cells[3,i+i1]:=floattostrf(
        SQL_DM.mysql_DSQ6.DataSet.FieldByName('znach').AsFloat/scales[0], ffNumber,5,3)+' МОм'
   else if Cells[1,i]='G0' then
        Cells[3,i+i1]:=floattostrf(SQL_DM.mysql_DSQ6.DataSet.FieldByName('znach').AsFloat/scales[1], ffNumber,5,3)+' мкСм'
   else   if Cells[1,i]='G1' then
        Cells[3,i+i1]:=floattostrf(SQL_DM.mysql_DSQ6.DataSet.FieldByName('znach').AsFloat/scales[2], ffNumber,5,3)+' мкСм'
   else   if Cells[1,i]='G2' then
        Cells[3,i+i1]:=floattostrf(SQL_DM.mysql_DSQ6.DataSet.FieldByName('znach').AsFloat/scales[3], ffNumber,5,3)+' мкСм'
   else   if Cells[1,i]='G3' then
        Cells[3,i+i1]:=floattostrf(SQL_DM.mysql_DSQ6.DataSet.FieldByName('znach').AsFloat/scales[4], ffNumber,4,3)+' мкСм'
   else   if Cells[1,i]='C' then
        Cells[3,i+i1]:=floattostrf(SQL_DM.mysql_DSQ6.DataSet.FieldByName('znach').AsFloat/scales[5], ffNumber,4,3)+' нФ';

    tmp1:=Cells[0,i+i1];
    tmp2:='';
    if i>1 then tmp2:=Cells[0,i-1+i1];
    if (tmp1=tmp2) then
    begin
      MergeCells(0,i-1,1,i1+2);
      MergeCells(1,i-1,1,i1+2);
      MergeCells(2,i-1,1,i1+2);
      dec(i);
      inc(i1);
    end
    else
    begin
      i:=i+i1;
      i1:=0;
    end;
    SQL_DM.mysql_DSQ6.DataSet.Next;
end;
end;

end;

procedure TMainForm.look_res_number_filter_genparam_CBClick(Sender: TObject);
begin
if look_res_number_filter_genparam_CB.Checked then
  look_res_number_genparam_panel.Show
else look_res_number_genparam_panel.Hide;
end;
//выбор измерения
procedure TMainForm.look_res_number_izm_CBChange(Sender: TObject);
begin
look_res_choise_izm.Items[
    strtoint(look_res_number_izm_id_CB.Items[look_res_number_izm_CB.ItemIndex])
                          -1].Selected:=TRUE;

look_res_load_data.Execute;
end;

//Служебные процедуры, таблица численных значений
procedure TMainForm.look_res_graph_data_DBGridGetAlignment(Sender: TObject;
  ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment);
begin
HAlign:=taCenter;
VAlign:=vtaBottom;
end;


/////////////////////////////////
/// Закладка диагноза          //
////////////////////////////////
//Создание отчета
procedure TMainForm.look_res_make_report_btnClick(Sender: TObject);
var
  XL: TExcelApplication;
  WB: _WorkBook;
  //oRng: ExcelRange;
  ASheet: _WorkSheet;
const lcid=LOCALE_USER_DEFAULT;
begin
 // запускаем новый экземпляр Excel'я
  XL := TExcelApplication.Create(nil);
  try
    XL.ConnectKind := ckNewInstance;
    XL.Connect; // подключение
    XL.AutoQuit := FALSE; // по умолчанию это свойство TRUE только в unit ExcelXP
    XL.Visible[lcid] := TRUE;
    // здесь работаем с Excel'ем
    XL.DisplayAlerts [lcid]:= FALSE;
    // новый документ
    WB:=XL.Workbooks.Add(EmptyParam, lcid);
    ASheet := (XL.ActiveWorkbook.ActiveSheet as _Worksheet);
    ASheet.Range['A1', EmptyParam].Value2 := 'Любой текст';
  finally
    // отсоединяемся
    XL.UserControl := TRUE; // отдадим управление пользователю
    //XL.Quit; // закрыть Excel
    XL.Disconnect;
    FreeAndNil(XL);
  end;
end;

//Служебные процедуры таблицы результатов,
procedure TMainForm.look_res_diagnoz_data_StringGridGetAlignment(
  Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment;
  var VAlign: TVAlignment);
begin
if ACol in [0,3,6,9] then
  if ARow in [0,1,2,6,7,11,13] then HAlign:=taCenter;
VAlign:=vtatop;
  
end;
procedure TMainForm.look_res_diagnoz_data_StringGridGetCellBorderProp(
  Sender: TObject; ARow, ACol: Integer; LeftPen, TopPen, RightPen,
  BottomPen: TPen);
begin
if (ACol=0) then LeftPen.Color:=clSilver;
if ACol in [1,4,7,10] then
  begin
    if ARow in [5,6,7,10,11,12] then
      begin
        if ARow in [6,7,11,12] then TopPen.Style:=psClear;
        if ARow in [5,6,10,11] then BottomPen.Style:=psClear;
      end;

  end;
  
end;
procedure TMainForm.look_res_diagnoz_data_StringGridGetDisplText(
  Sender: TObject; ACol, ARow: Integer; var Value: string);
begin
if ACol in [2,5,8,11] then
  if ARow in [3,4,5,6,8,9,10,11] then Value:=diagnoz_table_unit;
if ACol in [0,3,6,9] then
  if ARow in [6,11] then Value:=summ_all;


end;
procedure TMainForm.look_res_diagnoz_data_StringGridGetFloatFormat(
  Sender: TObject; ACol, ARow: Integer; var IsFloat: Boolean;
  var FloatFormat: string);
begin
FLoatFormat:= '%.3f';
end;

procedure TMainForm.look_res_diagnoz_points_table_switchClick(Sender: TObject);
var stream:TFileStream;
begin
look_res_diagnoz_help_StringGrid.ColCount:=9;
look_res_diagnoz_help_StringGrid.RowCount:=15;


stream:=TFileStream.Create('table2.dat', fmOpenRead);
 look_res_diagnoz_help_StringGrid.LoadFromBinStream(stream);
stream.Destroy;
look_res_diagnoz_help_StringGrid.ColWidths[0]:=21;
look_res_diagnoz_help_StringGrid.ColWidths[1]:=58;
look_res_diagnoz_help_StringGrid.ColWidths[2]:=83;
look_res_diagnoz_help_StringGrid.ColWidths[3]:=73;
look_res_diagnoz_help_StringGrid.ColWidths[4]:=60;
look_res_diagnoz_help_StringGrid.ColWidths[5]:=87;
look_res_diagnoz_help_StringGrid.ColWidths[6]:=70;
look_res_diagnoz_help_StringGrid.ColWidths[7]:=105;
look_res_diagnoz_help_StringGrid.ColWidths[8]:=104;
end;
procedure TMainForm.look_res_diagnoz_koeffs_table_switchClick(Sender: TObject);
var stream:TFileStream;
begin
look_res_diagnoz_help_StringGrid.ColCount:=4;
look_res_diagnoz_help_StringGrid.RowCount:=9;



stream:=TFileStream.Create('table3.dat', fmOpenRead);
 look_res_diagnoz_help_StringGrid.LoadFromBinStream(stream);
stream.Destroy;
look_res_diagnoz_help_StringGrid.ColWidths[0]:=32;
look_res_diagnoz_help_StringGrid.ColWidths[1]:=32;
look_res_diagnoz_help_StringGrid.ColWidths[2]:=32;
look_res_diagnoz_help_StringGrid.ColWidths[3]:=422;

end;
//среднее значение сопротивления точки в измерении
function TMainForm.Get_R(point:string; measure:string; type_of:integer):string;
begin
//При расчетах нулевые-отрицательные-ошибочные значения выкидываются и не учитываются!!!
 
case type_of of
  0: mysql_query(SQL_DM.mysql_query4,
      'SELECT AVG(`znach`) as value FROM `'+table_znacheniya_name+'` WHERE '+
      '(`izm_num`='+measure+') AND '+
      '(`param_num`=(SELECT `id` FROM '+table_param_name+' WHERE `name`=''R'')) AND '+
      '(`znach`>=0) AND '+
      '(`point_num`=(SELECT `num` FROM '+table_points_name+' WHERE `name`='''+point+'''))',2);
  1: mysql_query(SQL_DM.mysql_query4,
      'SELECT `znach` as value FROM `'+table_znacheniya_name+'` WHERE '+
      '(`izm_num`='+measure+') AND'+
      '(`param_num`=(SELECT `id` FROM '+table_param_name+' WHERE `name`=''R'')) AND'+
      '(`znach`>=0) AND '+
      '(`povtor_num`=1) AND '+
      '(`point_num`=(SELECT `num` FROM '+table_points_name+' WHERE `name`='''+point+'''))',2);
  2: mysql_query(SQL_DM.mysql_query4,
      'SELECT MAX(`znach`) as value FROM `'+table_znacheniya_name+'` WHERE '+
      '(`izm_num`='+measure+') AND'+
      '(`param_num`=(SELECT `id` FROM '+table_param_name+' WHERE `name`=''R'')) AND'+
      '(`znach`>=0) AND '+
      '(`point_num`=(SELECT `num` FROM '+table_points_name+' WHERE `name`='''+point+'''))',2);
  3: mysql_query(SQL_DM.mysql_query4,
      'SELECT MIN(`znach`) as value FROM `'+table_znacheniya_name+'` WHERE '+
      '(`izm_num`='+measure+') AND'+
      '(`param_num`=(SELECT `id` FROM '+table_param_name+' WHERE `name`=''R'')) AND'+
      '(`znach`>=0) AND '+
      '(`point_num`=(SELECT `num` FROM '+table_points_name+' WHERE `name`='''+point+'''))',2);
end;

try
  result:=floattostr(SQL_DM.mysql_DSQ4.DataSet.FieldByName('value').AsFloat/scales[0])
except
  result:='0';
end;
end;


/////////////////////////////////
/// Пользовательские процедуры //
////////////////////////////////
function TMainForm.Sign(X:Extended):Integer;
begin
    if X>0 then
        Result := 1
    else if X<0 then
        Result := -1
    else
        Result := 0;
end;
function TMainForm.In_power (x:extended; n:extended):extended;
begin
  result:=exp(n*ln(x));
end;
procedure TMainForm.load_info_to_diagnoz_tables(create_files:boolean);
var stream:TFileStream;
begin
//Флаг, который устанавливает, будут ли заново создаваться файлы *.dat
if create_files then
  begin
    //загружаем начальную информацию и форматируем колонки в диагнозе
    with MainForm.look_res_diagnoz_data_StringGrid do
      begin
        //Содержание
          //Надписи
            Cells[0,0]:='РУКИ';
            Cells[6,0]:='НОГИ';

            Cells[0,1]:='Левая рука';
            Cells[3,1]:='Правая рука';
            Cells[6,1]:='Левая нога';
            Cells[9,1]:='Правая нога';

            Cells[0,2]:='Инь';
            Cells[0,7]:='Ян';
            Cells[3,2]:='Инь';
            Cells[3,7]:='Ян';
            Cells[6,2]:='Инь';
            Cells[6,7]:='Ян';
            Cells[9,2]:='Инь';
            Cells[9,7]:='Ян';

            Cells[0,12]:='Сумма левой =';
            Cells[3,12]:='Сумма правой =';
            Cells[6,12]:='Сумма левой =';
            Cells[9,12]:='Сумма правой =';

            Cells[0,13]:='Сумма рук =';
            Cells[6,13]:='Сумма ног =';

            CellProperties[0,0].FontStyle:=[fsBold];
            CellProperties[6,0].FontStyle:=[fsBold];
            CellProperties[0,1].FontStyle:=[fsBold];
            CellProperties[3,1].FontStyle:=[fsBold];
            CellProperties[6,1].FontStyle:=[fsBold];
            CellProperties[9,1].FontStyle:=[fsBold];
            CellProperties[0,2].FontStyle:=[fsBold];
            CellProperties[0,7].FontStyle:=[fsBold];
            CellProperties[3,2].FontStyle:=[fsBold];
            CellProperties[3,7].FontStyle:=[fsBold];
            CellProperties[6,2].FontStyle:=[fsBold];
            CellProperties[6,7].FontStyle:=[fsBold];
            CellProperties[9,2].FontStyle:=[fsBold];
            CellProperties[9,7].FontStyle:=[fsBold];
            CellProperties[0,6].FontStyle:=[fsBold];
            CellProperties[3,6].FontStyle:=[fsBold];
            CellProperties[6,6].FontStyle:=[fsBold];
            CellProperties[9,6].FontStyle:=[fsBold];
            CellProperties[0,11].FontStyle:=[fsBold];
            CellProperties[3,11].FontStyle:=[fsBold];
            CellProperties[6,11].FontStyle:=[fsBold];
            CellProperties[9,11].FontStyle:=[fsBold];

            CellProperties[0,12].FontStyle:=[fsBold];
            CellProperties[3,12].FontStyle:=[fsBold];
            CellProperties[6,12].FontStyle:=[fsBold];
            CellProperties[9,12].FontStyle:=[fsBold];

            CellProperties[0,13].FontStyle:=[fsBold];
            CellProperties[6,13].FontStyle:=[fsBold];

            CellProperties[1,6].FontStyle:=[fsBold];
            CellProperties[2,6].FontStyle:=[fsBold];
            CellProperties[4,6].FontStyle:=[fsBold];
            CellProperties[5,6].FontStyle:=[fsBold];
            CellProperties[7,6].FontStyle:=[fsBold];
            CellProperties[8,6].FontStyle:=[fsBold];
            CellProperties[10,6].FontStyle:=[fsBold];
            CellProperties[11,6].FontStyle:=[fsBold];

            CellProperties[1,11].FontStyle:=[fsBold];
            CellProperties[2,11].FontStyle:=[fsBold];
            CellProperties[4,11].FontStyle:=[fsBold];
            CellProperties[5,11].FontStyle:=[fsBold];
            CellProperties[7,11].FontStyle:=[fsBold];
            CellProperties[8,11].FontStyle:=[fsBold];
            CellProperties[10,11].FontStyle:=[fsBold];
            CellProperties[11,11].FontStyle:=[fsBold];


            //Объединение
            MergeCells(0,0,6,1); //руки
            MergeCells(6,0,6,1); //ноги
            MergeCells(0,1,3,1); //левая рука
            MergeCells(3,1,3,1); //правая рука
            MergeCells(6,1,3,1); //левая нога
            MergeCells(9,1,3,1); //правая нога
            MergeCells(0,2,3,1); //Инь и Ян
            MergeCells(3,2,3,1); //Инь и Ян
            MergeCells(6,2,3,1); //Инь и Ян
            MergeCells(9,2,3,1); //Инь и Ян
            MergeCells(0,7,3,1); //Инь и Ян
            MergeCells(3,7,3,1); //Инь и Ян
            MergeCells(6,7,3,1); //Инь и Ян
            MergeCells(9,7,3,1); //Инь и Ян

            MergeCells(0,13,6,1); //сумма рук
            MergeCells(6,13,6,1); //сумма ног

            MergeCells(0,12,3,1); //сумма руки
            MergeCells(3,12,3,1); //сумма руки
            MergeCells(6,12,3,1); //сумма ноги
            MergeCells(9,12,3,1); //сумма ноги

// fmOpenRead       = $0000;
//  fmOpenWrite      = $0001;
//  fmOpenReadWrite  = $0002;

            stream:=TFileStream.Create('table1.dat',fmCreate);
              stream.Position:=0;
              //stream.Write(sizeof() 'Таблица коэффициентов',strlen('Таблица коэффициентов'))));
              SaveToBinStream(stream);
            stream.Destroy;
        end;

      with MainForm.look_res_diagnoz_help_StringGrid do
        begin
            Clear;
            LoadFromCSV('Справочные материалы. Методика Риодораку. точки.csv');
            InsertRows(0,1);
            Cells[0,0]:=Cells[0,1];
            MergeCells(0,0,1,3);

            Cells[1,0]:=Cells[1,1];
            MergeCells(1,0,1,3);

            Cells[2,0]:=Cells[2,1];
            MergeCells(2,0,6,1);
            CellProperties[2,0].Alignment:=taCenter;

            Cells[2,1]:=Cells[2,2];
            Cells[3,1]:=Cells[3,2];
            Cells[4,1]:=Cells[4,2];
            Cells[5,1]:=Cells[5,2];
            Cells[6,1]:=Cells[6,2];
            Cells[7,1]:=Cells[7,2];

            CellProperties[2,1].Alignment:=taCenter;
            CellProperties[3,1].Alignment:=taCenter;
            CellProperties[4,1].Alignment:=taCenter;
            CellProperties[5,1].Alignment:=taCenter;
            CellProperties[6,1].Alignment:=taCenter;
            CellProperties[7,1].Alignment:=taCenter;
            CellProperties[8,0].Alignment:=taCenter;

            MergeCells(2,1,1,2);
            MergeCells(3,1,1,2);
            MergeCells(4,1,1,2);
            MergeCells(5,1,1,2);
            MergeCells(6,1,1,2);
            MergeCells(7,1,1,2);

            Cells[8,0]:=Cells[8,1];
            MergeCells(8,0,1,3);
            stream:=TFileStream.Create('table2.dat',fmCreate);
                stream.Position:=0;
                //stream.Write(sizeof() 'Таблица коэффициентов',strlen('Таблица коэффициентов'))));
                SaveToBinStream(stream);
            stream.Destroy;
        end;

        with MainForm.look_res_diagnoz_help_StringGrid do
          begin
            Clear;
            ColCount:=4;
            LoadFromCSV('Справочные материалы. Методика Риодораку. коэф.csv');
            MergeCells(0,0,4,2);
            CellProperties[0,0].FontStyle:=[fsBold];
            CellProperties[0,0].Alignment:=taCenter;
            stream:=TFileStream.Create('table3.dat',fmCreate);
                stream.Position:=0;
                //stream.Write(sizeof() 'Таблица коэффициентов',strlen('Таблица коэффициентов'))));
                SaveToBinStream(stream);
            stream.Destroy;
          end;
  end;
    stream:=TFileStream.Create('table1.dat',fmOpenRead);
    MainForm.look_res_diagnoz_data_StringGrid.LoadFromBinStream(stream);
    stream.Destroy;
    MainForm.look_res_diagnoz_points_table_switchClick(MainForm);
end;





end.
