<?
class report_itog_score extends c_report
{  var $title='Показатели SCORE системы ЭСМО' ;
   var $filter=array() ;
   //var $url_report='/cab/reports/itog6/' ;
   public $use_fusioncharts=1 ;
   //var $PDF_master='TCPDF' ;  // короткие отчеты выгружвать через обычный  PDF
   var $view_graf=1 ;
   var $view_table=1 ;
   var $time_int=array(1=>'Текущие сутки',2=>'Текущая неделя',3=>'Текущий месяц') ;
   var $step='1m' ;
    var $allow_export_to_csv=1 ;
    public $PDF_page_orientation='P' ; // L P

   function setting()
   { $data_info=execSQL_van('select min(c_data) as min_data,max(c_data) as max_data from obj_site_mo_session') ;
     $t=$data_info['min_data'] ;  $arr_from=array() ; $arr_to=array() ;
     if ($data_info['max_data']>$data_info['min_data']) while($t<$data_info['max_data'])
        {   $ts=getdate($t) ;
            $cur_month=mktime(0,0,0,$ts['mon'],1,$ts['year']) ;
            $arr_from[$cur_month]=get_month_year($cur_month,'month year') ;
            $cur_month=mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ;
            $arr_to[$cur_month]=get_month_year($cur_month,'month year') ;
            $t=mktime(0,0,0,$ts['mon']+1,1,$ts['year']) ;
        }

     if ($this->filter['time_int']) unset($this->filter['time_from'],$this->filter['time_to']) ;

     $arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;
     list($arr_orgs_ids,$arr_otdel_ids,$arr_works_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter) ;

     ?><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">
                       <? $this->filter_section_select('group_id',$GLOBALS['LS_person_group_title'].':',2,$arr_groups) ;
                          $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
                          $this->filter_section_select_multiple('otdel_ids','Подразделение:',2,$arr_otdel_ids) ;
                          $this->filter_section_select('time_int','Временной интервал:',2,$this->time_int) ;
                          $this->filter_section_select('time_from','С, месяц:',2,$arr_from) ;
                          $this->filter_section_select('time_to','По, месяц:',2,$arr_to) ;
                       ?>
                   </div>
               </fieldset>
               <?$this->panel_buttons();?>
           </form>
        </div>
     <?
   }

    function setting_small()
      {   $arr_orgs_ids=PERSONAL()->get_arr_orgs_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">
                                <?
                                $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
                                ?>
                                <section class="col col-2 buttons"><?$this->panel_button_apply();?></section>
                            </div>
                        </fieldset>

                    </form>
            </div>
        <?
      }

