<?php
class report_psychophysical extends c_report
{
 var $title='Оценка психофизиологического состояния' ;
    public $use_fusioncharts=1 ;

    var $chart_data=[];

    function setting($options=array())
    {
        $now=getdate() ;
        if (!$this->filter['data_from']) $this->filter['data_from']=date('d.m.Y',mktime(0,0,0,$now['mon'],$now['mday'],$now['year']));
        if (!$this->filter['data_to'])   $this->filter['data_to']=date('d.m.Y',mktime(0,0,0,$now['mon'],$now['mday']+1,$now['year'])-1);
        if (_sizeof($_SESSION['ARR_mo_tk_type']))  foreach ($_SESSION['ARR_mo_tk_type'] as $key_tk=>$value_tk) {
            $tk_type_arr[$key_tk+1]=$value_tk;
        }
        $arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;
        ?>
        <div id="panel_filter">
             <form id="sky-form" class="sky-form"><input type="hidden" name="filter_dir" value="<?echo _CUR_REPORT_DIR?>">
                 <fieldset>
                     <div class="row">
                         <div class="row">
                             <?
                             $this->filter_section_select('group_id',ESMO()->group_title.':',2,$arr_groups) ;
                             $this->filter_section_select('tk','Тип контроля:',2,$tk_type_arr) ;
                             $this->filter_section_input_text('data_from','Дата от:',2,array('class'=>'datepicker','required'=>1)) ;
                             $this->filter_section_input_text('data_to','Дата до:',2,array('class'=>'datepicker','required'=>1)) ;
                             $this->filter_section_input_text('name','ФИО:',2,array('auto_complete'=>"autocomplette_personal_name")) ;
                             $this->filter_section_input_text('IK','Порог ВИК:',2) ;
                             ?>
                         </div>
                 </fieldset>
                 <?$this->panel_buttons();?>
              </form>
        </div><br>
        <?
    }

    function panel_info_filter()
    {
        $_str=array() ; $info=array() ; $title='' ;

        if ($this->filter['tk'])                        $info['Тип контроля']=$_SESSION['ARR_mo_tk_type'][$this->filter['tk']-1]  ;
        if ($this->filter['data_from'])                 $info['c']=$this->filter['data_from'] ;
        if ($this->filter['data_to'])                   $info['по']=$this->filter['data_to'] ;
        if ($this->filter['group_id'])                  $info[ESMO()->group_title.':']=ACCOUNTS()->get_group_name($this->filter['group_id'])  ;
        if ($this->filter['name'])                            $info['ФИО']='"'.$this->filter['name'].'"' ;

        if (_sizeof($info)) foreach($info as $title=>$value) $_str[]=$title.': <strong>'.$value.'</strong>' ;
        if (_sizeof($_str)) $title='<p class=center>'.implode(' ',$_str).'</p>' ;
        return $title ;
    }

