<?php
class report_reason extends c_report
{
 var $title='Отчет по ошибкам работы терминалов' ;
 var $filter=array() ;
 public $use_fusioncharts=1 ;
 //var $PDF_master='TCPDF' ;  // короткие отчеты выгружвать через обычный  PDF

 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'] ;
        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']) ;
           }


      //damp_array($this->filter) ;
       //$this->filter['data_from']=date('d.m.Y',));
     ?><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">
                             <?$arr_groups=execSQL_row('select pkey,obj_name,clss from obj_site_account where clss=206')?>
                             <section class="col col-2">
                                 <label class="label">Группа:</label>
                                 <label class="select">
                                     <select name="filter[group_id]"><option value="0">Все</option><?
                                       if (_sizeof($arr_groups)) foreach($arr_groups as $id=>$name) {?><option value="<?echo $id?>" <?if($this->filter['group_id']==$id) echo 'selected'?>><?echo $name?></option><?}?>
                                     </select>
                                 </label>
                             </section>
                             <section class="col col-2">
                                 <label class="label">С, месяц:</label>
                                 <label class="select">
                                     <select name="filter[time_from]"><option></option>
                                         <?foreach($arr_from as $t=>$month){?><option value="<?echo $t?>" <?if ($this->filter['time_from']==$t) echo 'selected'?>><?echo $month?></option><?}?>
                                     </select>
                                 </label>
                             </section>
                             <section class="col col-2">
                                 <label class="label">По, месяц</label>
                                 <label class="select">
                                     <select name="filter[time_to]"><option></option>
                                         <?foreach($arr_to as $t=>$month){?><option value="<?echo $t?>" <?if ($this->filter['time_to']==$t) echo 'selected' ?>><?echo $month?></option><?}?>
                                     </select>
                                 </label>
                             </section>
                         </div>
                     </fieldset>
                     <?$this->panel_buttons();?>
                 </form>
         </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']) ;;
            }

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

            $result=array() ;$result2=array() ; $all_reason=array() ; $all_reason2=array() ;
            $tf=getdate($this->filter['time_from']) ;
            $tt=getdate($this->filter['time_to']) ;
            $this->step=($tf['mon']==$tt['mon'])? '1d':'1m' ;

            $usl_group=($this->filter['group_id'] and isset(ACCOUNTS()->tree[$this->filter['group_id']]))?  ' and group_id in ('.ACCOUNTS()->tree[$this->filter['group_id']]->get_list_child().')':'' ;

            $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 '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 ;
                }

                $result2[date('d.m.Y',$t1)]['mo_cnt']=execSQL_value('select count(pkey) from obj_site_mo_session where status in (2,3) and c_data>='.$t1.' and c_data<='.$t2.$usl_group,0,1) ;
                $result2[date('d.m.Y',$t1)]['equipment']=execSQL_row('select equipment,count(pkey) from obj_site_mo_session where reason="equipmentFailure" and c_data>='.$t1.' and c_data<='.$t2.$usl_group.' group by equipment',0,1) ;
                $result2[date('d.m.Y',$t1)]['terminal_id']=execSQL_row('select terminal_id,count(pkey) from obj_site_mo_session where reason="equipmentFailure" and c_data>='.$t1.' and c_data<='.$t2.$usl_group.' group by terminal_id',0,1) ;

            }
        return($result2) ;
    }

