<?php
/*добавить в вывод параматеров фильтра процент и число МО*/
class report_itog3 extends c_report
{
 var $title='Отчет по группам риска пофамильный' ;
 var $filter=array() ;
 //var $PDF_master='TCPDF' ;  // короткие отчеты выгружвать через обычный  PDF
 var $rules_ag=array(
     //'opt'>=array('s_min'=>0,  's_max'=>120,'title'=>'Оптимальное АД<br>ниже 120'),
     //'norm'=>array('s_min'=>120,'s_max'=>130,'title'=>'Нормальное АД<br>120-129'),
     //'v_norm'=>array('s_min'=>130,'s_max'=>140,'title'=>'Высокое нормальное АД<br>130–139'),
     'ag1'=>array('s_min'=>140,'s_max'=>160,'title'=>'АГ I степени тяжести<br>140–159'),
     'ag2'=>array('s_min'=>160,'s_max'=>179,'title'=>'АГ II степени тяжести<br>160–179'),
     'ag3'=>array('s_min'=>180,'s_max'=>10000,'title'=>'АГ III степени тяжести<br>180 и выше')
 ) ;

  var $allow_export_to_csv=1 ;
 function setting()
   {
     $now=getdate() ;
     if (!$this->filter['data_from']) $this->filter['data_from']=date('d.m.Y',mktime(0,0,0,$now['mon'],1,$now['year']));
     if (!$this->filter['data_to'])   $this->filter['data_to']=date('d.m.Y',mktime(0,0,0,$now['mon']+1,1,$now['year'])-1);

     $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_multiple('working','Должность:',2,$arr_works_ids) ;
                                $this->filter_section_select('tk','Тип контроля:',2,$_SESSION['ARR_mo_tk_type'],array('use_id_plus_1'=>1)) ;
                                $this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
                                $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;
                             ?></div><div class="row"><?
                                $this->filter_section_input_text('min_mo','Минимальное число МО:',2) ;
                                $this->filter_section_input_text('min_proc','Пороговый процент:',2) ;
                                $this->filter_section_select_multiple('group_medic','Группа по болезни:',2,_IL('IL_group_medic')->recs) ;
                             ?>
                         </div>
                         <div class="row">
                              <section class="col col-2">
                                 <label class="label">Группа АГ:</label>
                                 <label class="select">
                                     <select name="filter[ag]"><option value="0">Все</option>
                                       <option value="1" <?if($this->filter['ag']==1) echo 'selected'?>>АГ1</option>
                                     <option value="2" <?if($this->filter['ag']==2) echo 'selected'?>>АГ2</option>
                                     <option value="3" <?if($this->filter['ag']==3) echo 'selected'?>>АГ3</option>
                                     </select>
                                 </label>
                             </section>
                         </div>
                     </fieldset>
                     <?$this->panel_buttons();?>
                 </form>
         </div>
     <?
   }

 function get_arr_info_filters()
 { $info=parent::get_arr_info_filters() ;
   if ($this->filter['min_mo'])  $info['Минимальное число МО']=$this->filter['min_mo'] ;
   if ($this->filter['min_proc'])  $info['Пороговый процент']=$this->filter['min_proc'] ;
   return $info ;
 }

function full_data_to_org($arr,&$recs,$level=0,$sel_pkey=0)
{  $str='' ;  $level++ ;
 if (_sizeof($arr)) foreach ($arr as $id=>$arr_child)
 {   if (isset($this->arr_parents[$id]))
     { echo $recs[$id]['obj_name'].'<br>' ;  //else echo '$id='.$id.' '.$recs[$id]['obj_name'].' - не используется<br>' ;
     }
     if (_sizeof($arr_child)) $str.=$this->full_data_to_org($arr_child,$recs,$level,$sel_pkey) ;
 }
 return($str) ;
}

function create_usl_select_obj($_params,&$options)
{ //damp_array($this->filter) ;
  $_usl=array() ;
  $_usl[]='model>0' ;
  $_usl[]='dopusk in (1,2,3)' ;
  //$_usl[]='terminal_id>0' ;
  if ($this->filter['data_from']) $_usl[]='c_data>='.strtotime($this->filter['data_from']) ;
  if ($this->filter['data_to'])   $_usl[]='c_data<='.strtotime($this->filter['data_to']) ;
  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['tk']==1)         $_usl[]='tk=0' ;
  if ($this->filter['tk']==2)         $_usl[]='tk=1' ;
  if ($this->filter['tk']==3)         $_usl[]='tk=2' ;
  if ($this->filter['dep_id'])
  { $cur_level=execSQL_value('select level from obj_site_personals where pkey='.$this->filter['dep_id']) ;
    $_usl[]='personal_parent'.$cur_level.'='.$this->filter['dep_id'] ;
  }
  if ($this->filter['org_ids'])       $_usl[]='personal_parent2 in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
  if ($this->filter['otdel_ids'])     $_usl[]='personal_parent3 in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;