  function get_arr_info_filters()
  { $info=parent::get_arr_info_filters() ;
    if ($this->filter['time_int'])                        $info['временной интервал']=$this->time_int[$this->filter['time_int']] ;
    return $info ;
 }

function HTML_report_body($options=array())
{   $result=$this->prepare_result_data() ;
    //damp_array($result,1,-1) ;
    ?><div id="reports_itog1"><?
       if ($this->view_graf) $this->report_graf($result) ;
       if ($this->view_table) $this->report_table($result) ;
    ?></div><?
}

function prepare_result_data()
{
    $data_info=execSQL_van('select min(c_data) as min_data,max(c_data) as max_data from obj_site_mo_session') ;

        if (!$this->filter['time_from'])
        { $ts=getdate($data_info['min_data']) ;
          $this->filter['time_from']=mktime(0,0,0,$ts['mon'],1,$ts['year']) ;;
        }

        // определение time_from по time_int должно находиться именно тут, чтобы перезадавать значение time_from.
        if ($this->filter['time_int'])
        { $ts=getdate() ;
          //damp_array($ts,1,-1) ;
          switch($this->filter['time_int'])
          { case 1: $this->filter['time_from']=mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']) ;; break ;
            case 2: $week_day=($ts['wday'])? $ts['wday']-1:6 ; // для коррекции что ВСК = 0, а ПНД = 1
                    $this->filter['time_from']=mktime(0,0,0,$ts['mon'],$ts['mday']-$week_day,$ts['year']) ;; break ;
            case 3: $this->filter['time_from']=mktime(0,0,0,$ts['mon'],1,$ts['year']) ;; break ;
          }
        }


        if (!$this->filter['time_to'])
        { $max_data=($data_info['max_data']>$this->filter['time_from'])? $data_info['max_data']:$this->filter['time_from'] ;
          $ts=getdate($max_data) ;
          $this->filter['time_to']=mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ;;
        }

        // определение time_to по time_int должно находиться именно тут, чтобы перезадавать значение time_to.
        if ($this->filter['time_int'])
        { $ts=getdate() ;
          switch($this->filter['time_int'])
          { case 1: $ts=getdate($this->filter['time_from']) ;
                    $this->filter['time_to']=mktime(23,59,59,$ts['mon'],$ts['mday'],$ts['year']) ;; break ;
            case 2: $ts=getdate($this->filter['time_from']) ;
                    $this->filter['time_to']=mktime(23,59,59,$ts['mon'],$ts['mday']+6,$ts['year']) ;; break ;
            case 3: $ts=getdate($this->filter['time_from']) ;
                    $this->filter['time_to']=mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ;; break ;
          }
        }


        //echo 'from: '.date('d.m.Y H:i:s',$this->filter['time_from']).'<br>' ;
        //echo 'to: '.date('d.m.Y H:i:s',$this->filter['time_to']).'<br>' ;


        //execSQL_update('update obj_site_mo_session set res_n=2 where narko like "%распознования%" or narko like "%распознания%"',2) ;
        //execSQL_update('update obj_site_mo_session set res_n=3 where narko like "%зрачки%" or narko like "%Зрачки%" or narko like "%реакция%"',2) ;


        //$recs=ESMO()->get_mo_recs($options) ;
        //print_2x_arr($recs) ;
        $result=array() ;$result2=array() ; $all_reason=array() ; $all_reason2=array() ;
        $tf=getdate($this->filter['time_from']) ;
        $tt=getdate($this->filter['time_to']) ;
        if ($tf['mday']==$tt['mday'] and $tf['mon']==$tt['mon'] and $tf['year']==$tt['year']) $this->step='1h' ;
        else if ($tf['mon']==$tt['mon'] and $tf['year']==$tt['year'])                         $this->step='1d' ;
        else                                                                                  $this->step='1m' ;

        //echo 'step='.$this->step.'<br>' ;

        $t=$this->filter['time_from'] ;
        while($t<=$this->filter['time_to'])
        {   $ts=getdate($t) ;   $t1=$t ;
            $cur_month=mktime(0,0,0,$ts['mon'],1,$ts['year']) ;
            $arr_month[$cur_month]=get_month_year($cur_month,'month year') ;
            switch($this->step)
            { case '1h': $t=mktime($ts['hours']+1,0,0,$ts['mon'],$ts['mday'],$ts['year']) ; $t2=$t-1; break  ;
              case '1d': $t=mktime(0,0,0,$ts['mon'],$ts['mday']+1,$ts['year']) ; $t2=$t-1; break  ;
              case '1m': $t=mktime(0,0,0,$ts['mon']+1,1,$ts['year']) ; $t2=$t-1; break  ; break ;
              default:   $t=$this->filter['time_to'] ;$t2=$t ;
            }

            //echo date('d.m.Y H:i:s',$t1).' - '.date('d.m.Y H:i:s',$t2).'<br>' ;

            //$res=execSQL_van('select ')   ;
            $_usl=array() ;
            if ($this->filter['org_id'])    $_usl[]='_org_id='.$this->filter['org_id'] ;
            if ($this->filter['org_ids'])   $_usl[]=' _org_id in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
            if ($this->filter['otdel_id'])  $_usl[]='_otdel_id in ('.$this->filter['otdel_id'].')' ;
            if ($this->filter['group_id'] and isset(ACCOUNTS()->tree[$this->filter['group_id']]))  $_usl[]='group_id in ('.ACCOUNTS()->tree[$this->filter['group_id']]->get_list_child().')' ;
            $dop_usl=(_sizeof($_usl))? ' and '.implode(' and ',$_usl):'' ;

            $result2[date('d.m.Y H:i:s',$t1)]['count_mo']=execSQL_value('select count(pkey) from view_mo_session where c_data>='.$t1.' and c_data<='.$t2.' and model>0 and dopusk in (1) and member_id>0 '.$dop_usl) ;
            $result2[date('d.m.Y H:i:s',$t1)]['score']=execSQL_row('select score,count(pkey)  as cnt from view_mo_session where c_data>='.$t1.' and c_data<='.$t2.' and model>0 and dopusk in (1) and member_id>0 and score>=0 '.$dop_usl.' group by score') ;


        }

////damp_array($result2,1,-1) ;

    if (_sizeof($result2)) foreach($result2 as $data=>$rec)
    {    //$a3=$rec['mo_stats'][5]+$rec['mo_stats'][7]+$rec['mo_stats'][9] ;
         //$a4=$rec['mo_stats'][6]+$rec['mo_stats'][8]+$rec['mo_stats'][10]  ;
         //$k1=($rec['count_mo'])? round(($a3+$a4)/$rec['count_mo']*100,2):0 ;
         //$result2[$data]['k1']=$k1 ;
         //$k2=($rec['count_mo'])? round($e/$rec['count_mo']*100,2):0 ;
         //$result2[$data]['k2']=$k2 ;
         $result2[$data]['time']=strtotime($data) ;
    }

    return($result2) ;
}


function report_graf($result)
   {   $caption='Показатели шкалы SCORE' ;
       switch($this->step)
         { case '1h': $yAxisName='Часы'; break  ;
           case '1d': $yAxisName='Дни' ;break  ;
           case '1m': $yAxisName='Месяцы' ; break ;
         }
       $t_now=time() ;
       $arr_month=array_keys($result) ;
       //damp_array($result,1,-1) ;
        ?><div id="chart-container">Подождите, идет построение графика</div>
         <script type="text/javascript">
          $j(document).ready(function(){
          FusionCharts.ready(function(){
         var revenueChart2 = new FusionCharts({
               type: 'mscombidy2d',
               renderAt: 'chart-container',
               width: '1000',
               height: '400',
               dataFormat: 'json',
               dataSource: {
                   "chart": {
                       //"caption": "<?echo $caption?>",
                       //"subCaption": "от <? echo date('d.m.Y',$this->filter['time_from']).' до '.date('d.m.Y',$this->filter['time_to'])?>",
                       "xAxisname": "<?echo $yAxisName?>",
                       "pYAxisName": "Кол-во допусков",
                       "sYAxisName": "Риск, Вероятность инфаркта",
                       "numberPrefix": "",
                       "sNumberSuffix" : "",
                       //"sYAxisMaxValue" : "50",
                       //"sYAxisMaxValue" : "9",

                       //Cosmetics
                       "paletteColors" : "#f2c500,#1aaf5d,#FF0000",
                       "baseFontColor" : "#333333",
                       "baseFont" : "Helvetica Neue,Arial",
                       "captionFontSize" : "14",
                       "subcaptionFontSize" : "14",
                       "subcaptionFontBold" : "0",
                       "showBorder" : "0",
                       "bgColor" : "#ffffff",
                       "showShadow" : "0",
                       "canvasBgColor" : "#ffffff",
                       "canvasBorderAlpha" : "0",
                       "divlineAlpha" : "100",
                       "divlineColor" : "#999999",
                       "divlineThickness" : "1",
                       "divLineIsDashed" : "1",
                       "divLineDashLen" : "1",
                       "divLineGapLen" : "1",
                       "usePlotGradientColor" : "0",
                       "showplotborder" : "0",
                       "showXAxisLine" : "1",
                       "xAxisLineThickness" : "1",
                       "xAxisLineColor" : "#999999",
                       "showAlternateHGridColor" : "0",
                       "showAlternateVGridColor" : "0",
                       "legendBgAlpha" : "0",
                       "legendBorderAlpha" : "0",
                       "legendShadow" : "0",
                       "legendItemFontSize" : "10",
                       "legendItemFontColor" : "#666666"
                   },
                   "categories":
                   [{
                       "category": [ <?foreach($arr_month as $t=>$date)
                       {  $time_s=strtotime($date) ;
                          switch($this->step)
                          { case '1h': $ee=date('H',$time_s) ; break  ;
                            case '1d': $ee=date('d.m.Y',$time_s) ;break  ;
                            case '1m': $ee=get_month_year($time_s,'month year'); break ;
                          }
                          echo '{ "label": "'.$ee.'" },' ;
                       }

                       ?>]
                   }],
                   "dataset":
                   [
                       {
                           "seriesName": "Количество допусков",
                           "color": "008ee4",
                           "data": [ <?foreach($result as $t=>$res)if ($res['time']<$t_now) echo '{ "value" : "'.$res['count_mo'].'" },'?>]
                       },
                       {
                           "seriesName": "10% и более",
                           "color": "e20000",
                           "data": [ <?foreach($result as $t=>$res) if ($res['time']<$t_now) echo '{ "value" : "'.($res['score'][10]+$res['score'][15]).'" },'?>]
                       },
                       {
                          "seriesName": "Риск",
                          "parentYAxis": "S",
                          "renderAs": "line",
                          "showValues": "1",
                          "divlineThickness" : "1",
                          "data": [ <?foreach($result as $t=>$res) if ($res['time']<$t_now)
                                    {  $k1=($res['count_mo'])? round(($res['score'][10]+$res['score'][15])/$res['count_mo']*100,2):0 ;
                                       echo '{ "value" : "'.$k1.'" },' ;
                                    }?>
                                  ]
                       },
                       {
                          "seriesName": "Вероятность инфаркта",
                          "parentYAxis": "S",
                          "renderAs": "line",
                          "showValues": "1",
                          "divlineThickness" : "1",
                          "data": [ <?foreach($result as $t=>$res) if ($res['time']<$t_now)
                                    {   $cnt_mo_risk=$res['score'][1]+$res['score'][2]+$res['score'][3]+$res['score'][5]+$res['score'][10]+$res['score'][15] ;
                                        $proc_risk=$res['score'][1]*1+$res['score'][2]*2+$res['score'][3]*3+$res['score'][5]*5+$res['score'][10]*10+$res['score'][15]*15 ;
                                        $k1=($res['count_mo'])? $proc_risk/$cnt_mo_risk:0 ;
                                       echo '{ "value" : "'.$k1.'" },' ;
                                    }?>
                                  ]
                       }
                   ]
               }
           });

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



   }

function report_table($result)
   {   ?><table class="basic fz_small" style="table-layout:fixed;">
               <tr><th rowspan="2">Дата</th>
                   <th rowspan="2"><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/cntmo.png'?>"><!--Кол-во МО--></th>
                   <th colspan="7">SCORE</th>
               </tr>
               <tr><th>менее 1%</th>
                   <th>1%</th>
                   <th>2%</th>
                   <th>3%-4%</th>
                   <th>5%-9%</th>
                   <th>10%-14%</th>
                   <th>более 15%</th>
               </tr>
           <? $itog=array() ;
              if (_sizeof($result)) foreach($result as $data=>$rec)
               {   $time_s=strtotime($data) ;
                   $ts=getdate($time_s) ;
                   //$time_e=mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ;  // исправлено
                   $a_href='' ; $row_title='' ;
                   switch($this->step)
                   { case '1h': $row_title=date('H:i:s',$time_s) ;
                                $time_e=mktime($ts['hours']+1,0,0,$ts['mon'],$ts['mday'],$ts['year'])-1 ;
                                $a_href='' ;
                                break  ;
                     case '1d': $row_title=date('d.m.Y',$time_s) ;
                                $time_e=mktime(0,0,0,$ts['mon'],$ts['mday']+1,$ts['year'])-1 ;
                                $a_href='' ;
                                break  ;
                     case '1m': $row_title=get_month_year($time_s,'month year');
                                $time_e=mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ;
                                $a_href=$this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e),array('url_report'=>'/cab/reports/itog6/')) ;
                                break ;

                   }

                   ?><tr>
                     <td><?echo ($a_href)? '<a href="'.$a_href.'" target=_BLANK>'.$row_title.'</a>':$row_title?></td>
                     <td><?echo $rec['count_mo'] ;  $itog['all']+=$rec['count_mo'] ; ?></td>
                     <td><? $a0=$rec['score'][0] ; if ($a0) echo $a0 ; $itog['a0']+=$a0 ; ?></td>
                     <td><? $a1=$rec['score'][1] ; if ($a1) echo $a1 ; $itog['a1']+=$a1 ; ?></td>
                     <td><? $a2=$rec['score'][2] ; if ($a2) echo $a2 ; $itog['a2']+=$a2 ; ?></td>
                     <td><? $a3=$rec['score'][3] ; if ($a3) echo $a3 ; $itog['a3']+=$a3 ; ?></td>
                     <td><? $a5=$rec['score'][5] ; if ($a5) echo $a5 ; $itog['a5']+=$a5 ; ?></td>
                     <td><? $a10=$rec['score'][10] ; if ($a10) echo $a10 ; $itog['a10']+=$a10 ; ?></td>
                     <td><? $a15=$rec['score'][15] ; if ($a15) echo $a15 ; $itog['a15']+=$a15 ; ?></td>
                    </tr>
                   <?
               }
               ?><tr class="itog">
                   <td class="left">ИТОГО</td>
                   <td><?echo $itog['all']?></td>
                   <td><?echo $itog['a0']?></td>
                   <td><?echo $itog['a1']?></td>
                   <td><?echo $itog['a2']?></td>
                   <td><?echo $itog['a3']?></td>
                   <td><?echo $itog['a5']?></td>
                   <td><?echo $itog['a10']?></td>
                   <td><?echo $itog['a15']?></td>
               </tr>
             </table>
       <br>
       <br>
             <style type="text/css">
                 div#reports_itog1{}
                 div#reports_itog1 table{width:100%;table-layout:fixed;border-collapse:collapse;}
                 div#reports_itog1 table colgroup col#c1{width:100px;}
                 div#reports_itog1 table colgroup col#c2{width:100px;}
                 div#reports_itog1 table colgroup col#c3{width:100px;}
                 div#reports_itog1 table colgroup col#c4{width:100px;}
                 div#reports_itog1 table colgroup col#c6{width:100px;}
                 div#reports_itog1 table colgroup col#c7{width:100px;}
                 div#reports_itog1 table colgroup col#c8{width:100px;}
                 div#reports_itog1 th{background:#dddddd;color:black;font-weight:bold;border:1px solid #aaaaaa;}
                 div#reports_itog1 td{padding:5px;border:1px solid #aaaaaa;text-align:center;}
                 div#reports_itog1 td.left{text-align:left;}
                 div#reports_itog1 tr.subitog1 td{font-weight:bold;background:#f1f1f1;text-align:center;}
                 div#reports_itog1 tr.subitog1 td.left{text-align:left;}
                 div#reports_itog1 tr.subitog2 td{font-weight:bold;background:#fafafa;text-align:center;}
                 div#reports_itog1 tr.subitog2 td.left{text-align:left;}
                 div#reports_itog1 tr.itog td{font-weight:bold;background:#dddddd;}
                 div#reports_itog1 table.debug td:first-child{width:250px;text-align:left;}
                 div#reports_itog1 table.debug td:last-child{width:70px;}
              </style>
     <?
   }

function print_template_CSV($list_recs,$options=array())
        { $i=$options['from'] ;
          if (_sizeof($list_recs)) foreach($list_recs as $d=>$rec)
            { $data=array() ;
              $data['Дата']=$d ;
              $data['Кол-во МО']=$rec['count_mo'] ;
              $data['Терминалы - МО пройден']=$rec['mo_stats'][1]+$rec['mo_stats'][3] ;
              $data['Терминалы - МО не пройден, уклонились от РМВ']=$rec['mo_stats'][2]+$rec['mo_stats'][4] ;

              $data['РМВ - Причины - Давление']=$rec['d'][0] ;
              $data['РМВ - Причины - Пульс']=$rec['p'][0] ;
              $data['РМВ - Причины - Температура']=$rec['t'][0] ;
              $data['РМВ - Причины - Алкоголь']=$rec['a'][0] ;
              $data['РМВ - Причины - Пупиллометрия']=$rec['n'][0] ;
              $data['РМВ - Причины - Жалобы']=$rec['q'][0] ;
              $data['РМВ - Причины - Не удалось провести измерение']=$e=$rec['error'][0] ;
              $data['РМВ - МО пройден']=$a3=$rec['mo_stats'][5]+$rec['mo_stats'][7]+$rec['mo_stats'][9] ;
              $data['РМВ - Допуск запрещен']=$a4=$rec['mo_stats'][6]+$rec['mo_stats'][8]+$rec['mo_stats'][10] ;
              $data['Среднее время МО']=round($rec['avg_time']) ;
              $data['КРТ']=number_format(round(($a3+$a4)/$rec['count_mo']*100,2),2,',','') ; ;
              $data['КОC']=number_format(round($e/$rec['count_mo']*100,2),2,',','')  ;


              $this->put_data_to_CSV($data,$i) ;
              $i++ ;
            }

        }

}

?>
