<?
class report_itog6 extends c_report
{  var $title='Показатели эффективности системы ЭСМО' ;
   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 $send_type_only_period = 1; //отправка отчета на email - только период
   var $time_interval=array(1=>'Cутки',2=>'Неделя',3=>'Месяц') ;
   var $step='1m' ;
    var $allow_export_to_csv=1 ;
    public $PDF_page_orientation='P' ; // L P
    var $use_csv_easy=1 ;


    function filter_section_select($element_name,$element_title,$col_count,$recs,$options=array())
    {  if (!_sizeof($recs)) return ;
        $cur_value=(isset($options['cur_value']))? $options['cur_value']:$this->filter[$element_name] ;
        ?><section class="col col-<?echo $col_count?>">
        <label class="label"><?echo $element_title?></label>
        <label class="select">
            <select class=filter name="filter[<?echo $element_name?>]" <?if ($options['select_params']) echo $options['select_params'];?>>
                <? if (!$options['nospace_element']){?><option value="0"></option><?}
                if (_sizeof($recs)) foreach($recs as $id=>$value)
                {   $key=(is_array($value) and $options['key_fname'])?  $value[$options['key_fname']]:$id ;
                    $val=(is_array($value))?  $value['obj_name']:$value ;
                    if ($options['use_id_plus_1']) $key++ ;
                    ?><option value="<?echo $key?>" <?if($cur_value==$key) echo 'selected'?>><?echo $val?></option><?
                }
                ?>
            </select><i></i>
        </section>
        <?
    }

    function get_week_period($data_info) {
        $result=[];
        $ts=getdate($data_info['min_data']) ; $wday_shift=0;
        if ($ts['wday']) $wday_shift=$ts['wday']-1; else $wday_shift=6;
        $cur_week_start=mktime(0,0,0,$ts['mon'],$ts['mday']-$wday_shift,$ts['year']) ;
        $cur_week_end=$cur_week_start+60*60*24*7-1;
        $result[$cur_week_start]=date('d.m.Y',$cur_week_start).' - '.date('d.m.Y',$cur_week_end);
        $t1=$cur_week_start+60*60*24*7;
        while ($t1<$data_info['max_data']) {
            $t2=$t1+60*60*24*7-1;
            $result[$t1]=date('d.m.Y',$t1).' - '.date('d.m.Y',$t2);
            $t1+=60*60*24*7;
        }
        krsort($result);
        return $result;
    }

   function setting()
   { $data_info=execSQL_van('select min(c_data) as min_data,max(c_data) as max_data from obj_site_mo_session') ;
     $arr_from=array() ; $arr_to=array() ;
     if ($data_info['max_data']>$data_info['min_data']) {
         //список по месяцам
         $t=$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']) ;
         }
         krsort($arr_from);
         krsort($arr_to);
         //список по неделям
         $week_arr=$this->get_week_period($data_info);
         //список по дням
     }

     if (!$this->filter['time_interval']) {
         $this->filter['time_interval']=1;
     }

       $day_section_class='2 day_section';
       $week_section_class='2 week_section';
       $month_section_class='2 month_section';

     switch ($this->filter['time_interval']) {
        case 1:
            $week_section_class.=' hidden_element';
            $month_section_class.=' hidden_element';
            break;
        case 2:
            $day_section_class.=' hidden_element';
            $month_section_class.=' hidden_element';
            break;
        case 3:
            $day_section_class.=' hidden_element';
            $week_section_class.=' hidden_element';
            break;
     }

     $arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;
     $arr_orgs_ids=PERSONAL()->get_arr_orgs_to_cur_account() ;
     $arr_otdel_ids=(_sizeof($this->filter['org_ids']))? PERSONAL()->get_arr_otdels_to_cur_account($this->filter['org_ids']):array() ;
     $arr_works_ids=PERSONAL()->get_arr_working_by_usl($arr_orgs_ids,$arr_otdel_ids) ;

