<?php
include_once(_DIR_EXT.'/aspmo_pp/i_source.php') ;
/*добавить в вывод параматеров фильтра процент и число МО*/
class report_pp_itog4 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);
     ?><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">
                             <section class="col col-4">
                                 <label class="label">Подразделениe:</label>
                                 <label class="select">
                                      <select name="filter[dep_id]"><option value="0">Все</option>
                                        <? echo PERSONAL()->get_select_option(1,$this->filter['dep_id']) ;?>
                                      </select>
                                 </label>
                             </section>
                             <?$arr_groups=execSQL_row('select pkey,obj_name,clss from obj_site_account where clss=206')?>
                             <section class="col col-3">
                                 <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-3">
                                 <label class="label">Результат:</label>
                                 <label class="select">
                                     <select name="filter[pp_result]"><option value="0">Все</option><?
                                         if (_sizeof($GLOBALS['pp_result'])) foreach($GLOBALS['pp_result'] as $id=>$name) {?><option value="<?echo $id+1?>" <?if($this->filter['pp_result']==($id+1)) echo 'selected'?>><?echo $name?></option><?}?>
                                     </select>
                                 </label>
                             </section>
                         </div>
                         <div class="row">
                             <section class="col col-4">
                                 <label class="label">ФИО:</label>
                                 <label class="input"><input type="text" name="filter[name]" value="<?echo $this->filter['name']?>" id="personal_name" SetAutoComplete cmd="autocomplette_personal_name"></label>
                             </section>
                             <section class="col col-3">
                                 <label class="label">От:</label>
                                 <label class="input"><input type="text" name="filter[data_from]" class="datepicker" data-required value="<?echo $this->filter['data_from']?>"></label>
                             </section>
                             <section class="col col-3">
                                 <label class="label">До:</label>
                                 <label class="input"><input type="text" name="filter[data_to]" class="datepicker" data-required value="<?echo $this->filter['data_to']?>"></label>
                             </section>
                         </div>
                     </fieldset>
                     <?$this->panel_buttons();?>
                 </form>
         </div>
     <?
   }