function HTML_report_body($options=array())
{   $result=$this->prepare_result_data() ;
    //print_2x_arr($result) ;
    $all_terminals=execSQL_line('select distinct(terminal_id) from obj_site_mo_session where reason="equipmentFailure" and c_data>='.$this->filter['time_from'].' and c_data<='.$this->filter['time_to'].' order by terminal_id') ;
    $all_devices=execSQL_line('select distinct(equipment) from obj_site_mo_session where reason="equipmentFailure" and c_data>='.$this->filter['time_from'].' and c_data<='.$this->filter['time_to'].' order by equipment') ;

    ?><br><table class="basic fz_small" style="margin:0 auto;">
               <tr><th rowspan="2">Дата</th>
                   <th rowspan="2">Общее кол-во пройденных МО</th>
                   <th colspan="<?echo _sizeof($all_devices)?>">Число неисправностей по устройствам</th>
                   <th colspan="<?echo _sizeof($all_terminals)?>">Число неисправностей по терминалам</th>
               </tr>
               <tr>
                   <?if (_sizeof($all_devices)) foreach($all_devices as $name) echo '<th>'.$name.'</th>' ;?>
                   <?if (_sizeof($all_terminals)) foreach($all_terminals as $name) echo '<th>'.$name.'</th>' ;?>
               </tr>
           <? $itog=array() ;

              if (_sizeof($result)) foreach($result as $data=>$rec)
               {   $time_s=strtotime($data) ;
                   $ts=getdate($time_s) ;
                   $time_e=($this->step=='1d')? mktime(0,0,0,$ts['mon'],$ts['mday']+1,$ts['year'])-1:mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ;
                   $url_report_detail=($this->step=='1d')? '/cab/reports/report_mo_sess/':'/cab/reports/report_reason/' ;

                   ?><tr>
                     <td><?echo ($this->step=='1d')? $data:'<a href="'.$this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e),array('url_report'=>$url_report_detail)).'" target=_BLANK>'.get_month_year($time_s,'month year').'</a>'?></td>
                     <td><?echo $rec['mo_cnt'] ;            $itog['all']+=$rec['mo_cnt'] ; ?></td>
                   <?
                     if (_sizeof($all_devices)) foreach($all_devices as $name)
                     {   ?><td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'equipmentFailure'=>1,'equipment'=>$name),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><? echo $rec['equipment'][$name] ; ?></a></td><?
                         $itog['equipment'][$name]+=$rec['equipment'][$name] ;
                     }
                     if (_sizeof($all_terminals)) foreach($all_terminals as $name)
                     {   ?><td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'equipmentFailure'=>1,'terminal_id'=>$name),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><? echo $rec['terminal_id'][$name] ; ?></a></td><?
                         $itog['terminal_id'][$name]+=$rec['terminal_id'][$name] ;
                     }

                   /*
                   ?>

                     <td><?echo $a1=$rec['mo_stats'][1]+$rec['mo_stats'][3] ;  $itog['a1']+=$a1 ; ?></td>
                     <td><?echo $a2=$rec['mo_stats'][2]+$rec['mo_stats'][4] ;  $itog['a2']+=$a2 ;?></td>
                     <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'d'=>1,'model'=>'(0;1;3;5;6;7;8;9;10)'),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;1;3;5;6;7;8;9;10)'),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;1;3;5;6;7;8;9;10)'),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;1;3;5;6;7;8;9;10)'),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;1;3;5;6;7;8;9;10)'),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;1;3)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><?echo $q=$rec['q'][0] ;  $itog['q']+=$q ;?></a></td>
                     <td><a href="<?echo $this->get_filter_to_params(array('time_from'=>$time_s,'time_to'=>$time_e,'equipmentError'=>1,'cancelTimeout'=>1,'model'=>'(0;1;3)'),array('url_report'=>'/cab/reports/report_mo_sess/'))?>" target=_BLANK><? echo $e=$rec['error'][0] ?></a><? $itog['e']+=$e ;?></td>
                     <td><?echo $a3=$rec['mo_stats'][5]+$rec['mo_stats'][7]+$rec['mo_stats'][9]  ; $itog['a3']+=$a3 ;?></td>
                     <td><?echo $a4=$rec['mo_stats'][6]+$rec['mo_stats'][8]+$rec['mo_stats'][10]  ;$itog['a4']+=$a4 ;?></td>
                     <td><?echo round($rec['avg_time']) ;  $itog['avg_time']+=$rec['avg_time']  ;  ?></td>
                     <td><?echo $result[$data]['k1']=$k1=round(($a3+$a4)/$rec['count_mo']*100,2) ;  $itog['k1']+=$k1  ;  ?></td>
                     <td><?echo $result[$data]['k2']=$k2=round($e/$rec['count_mo']*100,2) ;  $itog['k2']+=$k2  ;  ?></td>
                    </tr>
                   <?      */
                   ?></tr><?
               }
               ?><tr class="itog">
                   <td class="left">ИТОГО</td>
                   <td><?echo $itog['all']?></td>
                   <? if (_sizeof($all_devices)) foreach($all_devices as $name)  echo '<td>'.$itog['equipment'][$name].'</td>' ;
                      if (_sizeof($all_terminals)) foreach($all_terminals as $name)  echo '<td>'.$itog['terminal_id'][$name].'</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 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>
     <?
       $caption='Показатели эффективности системы ЭСМО' ;
       $yAxisName='Месяцы' ;
       $arr_month=array_keys($result) ;
       //damp_array($result) ;
    ?>  <script type="text/javascript">
          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": "КРТ, КО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) ;
                          $ee=($this->step=='1d')? $date:get_month_year($time_s,'month year') ;
                          echo '{ "label": "'.$ee.'" },' ;
                       }

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

                   ]
               }
           });

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



   }



}

?>