    function prepare_data($options=array())
    {
        $day_time_step=24*60*60;
        $_usl=[];
        $_usl[]='diastolic>0';
        $_usl[]='pulse>0';
        $_usl[]='dopusk in (1,2)';
        if ($this->filter['IK']) $IK_value=$this->filter['IK']; else $IK_value=0;
        if ($this->filter['name'])
        {   $arr_ids=execSQL_line('select pkey from obj_site_personals where clss=211 and obj_name like "%'.addslashes($this->filter['name']).'%"') ;
            if (_sizeof($arr_ids))  $_usl[]='member_id in ('.implode(',',$arr_ids).')' ;
            else                   $_usl[]='member_id=-1' ;
        }
        if ($this->filter['personal_id']) $_usl[]='member_id='.$this->filter['personal_id'] ;
        if ($this->filter['tk']) $_usl[]='tk='.($this->filter['tk']-1) ;
        if ($this->filter['data_from']) {
            $time_from=strtotime($this->filter['data_from']);
            $_usl[]='c_data>='.$time_from ;
        }
        if ($this->filter['data_to']) {
            $arr=explode(' ',trim($this->filter['data_to'])) ;
            $time_to=(!$arr[1])? strtotime($this->filter['data_to'].' 23:59:59'):strtotime($this->filter['data_to']) ;
            $_usl[]='c_data<='.$time_to ;
        }
        if (_sizeof($_usl)) $usl=implode(' and ',$_usl) ;
//        damp_array($_usl,1,-1);

        $recs=execSQL('select * from obj_site_mo_session where '.$usl);

        $persons_data=[];

        if ($this->filter['personal_id'] or $this->filter['name']) {
            $this->chart_data['type']='personal';
            if (_sizeof($recs)) foreach ($recs as $rec) {
                $date_mo=getdate($rec['c_data']);
                $day_start_date=mktime(0,0,0,$date_mo['mon'],$date_mo['mday'],$date_mo['year']);
                $this->chart_data['members'][$rec['member_id']]=1;
                if (!$persons_data[$day_start_date][$rec['member_id']]) {
                    $persons_data[$day_start_date][$rec['member_id']]=1;
                    $IK=round(100*(1-$rec['diastolic']/$rec['pulse']),2);
                    $this->chart_data['data'][$rec['member_id']][$day_start_date]=$IK;
                }
            }
            if (_sizeof($this->chart_data['data'])) ksort($this->chart_data['data']);
        } elseif ($time_to-$time_from<$day_time_step) {
            $this->chart_data['type']='pie';
            if (_sizeof($recs)) foreach ($recs as $rec) {
                $IK=0;
                if (!$persons_data[$rec['member_id']]) {
                    $persons_data[$rec['member_id']]=1;
                    $IK=round(100*(1-$rec['diastolic']/$rec['pulse']),2);
//                echo $IK;
                    if ($IK<$IK_value) $this->chart_data['data']['parasympathetic']++; else $this->chart_data['data']['sympathetic']++;
                }
            }
        } else {
            $this->chart_data['type']='graf';
            if (_sizeof($recs)) foreach ($recs as $rec) {
                $date_mo=getdate($rec['c_data']);
                $day_start_date=mktime(0,0,0,$date_mo['mon'],$date_mo['mday'],$date_mo['year']);
//                echo $day_start_date.'<br>';
                $IK=0;
                if (!$persons_data[$day_start_date][$rec['member_id']]) {
                    $persons_data[$day_start_date][$rec['member_id']]=1;
                    $IK=round(100*(1-$rec['diastolic']/$rec['pulse']),2);
                    if ($IK<$IK_value) $this->chart_data['data'][$day_start_date]['parasympathetic']++; else $this->chart_data['data'][$day_start_date]['sympathetic']++;
                }
            }
            if (_sizeof($this->chart_data['data'])) ksort($this->chart_data['data']);
        }

    }

    function HTML_report_body($options=array())
    {

        $this->prepare_data($options);


        switch ($this->chart_data['type']) {
            case 'pie': if ($this->chart_data['data']) $this->report_graf_pie(); break;
            case 'graf': if ($this->chart_data['data']) $this->report_graf(); break;
            case 'personal': {
                if (_sizeof($this->chart_data['members'])) foreach ($this->chart_data['members'] as $member_id=>$value) {
                    $this->report_graf_personal_line($member_id);
                }
            } break;
        }
    }

    function report_graf_pie()
    {
        $caption='Оценка психофизиологического состояния' ;
        ?><div id="chart-container">Подождите, идет построение графика</div>
        <script type="text/javascript">
         $j(document).ready(function(){
            FusionCharts.ready(function(){
                var revenueChart2 = new FusionCharts({
                    type: 'pie2d',
                    renderAt: 'chart-container',
                    width: '1000',
                    height: '400',
                    dataFormat: 'json',
                    dataSource: {
                        "chart": {
                            //"subCaption": "от <? echo date('d.m.Y',$this->filter['time_from']).' до '.date('d.m.Y',$this->filter['time_to'])?>",
                            "caption": "<?echo $caption?>",
                            "use3DLighting": "0",
                            "showPercentValues": "1",
                            "decimals": "1",
                            "useDataPlotColorForLabels": "0",
                            "theme": "fusion",
                            "animation": "0",
                            "showBorder" : "0",
                            "bgColor" : "#ffffff",
                            "showLegend": "1"
                        },
                        "data":
                            [
                                {
                                    "label": "Преобладание симпатического звена",
                                    "value": "<?echo $this->chart_data['data']['parasympathetic']?>",
                                    "color": "00ff00"
                                },
                                {
                                    "label": "Преобладание парасимпатического  звена",
                                    "value": "<?echo $this->chart_data['data']['sympathetic']?>",
                                    "color": "ff0000"
                                }
                            ]
                    }
                });

                revenueChart2.render();
            });
         }) ;
        </script>
        <style type="text/css">#chart-container{margin:0 auto;width:1000px;}</style>
        <?
    }