function panel_info_filter()
{ $_str=array() ; $info=array() ; $title='' ;
  //if ($this->filter['member'])                           $info['механик']=ACCOUNTS()->get_member_name_by_id($this->filter['member'] )  ;
  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['Группа терминалов']=ACCOUNTS()->get_member_name_by_id($this->filter['group_id'])  ;
  if ($this->filter['dep_id'])                          $info['Подразделение']=PERSONAL()->get_full_dep_name_by_dep_id($this->filter['dep_id'])  ;
  if ($this->filter['pp_result'])                       $info['Тип результата']=$GLOBALS['pp_result'][$this->filter['pp_result']-1]  ;
  if ($this->filter['pol'])                       $info['Пол']=($this->filter['pol']-1)?'Женский':'Мужской'  ;
  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='<div class=center>'.implode(' ',$_str).'</div>' ;
  return $title ;
}

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[]='terminal_id>0' ;
  if ($this->filter['data_from']) $_usl[]='c_data>='.strtotime($this->filter['data_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 ($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['pol'])                 $_usl[]='member_pol='.($this->filter['pol']-1) ;
  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['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['pp_result']>0) {
    if ($this->filter['pp_result']==7) $_usl[]='_pp_result is NULL';
    elseif ($this->filter['pp_result']==1)   $_usl[]='_pp_result="ok"';
    else $_usl[]='_pp_result="'.$GLOBALS['pp_result'][$this->filter['pp_result']-1].'"';
  }

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

  return($usl_res) ;
}

 function get_cnt_items($usl,$options=array())
 {
    //$options['debug']=0 ;
    if ($usl) $usl='where '.$usl;
    $this->cnt_items=execSQL_value('select count(t_res.personal_id) from
                        (select personal_id,
                        count(pkey) as cnt_all
                        from view_mo_session_pp '.$usl.' 
                        group by personal_id
                        having cnt_all>0) as t_res
                        ',$options) ;
    return($this->cnt_items) ;
 }

 function get_items($usl,$options=array())
 {
     $limit=($options['limit'])? ' '.$options['limit']:'' ;
//   $options['debug']=1 ;
     if ($usl) $usl='where '.$usl;

//   $recs=execSQL('select pkey,model,working,member_pol,personal_age,_pp_result,group_id,
//                  parent,personal_parent1,personal_parent2,personal_parent3,personal_parent4,
//                  personal_parent5,personal_parent6,personal_parent7,personal_parent8,personal_parent9
//                  from view_mo_session_pp where '.$usl.$limit.$order,$options) ;
    $recs=execSQL('select personal_id,personal_name,working,member_pol,personal_age,group_id,_org_name,personal_parent,
                     personal_parent1,personal_parent2,personal_parent3,personal_parent4,personal_parent5,personal_parent6,personal_parent7,personal_parent8,personal_parent9,
                     count(pkey) as cnt_all
              from view_mo_session_pp '.$usl.' 
              group by personal_id, group_id, _org_name
              having cnt_all>0
              order by personal_name
              '.$limit,$options,1) ;
    return($recs) ;
 }

// шаблон - вывод ссылками без разделитея
function print_template_HTML($list_recs,$options=array())
{
    $arr_groups=execSQL_row('select pkey,obj_name,clss from obj_site_account where clss=206');
    ?><table class="basic fz_small full auto" >
    <tr><th rowspan="2">№</th>
        <th rowspan="2">ФИО</th>
        <th rowspan="2">Возраст</th>
        <th rowspan="2">Организация</th>
        <th rowspan="2">Должность</th>
        <th rowspan="2">Группа</th>
        <th colspan="7">Количество МО</th>
        <th rowspan="2">Итого</th>
    </tr>
    <tr>
        <?
        foreach ($GLOBALS['pp_result'] as $name){
            ?><th><?echo $name?></th><?
        }
        ?>
    </tr>
    <? $i=(_CUR_PAGE_NUMBER-1)*100+1 ;
//    $where_usl[]='model>0' ;
//    if ($this->filter['data_from'] or $this->filter['data_to']) {
//        if ($this->filter['data_from']) $where_usl[]='c_data>='.strtotime($this->filter['data_from']) ;
//        if ($this->filter['data_to']) $where_usl[]='c_data<='.strtotime($this->filter['data_to'].' 23:59:59') ;
//    }
//
//    $where_usl_res=implode(' and ',$where_usl) ;
//    $where_usl_res=' and '.$where_usl_res;
    $where_usl_res=' and '.$this->create_usl_select_obj([],$options) ;
    if (_sizeof($list_recs)) foreach($list_recs as $key=>$list_rec)
    {
        $pp_result=execSQL_row('select IFNULL(_pp_result,0),count(pkey) from view_mo_session_pp where personal_id='.$list_rec['personal_id'].$where_usl_res.' and group_id='.$list_rec['group_id'].' group by _pp_result');
        ?><tr><td><?echo $i?></td>
            <td><a href="/window/personal/person/<?echo $list_rec["personal_id"]?>/pp/" class="new_window" target="_blank" title="win_second"><?echo $list_rec['personal_name']?></a></td>
            <td><?echo $list_rec['personal_age']?></td>
            <td><?echo $list_rec['_org_name'] ?></td>
            <td><?echo _IL('IL_works')->recs[$list_rec['working']]['obj_name'];?></td>
            <td><?echo $arr_groups[$list_rec['group_id']]?></td>
            <td><?if ($pp_result['ok']) echo $pp_result['ok']?></td>
            <td><?if ($pp_result[$GLOBALS['pp_result'][1]]) echo $pp_result[$GLOBALS['pp_result'][1]]?></td>
            <td><?if ($pp_result[$GLOBALS['pp_result'][2]]) echo $pp_result[$GLOBALS['pp_result'][2]]?></td>
            <td><?if ($pp_result[$GLOBALS['pp_result'][3]]) echo $pp_result[$GLOBALS['pp_result'][3]]?></td>
            <td><?if ($pp_result[$GLOBALS['pp_result'][4]]) echo $pp_result[$GLOBALS['pp_result'][4]]?></td>
            <td><?if ($pp_result[$GLOBALS['pp_result'][5]]) echo $pp_result[$GLOBALS['pp_result'][5]]?></td>
            <td><?if ($pp_result[0]) echo $pp_result[0] ?></td>
            <td><?echo $list_rec['cnt_all']?></td>
        </tr>
       <?
       $i++ ;
    }
  ?></table><?
}


function print_template_CSV($list_recs,$options=array())
{
    $i=0 ;
    $arr_groups=execSQL_row('select pkey,obj_name,clss from obj_site_account where clss=206');
    $where_usl_res=' and '.$this->create_usl_select_obj(array()) ;
    if (_sizeof($list_recs)) foreach($list_recs as $rec)
    {
        $data=array() ;
        $data['№']=$i+1 ;
        $data['ФИО']=$rec['personal_name'] ;
        $data['Возраст']=$rec['personal_age'] ;
        $data['Организация']=$rec['_org_name']?$rec['_org_name']:'' ;
        $data['Должность']=_IL('IL_works')->recs[$rec['working']]['obj_name']?_IL('IL_works')->recs[$rec['working']]['obj_name']:'';
        $data['Группа']=$arr_groups[$rec['group_id']];

        $pp_result=execSQL_row('select IFNULL(_pp_result,0),count(pkey) from view_mo_session_pp where personal_id='.$rec['personal_id'].$where_usl_res.' and group_id='.$rec['group_id'].' group by _pp_result');
        $data['Норма']=$pp_result['ok']?$pp_result['ok']:'' ;
        $data['Зрачки сужены']=$pp_result[$GLOBALS['pp_result'][1]]?$pp_result[$GLOBALS['pp_result'][1]]:'' ;
        $data['Зрачки расширены (мидриаз)']=$pp_result[$GLOBALS['pp_result'][2]]?$pp_result[$GLOBALS['pp_result'][2]]:'' ;
        $data['Реакция отсутствует']=$pp_result[$GLOBALS['pp_result'][3]]?$pp_result[$GLOBALS['pp_result'][3]]:'' ;
        $data['Недостаточный процент распознания']=$pp_result[$GLOBALS['pp_result'][4]]?$pp_result[$GLOBALS['pp_result'][4]]:'' ;
        $data['Реакция ослаблена']=$pp_result[$GLOBALS['pp_result'][5]]?$pp_result[$GLOBALS['pp_result'][5]]:'' ;
        $data['Измерение не проводилось']=$pp_result[0]?$pp_result[0]:'' ;

        $data['Итого']=$rec['cnt_all']?$rec['cnt_all']:'0';

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

}




}

?>