     ?><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_multiple('working_ids','Должность:',2,$arr_works_ids) ;
                          $this->filter_section_select('time_interval','Временной интервал:',2,$this->time_interval,array('nospace_element'=>1,'select_params'=>'id="selectInterval" onchange="onTimeIntervalChange()"')) ;
                          $this->filter_section_select('month_from','С, месяц:',$month_section_class,$arr_from) ;
                          $this->filter_section_select('month_to','По, месяц:',$month_section_class,$arr_to) ;
                          $this->filter_section_input_text('day_time','День:',$day_section_class,array('class'=>'datepicker','autocomplete'=>'off')) ;
                          $this->filter_section_select('week_time','Неделя:',$week_section_class,$week_arr) ;
                       ?>
                   </div>
               </fieldset>
               <?$this->panel_buttons();?>
           </form>
        </div>
       <style type="text/css">
           section.hidden_element {display:none;}
       </style>
       <script type="text/javascript">
            function onTimeIntervalChange() {
                let curValue=$j('#selectInterval')[0].value;
                console.log(curValue);
                switch (curValue) {
                    case '1':
                        console.log('day');
                        // console.log($j('section.day_section'));
                        $j('section.day_section').removeClass('hidden_element');
                        $j('section.week_section').removeClass('hidden_element').addClass('hidden_element');
                        $j('section.month_section').removeClass('hidden_element').addClass('hidden_element');
                        break;
                    case '2':
                        console.log('week');
                        $j('section.day_section').removeClass('hidden_element').addClass('hidden_element');
                        $j('section.week_section').removeClass('hidden_element');
                        $j('section.month_section').removeClass('hidden_element').addClass('hidden_element');
                        break;
                    case '3':
                        console.log('month');
                        $j('section.day_section').removeClass('hidden_element').addClass('hidden_element');
                        $j('section.week_section').removeClass('hidden_element').addClass('hidden_element');
                        $j('section.month_section').removeClass('hidden_element');
                        break;
                }
            }
       </script>
     <?
   }

    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_interval'])                        $info['временной интервал']=$this->time_interval[$this->filter['time_interval']] ;
    return $info ;
 }