    function report_graf()
    {
        $caption='Оценка психофизиологического состояния' ;
        ?><div id="chart-container">Подождите, идет построение графика</div>
        <script type="text/javascript">
         $j(document).ready(function(){
            FusionCharts.ready(function(){
                var revenueChart2 = new FusionCharts({
                    type: 'stackedcolumn2d',
                    renderAt: 'chart-container',
                    width: '1000',
                    height: '400',
                    dataFormat: 'json',
                    dataSource: {
                        "chart": {
                            //"subCaption": "от <? echo date('d.m.Y',$this->filter['time_from']).' до '.date('d.m.Y',$this->filter['time_to'])?>",
                            "caption": "<?echo $caption?>",
                            "showPercentValues": "1",
                            "theme": "fusion",
                            "animation": "0",
                            "showBorder" : "0",
                            "bgColor" : "#ffffff",
                            "showLegend": "1",
                            "showPlotBorder": "0",
                            "usePlotGradientColor": "0"
                        },
                        "categories": [
                            {
                                "category": [
                                    <?
                                        foreach ($this->chart_data['data'] as $date_key=>$value){
                                            echo '{';
                                            echo '"label": "'.date('d.m.Y',$date_key).'"';
                                            echo '},';
                                        }
                                    ?>
                                ]
                            }
                        ],
                        "dataset": [
                            {
                                "seriesname": "Преобладание симпатического звена",
                                "color": "ff0000",
                                "data": [
                                    <?
                                    foreach ($this->chart_data['data'] as $date_key=>$value){
                                        echo '{';
                                        echo '"value": "'.$value['sympathetic'].'"';
                                        echo '},';
                                    }
                                    ?>
                                ]
                            },
                            {
                                "seriesname": "Преобладание парасимпатического  звена",
                                "color": "00ff00",
                                "data": [
                                    <?
                                    foreach ($this->chart_data['data'] as $date_key=>$value){
                                        echo '{';
                                        echo '"value": "'.$value['parasympathetic'].'"';
                                        echo '},';
                                    }
                                    ?>
                                ]
                            }
                        ]
                    }
                });

                revenueChart2.render();
            });
         }) ;
        </script>
        <style type="text/css">#chart-container{margin:0 auto;width:1000px;}</style>
        <?
    }

    function report_graf_personal_line($member_id)
    {
        $person=PERSONAL()->get_personal_by_id($member_id);
        $caption='Оценка психофизиологического состояния' ;
        $subCaption=$person['obj_name'].' '.$person['dr'];
        ?><div id="chart-container-<?echo $member_id?>">Подождите, идет построение графика</div>
        <script type="text/javascript">
         $j(document).ready(function(){
            FusionCharts.ready(function(){
                var revenueChart2 = new FusionCharts({
                    type: 'scrollline2d',
                    renderAt: 'chart-container-<?echo $member_id?>',
                    width: '1200',
                    height: '400',
                    dataFormat: 'json',
                    dataSource: {
                        "chart": {
                            "caption": "<?echo $caption?>",
                            "subCaption": "<?echo $subCaption?>",
                            "showPercentValues": "1",
                            "theme": "fusion",
                            "animation": "0",
                            "showBorder" : "0",
                            "bgColor" : "#ffffff",
                            "showLegend": "1",
                            "lineThickness": "3",
                            "flatScrollBars": "1",
                            "scrollheight": "10",
                            "numVisiblePlot": "14",
                        },
                        "categories": [
                            {
                                "category": [
                                    <?
                                    foreach ($this->chart_data['data'][$member_id] as $date_key=>$value){
                                        echo '{';
                                        echo '"label": "'.date('d.m.Y',$date_key).'"';
                                        echo '},';
                                    }
                                    ?>
                                ]
                            }
                        ],
                        "dataset": [
                            {
                                "data": [
                                    <?
                                    foreach ($this->chart_data['data'][$member_id] as $date_key=>$value){
                                        echo '{';
                                        echo '"value": "'.$value.'"';
                                        echo '},';
                                    }
                                    ?>
                                ]
                            }
                        ],
                        <?if ($this->filter['IK']) {?>
                        "trendlines": [{
                            "line": [{
                                "color": "ff0000",
                                "thickness": "2",
                                "startValue": "<?echo $this->filter['IK']?>",
                                "endValue": "<?echo $this->filter['IK']?>"
                            }]
                        }]
                        <?}?>
                    }
                });

                revenueChart2.render();
            });
         }) ;
        </script>
        <style type="text/css">#chart-container-<?echo $member_id?>{margin:0 auto;width:1200px;}</style>
        <?
    }

}

?>