  $usl_res=implode(' and ',$_usl) ;

  if (!$this->filter['min_mo']) $this->filter['min_mo']=0 ;
  if (!$this->filter['min_proc']) $this->filter['min_proc']=0 ;

  return($usl_res) ;
}

 function get_cnt_items($usl,$options=array())
 { $options['debug']=0 ;
   $usl_rule=' and systolic>='.$this->rules_ag['ag1']['s_min'].' and systolic<'.$this->rules_ag['ag3']['s_max'].' ' ;
   $this->cnt_items=execSQL_value('select count(t_res.personal_id) from
                        (select personal_id,
                        count(pkey) as cnt_a,
                        (select count(pkey) from obj_site_mo_session t1 where '.$usl.' and t1.member_id=personal_id) as cnt_all 
                        from view_mo_session where '.$usl.$usl_rule.' 
                        group by personal_id
                        having cnt_all>='.$this->filter['min_mo'].' and (cnt_a/cnt_all*100)>='.$this->filter['min_proc'].') as t_res
                        ',$options) ;
   return($this->cnt_items) ;
 }

 function get_items($usl,$options=array())
 { $limit=($options['limit'])? ' '.$options['limit']:'' ;
   //$options['debug']=1 ;
   $usl_rule_all=' and systolic>='.$this->rules_ag['ag1']['s_min'].' and systolic<'.$this->rules_ag['ag3']['s_max'].' ' ;
   if (_sizeof($this->rules_ag))
   { $_str=array() ;
     foreach($this->rules_ag as $id=>$rec_rules) $_str[]='(select count(pkey) from obj_site_mo_session t1 where '.$usl.' and systolic>='.$rec_rules['s_min'].' and systolic<'.$rec_rules['s_max'].' and t1.member_id=personal_id) as cnt_'.$id ;
     $usl_rules=implode(', ',$_str).',' ;
   } else $usl_rules='' ;

if ($this->filter['ag']) $ag_usl=' and cnt_ag'.$this->filter['ag'].'>0' ; else $ag_usl='' ;

$recs=execSQL('select personal_id,personal_name,
               count(pkey) as cnt_a,'.$usl_rules.'(select count(pkey) from obj_site_mo_session t1 where '.$usl.' and t1.member_id=personal_id) as cnt_all,
               personal_parent,
               personal_parent1,personal_parent2,personal_parent3
               from view_mo_session22 where '.$usl.$usl_rule_all.' 
               group by personal_id
               having cnt_all>='.$this->filter['min_mo'].' and (cnt_a/cnt_all*100)>='.$this->filter['min_proc'].$ag_usl.'
               order by personal_name,personal_parent1,personal_parent2,personal_parent3,personal_parent4,personal_parent5,personal_parent6,personal_parent7,personal_parent8,personal_parent9
               '.$limit,$options) ;
   return($recs) ;
 }

 function get_items_to_event($usl,$options=array())
 { $options['debug']=1 ;
   // в этом массиве будут все работающие сотрудники, прошедшие минимальное число МО
   $arr_ids_all=execSQL_row('select member_id,count(pkey) as cnt_all 
                             from view_mo_session t1 where personal_enabled=1 and '.$usl.'
                             group by member_id
                             having cnt_all>='.$this->filter['min_mo']) ;

   $arr_ids_gr_all=array() ;
   if (_sizeof($this->rules_ag)) foreach($this->rules_ag as $id=>$rec_rules)
   { $arr_ids[$id]=execSQL_row('select member_id,count(pkey) from obj_site_mo_session t1 where '.$usl.' and systolic>='.$rec_rules['s_min'].' and systolic<'.$rec_rules['s_max'].' group by member_id') ;
     //  в $arr_ids_gr_all собираем данные по персоналу по всем группам риска
     if (_sizeof($arr_ids[$id])) foreach($arr_ids[$id] as $personal_id=>$cnt)
     {   if (isset($arr_ids_all[$personal_id])) $arr_ids_gr_all[$personal_id]+=$cnt ;
         else unset($arr_ids[$id][$personal_id]) ; //надо удалить из  $arr_ids сотрудников, у которых нет достаточного числа МО
     }
   }

   foreach($arr_ids_all as $personal_id=>$cnt_all)
   {  $cnt_gr_all=$arr_ids_gr_all[$personal_id] ;
      $proc=$cnt_gr_all/$cnt_all*100 ;
      if ($this->filter['max_proc'] and $proc>$this->filter['max_proc']) unset($arr_ids_all[$personal_id],$arr_ids_gr_all[$personal_id],$arr_ids['ag1'][$personal_id],$arr_ids['ag2'][$personal_id],$arr_ids['ag3'][$personal_id]) ;
      if ($this->filter['min_proc'] and $proc<=$this->filter['min_proc']) unset($arr_ids_all[$personal_id],$arr_ids_gr_all[$personal_id],$arr_ids['ag1'][$personal_id],$arr_ids['ag2'][$personal_id],$arr_ids['ag3'][$personal_id]) ;
   }

   // теперь из массива
   //foreach($arr_ids as $id=>$arr) echo 'level_'.$id.'='._sizeof($arr).'<br>' ;
   //echo 'level_all='._sizeof($arr_ids_gr_all).'<br>' ;

   return($arr_ids_gr_all) ;
 }

// шаблон - вывод ссылками без разделитея
function print_template_HTML($list_recs,$options=array())
{  ?><table class="basic fz_small full auto" >
    <tr><th>№</th>
       <th>Организация</th>
       <th>ФИО</th>
       <th>Кол-во МО</th>
       <th>% AГ от <br>общего числа<br>проверок</th>
       <?foreach($this->rules_ag as $id=>$rec_rules){?><th><?echo $rec_rules['title']?></th><?}?>
    </tr>
    <? $i=(_CUR_PAGE_NUMBER-1)*50+1 ;
    if (_sizeof($list_recs)) foreach($list_recs as $rec)
    { ?><tr><td><?echo $i?></td>
           <td class="left"><?echo PERSONAL()->get_full_dep_name_by_dep_levels($rec,'personal_') ?></td>
           <td class="left"><?echo $rec['personal_name'] ?> <?echo $rec['personal_id']?></td>
           <td><?echo $rec['cnt_all']?></td>
           <td><?echo round($rec['cnt_a']/$rec['cnt_all']*100)?> %</td>
           <?foreach($this->rules_ag as $id=>$rec_rules){?><td><?if ($rec['cnt_'.$id]) echo $rec['cnt_'.$id]?></td><?}?>
        </tr>
       <?
       $i++ ;
       $personal_id=$rec['personal_id'] ;
       if (isset($_SESSION['personal_check_report_1'][$personal_id]))  unset($_SESSION['personal_check_report_1'][$personal_id]) ;
       else      $_SESSION['personal_check_report_2'][$personal_id]=array('cnt_mo'=>$rec['cnt_all'],'ag_cnt'=>$rec['cnt_a']) ;

    }
  ?></table><?
    /*ksort($_SESSION['personal_check_report_1']) ;
    ksort($_SESSION['personal_check_report_2']) ;

    echo 'Сотрудники из отчета 1, которых нет в отчете 2 - '._sizeof($_SESSION['personal_check_report_1']) .'<br>' ;
    print_2x_arr($_SESSION['personal_check_report_1']) ;
    echo 'Сотрудники из отчета 2, которых нет в отчете 1 - '._sizeof($_SESSION['personal_check_report_2']) .'<br>' ;
    print_2x_arr($_SESSION['personal_check_report_2']) ;*/
}


function print_template_CSV($list_recs,$options=array())
{ $i=$options['from'] ;
  if (_sizeof($list_recs)) foreach($list_recs as $rec)
    { $data=array() ;
      $data['№']=$i+1 ;
      $data['Организация']=PERSONAL()->get_full_dep_name_by_dep_levels($rec,'personal_')  ;
      $data['ФИО']=$rec['personal_name'] ;
      $data['Кол-во МО']=$rec['cnt_all'] ;
      $data['% AГ от общего числа проверок']=round($rec['cnt_a']/$rec['cnt_all']*100) ;
      foreach($this->rules_ag as $id=>$rec_rules) $data[strip_tags($rec_rules['title'])]=($rec['cnt_'.$id])? $rec['cnt_'.$id]:'' ;
      // вносим данные в csv
      $this->put_data_to_CSV($data,$i) ;
      $i++ ;
    }

}



}

?>