function HTML_report_body($options=array())
{   $recs=$this->prepare_result_data() ;
    //damp_array($recs,1,-1) ;
    ?><div id="reports_itog1"><?
       if ($this->view_graf) $this->report_graf($recs) ;
       if ($this->view_table) $this->report_table($recs) ;
    ?></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') ;

    $time_from=0;
    $time_to=0;

    $ts=getdate() ;

    switch ($this->filter['time_interval']) {
        case 1:
            if ($this->filter['day_time']) {
                $time_from=strtotime($this->filter['day_time']);
                $time_to=$time_from+60*60*24-1;
            } else {
                $time_from=mktime(0,0,0,$ts['mon'],$ts['mday'],$ts['year']) ;
                $time_to=$time_from+60*60*24-1;
            }
            $this->step='1h' ;
            break;
        case 2:
            if ($this->filter['week_time']) {
                $time_from=$this->filter['week_time'];
                $time_to=$time_from+60*60*24*7-1;
            } else {
                $week_day=($ts['wday'])? $ts['wday']-1:6 ; // для коррекции что ВСК = 0, а ПНД = 1
                $time_from=mktime(0,0,0,$ts['mon'],$ts['mday']-$week_day,$ts['year']) ;
                $time_to=$time_from+60*60*24*7-1;
            }
            $this->step='1d' ;
            break;
        case 3:
            if ($this->filter['month_from'] and $this->filter['month_to']) {
                $time_from=$this->filter['month_from'];
                $time_to=$this->filter['month_to'];
                $tmf=getdate($time_from);
                $tmt=getdate($time_to);
                if (($tmf['mon']==$tmt['mon']) and ($tmf['year']==$tmt['year'])) {
                    $this->step='1d' ;
                } else {
                    $this->step='1m' ;
                }
            } else {
                if ($this->filter['month_from'] and !$this->filter['month_to']) {
                    $time_from=$this->filter['month_from'];
                    $tm=getdate($time_from);
                    $time_to=mktime(0,0,0,$tm['mon']+1,1,$tm['year'])-1 ;
                } elseif (!$this->filter['month_from'] and $this->filter['month_to']) {
                    $tm=getdate($data_info['min_data']);
                    $time_from=mktime(0,0,0,$tm['mon'],1,$tm['year']);
                    $time_to=$this->filter['month_to'];
                } else {
                    $time_from=mktime(0,0,0,$ts['mon'],1,$ts['year']);
                    $time_to=mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ;
                }
                // выбран один месяц
                $this->step='1d' ;
            }

            break;
    }
    if (isset($this->filter['data_from']) and isset($this->filter['data_to'])) {
        $time_from = strtotime($this->filter['data_from']);
        $time_to = strtotime($this->filter['data_to']);
    }

    //$recs=ESMO()->get_mo_recs($options) ;
    //print_2x_arr($recs) ;
    $result=array() ;$result2=array() ; $all_reason=array() ; $all_reason2=array() ;
    $tf=getdate($time_from) ;
    $tt=getdate($time_to) ;

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

    $t=$time_from ;
    while($t<=$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=$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_ids'])  $_usl[]='_otdel_id in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;
        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().')' ;
        if ($this->filter['working_ids'])   $_usl[]=' working in ('.implode(',',array_keys($this->filter['working_ids'])).')' ;
        $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,2) and member_id>0 '.$dop_usl) ;
        $result2[date('d.m.Y H:i:s',$t1)]['mo_stats']=execSQL_row('select model,count(pkey)  as cnt from view_mo_session where c_data>='.$t1.' and c_data<='.$t2.' and member_id>0 and dopusk in (1,2,3) '.$dop_usl.' group by model') ;
        $result2[date('d.m.Y H:i:s',$t1)]['d']=execSQL_row('select model,count(pkey) as cnt from view_mo_session where c_data>='.$t1.' and c_data<='.$t2.' and (res_s in (2,3) or res_d in (2,3)) '.$dop_usl.' group by model') ;
        $result2[date('d.m.Y H:i:s',$t1)]['p']=execSQL_row('select model,count(pkey) as cnt from view_mo_session where c_data>='.$t1.' and c_data<='.$t2.' and res_p in (2,3) '.$dop_usl.' group by model') ;
        $result2[date('d.m.Y H:i:s',$t1)]['t']=execSQL_row('select model,count(pkey) as cnt from view_mo_session where c_data>='.$t1.' and c_data<='.$t2.' and res_t in (2,3)   '.$dop_usl.' group by model') ;
        $result2[date('d.m.Y H:i:s',$t1)]['a']=execSQL_row('select model,count(pkey) as cnt from view_mo_session where c_data>='.$t1.' and c_data<='.$t2.' and res_a in (2,3)   '.$dop_usl.' group by model') ;
        $result2[date('d.m.Y H:i:s',$t1)]['n']=execSQL_row('select model,count(pkey) as cnt from view_mo_session where c_data>='.$t1.' and c_data<='.$t2.' and res_n in (2,3)  '.$dop_usl.' group by model') ;
        $result2[date('d.m.Y H:i:s',$t1)]['q']=execSQL_row('select model,count(pkey) as cnt from view_mo_session where c_data>='.$t1.' and c_data<='.$t2.' and question=1   '.$dop_usl.' group by model') ;
        $result2[date('d.m.Y H:i:s',$t1)]['error']=execSQL_row('select model,count(pkey) from view_mo_session where c_data>='.$t1.' and c_data<='.$t2.' and (reason="equipmentError" or reason="cancelTimeout") and model in (0,1,3) '.$dop_usl.' group by model') ;
        $result2[date('d.m.Y H:i:s',$t1)]['avg_time']=execSQL_value('select AVG(e_data-c_data) from view_mo_session where c_data>='.$t1.' and c_data<='.$t2.' and model in (0,1,2,3,4) and error=0 and message_terminal="success" and reason!="cancelTimeout" and e_data>0  '.$dop_usl.' ') ;

    }

    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]  ;
         $e=$rec['error'][0] ;
         $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='Показатели эффективности системы ЭСМО' ;
       switch($this->step)
         { case '1h': $yAxisName='Часы'; break  ;
           case '1d': $yAxisName='Дни' ;break  ;
           case '1m': $yAxisName='Месяцы' ; break ;
         }
       $t_now=time() ;
       $arr_month=array_keys($result) ;
        ?><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',$time_from).' до '.date('d.m.Y',$time_to)?>",
                       "xAxisname": "<?echo $yAxisName?>",
                       "pYAxisName": "Кол-во МО",
                       "sYAxisName": "КРТ, КОC",
                       "numberPrefix": "",
                       "sNumberSuffix" : "",
                       //"sYAxisMaxValue" : "50",
                       "sYAxisMaxValue" : "15",

                       //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": "Количество МО",
                           "data": [ <?foreach($result as $t=>$res)if ($res['time']<$t_now) echo '{ "value" : "'.$res['count_mo'].'" },'?>]
                       },
                       {
                           "seriesName": "КРТ",
                           "parentYAxis": "S",
                           "renderAs": "line",
                           "showValues": "1",
                           "divlineThickness" : "1",
                           "data": [ <?foreach($result as $t=>$res) if ($res['time']<$t_now) echo '{ "value" : "'.$res['k1'].'" },'?>]
                       },
                       {
                           "seriesName": "КОС",
                           "parentYAxis": "S",
                           "renderAs": "line",
                           "showValues": "1",
                           "divlineThickness" : "1",
                           "data": [ <?foreach($result as $t=>$res) if ($res['time']<$t_now) echo '{ "value" : "'.$res['k2'].'" },'?>]
                       }

                   ]
               }
           });

           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;">
               <colgroup>
                   <col id="c1">
                   <col id="c2">
                   <col id="c3">
                   <col id="c4">
                   <col id="c5">
                   <col id="c6">
                   <col id="c7">
                   <col id="c8">
               </colgroup>
               <tr><th rowspan="3">Дата <?echo $this->step?></th>
                   <th rowspan="3"><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/cntmo.png'?>"><!--Кол-во МО--></th>
                   <th colspan="2">Терминалы <?echo $this->filter['time_interval'];?></th>
                   <th colspan="9">РМВ</th>
                   <th rowspan="3"><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/dlit.png'?>"><!--Среднее время МО<br>сек--></th>
                   <th rowspan="3">КРТ</th>
                   <th rowspan="3">КОC</th>
               </tr>
               <tr><th rowspan="2"><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/mo_success.png'?>"><!--МО пройден--></th>
                   <th rowspan="2"><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/ukl.png'?>"><!--МО не пройден, уклонились от РМВ--></th>
                   <th colspan="7">Причины направления на РМВ</th>
                   <th rowspan="2"><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/mo_success.png'?>"><!--МО пройден--></th>
                   <th rowspan="2"><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/mo_failed.png'?>"><!--Допуск запрещен--></th>
               </tr>
               <tr><th><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/sd.png'?>"><!--Давление--></th>
                   <th><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/p.png'?>"><!--Пульс--></th>
                   <th><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/t.png'?>"><!--Температура--></th>
                   <th><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/a.png'?>"><!--Алкоголь--></th>
                   <th><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/pp.png'?>"><!--Пупиллометрия--></th>
                   <th><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/question.png'?>"><!--Жалобы--></th>
                   <th><img src="<?echo _PATH_TO_SITE._PATH_TO_EXT.'/aspmo_reports/images/no_result.png'?>"><!--Не удалось провести измерение--></th>
               </tr>
           <? $itog=array() ;
              if (_sizeof($result)) foreach($result as $data=>$rec)
               {   $time_s=strtotime($data) ;
                   if (!$itog['global_time_s'])  $itog['global_time_s']=$time_s;
                   $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('month_from'=>$time_s,'month_to'=>$time_e,'time_interval'=>3),array('url_report'=>'/cab/reports/report_itog6/')) ;
                                break ;
                   }

                   $itog['global_time_e']=$time_e;

                   ?><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><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'model'=>'(1;3)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><? $a1=$rec['mo_stats'][1]+$rec['mo_stats'][3] ; if ($a1) echo $a1 ; $itog['a1']+=$a1 ; ?></a></td>
                     <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'model'=>'(2;4)','dopusk'=>'(1;2;3)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><? $a2=$rec['mo_stats'][2]+$rec['mo_stats'][4] ; if ($a2) echo $a2 ; $itog['a2']+=$a2 ;?></a></td>
                     <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'d'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?echo $d=$rec['d'][0] ;  $itog['d']+=$d ;?></a></td>
                     <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'p'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?echo $p=$rec['p'][0] ;  $itog['p']+=$p ;?></a></td>
                     <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'t'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?echo $t=$rec['t'][0] ;  $itog['t']+=$t ;?></a></td>
                     <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'a'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?echo $a=$rec['a'][0] ;  $itog['a']+=$a ;?></a></td>
                     <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'n'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?echo $n=$rec['n'][0] ;  $itog['n']+=$n ;?></a></td>
                     <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'q'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?$q=$rec['q'][0] ; if ($q) echo $q ; $itog['q']+=$q ;?></a></td>
                     <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'equipmentErrorOrCancelTimeout'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><? $e=$rec['error'][0] ; if ($e) echo $e ; ?></a><? $itog['e']+=$e ;?></td>
                     <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'model'=>'(5;7;9)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><? $a3=$rec['mo_stats'][5]+$rec['mo_stats'][7]+$rec['mo_stats'][9]  ; if ($a3) echo $a3 ; $itog['a3']+=$a3 ;?></a></td>
                     <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'model'=>'(6;8;10)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><? $a4=$rec['mo_stats'][6]+$rec['mo_stats'][8]+$rec['mo_stats'][10]  ; if ($a4) echo $a4 ;$itog['a4']+=$a4 ;?></a></td>
                     <td><? $t=round($rec['avg_time']) ;  if ($t) {echo $t ; $itog['avg_time_cnt']++;} $itog['avg_time']+=$rec['avg_time']  ;  ?></td>
                     <td><?$k1=($rec['count_mo'])? round(($a3+$a4)/$rec['count_mo']*100,2):0 ;
                         $result[$data]['k1']=$k1 ; if ($k1) echo $k1 ;  $itog['k1']+=$k1  ;  ?></td>
                     <td><?$k2=($rec['count_mo'])? round($e/$rec['count_mo']*100,2):0 ;
                          $result[$data]['k2']=$k2 ; if ($k2) echo $k2 ;  $itog['k2']+=$k2  ;  ?></td>
                    </tr>
                   <?
               }
               ?><tr class="itog">
                   <td class="left">ИТОГО</td>
                   <td class="all_mo_count"><?echo $itog['all']?></td>
                   <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$itog['global_time_s'],'time_to'=>$itog['global_time_e'],'model'=>'(1;3)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?if ($itog['a1']) echo $itog['a1']?></a></td>
                   <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$itog['global_time_s'],'time_to'=>$itog['global_time_e'],'model'=>'(2;4)','dopusk'=>'(1;2;3)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?if ($itog['a2']) echo $itog['a2']?></a></td>
                   <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$itog['global_time_s'],'time_to'=>$itog['global_time_e'],'d'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?if ($itog['d']) echo $itog['d']?></a></td>
                   <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$itog['global_time_s'],'time_to'=>$itog['global_time_e'],'p'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?if ($itog['p']) echo $itog['p']?></a></td>
                   <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$itog['global_time_s'],'time_to'=>$itog['global_time_e'],'t'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?if ($itog['t']) echo $itog['t']?></a></td>
                   <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$itog['global_time_s'],'time_to'=>$itog['global_time_e'],'a'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?if ($itog['a']) echo $itog['a']?></a></td>
                   <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$itog['global_time_s'],'time_to'=>$itog['global_time_e'],'n'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?if ($itog['n']) echo $itog['n']?></a></td>
                   <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$itog['global_time_s'],'time_to'=>$itog['global_time_e'],'q'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?if ($itog['q']) echo $itog['q']?></a></td>
                   <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$itog['global_time_s'],'time_to'=>$itog['global_time_e'],'equipmentErrorOrCancelTimeout'=>1,'model'=>'(0)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?if ($itog['e']) echo $itog['e']?></a></td>
                   <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$itog['global_time_s'],'time_to'=>$itog['global_time_e'],'model'=>'(5;7;9)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?if ($itog['a3']) echo $itog['a3']?></a></td>
                   <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$itog['global_time_s'],'time_to'=>$itog['global_time_e'],'model'=>'(6;8;10)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?if ($itog['a4']) echo $itog['a4']?></a></td>
                   <td><?if ($itog['avg_time_cnt']) echo round($itog['avg_time']/$itog['avg_time_cnt'])?></td>
                   <td><?echo (_sizeof($result))? round($itog['k1']/_sizeof($result),2):'-'?></td>
                   <td><?echo (_sizeof($result))? round($itog['k2']/_sizeof($result),2):'-'?></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 CSV_report_body($options=array())
{      $recs=$this->prepare_result_data() ;
         $i=0 ;
          if (_sizeof($recs)) foreach($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++ ;
            }

        }

}

?>
