<?
class report_pp extends c_report
{
 var $title='Отчет по пупиллометрии' ;
 var $allow_export_to_csv=1 ;

 var $first_array=[];

 function setting()
   { 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 $this->url_report?>">
                     <fieldset>
                         <div class="row">
                             <section class="col col-2">
                                 <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-2">
                                 <label class="label">Минимальное кол-во измерений:</label>
                                 <label class="input"><input type="text" name="filter[cnt_pp]" value="<?echo $this->filter['cnt_pp']?>"></label>
                             </section>
                             <? $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_workd_ids) ;
                                 ?>
                         </div>
                         <div class="row">
                             <section class="col col-3">
                                 <label class="label">Возрастная группа:</label>
                                 <label class="select">
                                     <select name="filter[age_group]">
                                         <option value="0"></option>
                                         <?
                                         foreach(PP()->pp_age_group as $key=>$rec) {?><option value="<?echo $key?>" <?if ($this->filter['age_group']==$key) echo 'selected'?>><?echo $rec['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>
                                         <?
                                         $pp_result_list=PP()->getPPResultList();
                                          if (_sizeof($pp_result_list)) foreach($pp_result_list as $key=>$rec) {?><option value="<?echo $key?>" <?if ($this->filter['pp_result']==$key) echo 'selected'?>><?echo $rec?></option><?}?>
                                     </select>
                                 </label>
                             </section>
                             <section class="col col-3">
                                 <label class="label">Время измерения от:</label>
                                 <label class="input"><input type="text" name="filter[timepick_from]" class="timepicker_test" value="<?echo $this->filter['timepick_from']?>"></label>
                             </section>
                             <section class="col col-3">
                                 <label class="label">Время измерения до:</label>
                                 <label class="input"><input type="text" name="filter[timepick_to]" class="timepicker_test"  value="<?echo $this->filter['timepick_to']?>"></label>
                             </section>
                         </div>
                         <div class="row">
                             <section class="col col-3">
                                 <label class="label">Дата измерения от:</label>
                                 <label class="input"><input type="text" name="filter[data_from]" class="datepicker" 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" value="<?echo $this->filter['data_to']?>"></label>
                             </section>
                         </div>
                         <div class="row">
                             <section class="col col-3">
                                 <label class="label">Сортировка:</label>
                                 <label class="select">
                                     <select name="filter[order]">
                                         <option value="0"></option>
                                         <option value="cnt_pp" <?if ($this->filter['order']=="cnt_pp") echo 'selected'?>>Кол-во измерений: по возрастанию</option>
                                         <option value="cnt_pp desc" <?if ($this->filter['order']=="cnt_pp desc") echo 'selected'?>>Кол-во измерений: по убыванию</option>
                                         <option value="obj_name" <?if ($this->filter['order']=="obj_name") echo 'selected'?>>ФИО</option>
                                     </select>
                                 </label>
                             </section>
                         </div>
                     </fieldset>
                     <?$this->panel_buttons();?>
                 </form>
         </div>
       <script type="text/javascript">
           $j('.timepicker_test').timepicker();
       </script>
     <?
   }

    function create_usl_select_obj($_params,&$options)
    {
//        damp_array($this->filter,1,-1) ;
        $usl=array() ;
        $usl[]='clss=211' ;
        $usl[]='enabled=1';
//        if ($this->filter['time_from'])     $usl[]='t2.c_data>='.$this->filter['time_from'] ;
//        if ($this->filter['time_to'])       $usl[]='t2.c_data<='.$this->filter['time_to'] ;
//        if ($this->filter['data_from'])     $usl[]='t2.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[] = 't2.c_data<=' . $time_to;
//        }

        if ($this->filter['pkey'])              $usl[]='pkey='.$this->filter['pkey'] ;
        if ($this->filter['name'])              $usl[]='obj_name like "'.$this->filter['name'].'%"' ;
//        if ($this->filter['dep_id'])          $usl[]='parent='.$this->filter['dep_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['uid'])              $usl[]='uid='.$this->filter['uid'] ;
        if ($this->filter['ids'])              $usl[]='pkey in ('.implode(',',array_keys($this->filter['ids'])).')' ;
        if ($this->filter['propusk'])          $usl[]='propusk="'.$this->filter['propusk'].'"' ;
        if ($this->filter['working_id'])          $usl[]='working="'.$this->filter['working_id'].'"' ;
        if ($this->filter['working'])   {
            $keys=array_keys($this->filter['working']);
            $usl[]='working in ('.implode(",",$keys).')';
        }
        if ($this->filter['age_group'])   {
            if (PP()->pp_age_group[$this->filter['age_group']]['min']) $usl[]='age>='.PP()->pp_age_group[$this->filter['age_group']]['min'];
            if (PP()->pp_age_group[$this->filter['age_group']]['max']) $usl[]='age<='.PP()->pp_age_group[$this->filter['age_group']]['max'];
        }
        if ($this->filter['ext']==1)          $usl[]='ext=1' ; else $usl[]='(ext=0 or ext is null)' ;
        // выбор сотрудников по ID группы
        if ($this->filter['personal_ids'])    $usl[]='pkey in ('.$this->filter['personal_ids'].')' ;

//        if ($this->filter['cnt_pp'])              $usl[]='cnt_pp>='.$this->filter['cnt_pp'] ;
//            else $usl[]='cnt_pp>0';

//        if ($this->filter['group_id']) $usl[]='t3.group_id='.$this->filter['group_id'];

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

//        damp_array($usl,1,-1) ;
        return($usl_res) ;
    }



    function panel_info_filter()
    {
    $_str=array() ; $info=array() ; $title='' ;
    if ($this->filter['group_id'])                        $info['Группа терминалов']=ACCOUNTS()->get_member_name_by_id($this->filter['group_id'])  ;
    if ($this->filter['org_ids'])                          $info['организация']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['org_ids']))  ;
    if ($this->filter['working'])
    {
        $working_names=[];
        foreach (array_keys($this->filter['working']) as $array_key){
            $working_names[]=_IL('IL_works')->recs[$array_key]['obj_name'];
        }
        $info['Должность']=implode(', ',$working_names);
    }
    if ($this->filter['data_from']) $info['Дата от']=$this->filter['data_from'] ;
    if ($this->filter['data_to']) $info['Дата до']=$this->filter['data_to'] ;
    if ($this->filter['age_group']) $info['Возрастная группа']=PP()->pp_age_group[$this->filter['age_group']]['name'];
    if ($this->filter['pp_result']) $info['Результаты пупиллометрии']=PP()->getPPResultName($this->filter['pp_result']);
    if ($this->filter['timepick_from'] and $this->filter['timepick_to']){
        $info['Время измерения']='От '.$this->filter['timepick_from'].' до '.$this->filter['timepick_to'];
    } elseif ($this->filter['timepick_from'])  {
        $info['Время измерения']='От '.$this->filter['timepick_from'];
    } elseif ($this->filter['timepick_to']) {
        $info['Время измерения']='До '.$this->filter['timepick_to'];
    }

    if ($this->filter['cnt_pp'])          $info['Минимальное количество измерений']=$this->filter['cnt_pp'] ;
    if (_sizeof($info)) foreach($info as $title=>$value)   if (is_array($value)) $_str[]=$title.': <strong>'.implode(',',$value).'</strong>' ; else $_str[]=$title.': <strong>'.$value.'</strong>' ;
    if (_sizeof($_str)) $title='<p class=center>'.implode(' ',$_str).'</p>' ;
    return $title ;
    }


    function get_cnt_items($usl,$options=array())
    {  // !!! использовать  PERSONAL()->table_personal так как вьювер жутко тупит
//        $options['debug']=1 ;

        if (!$this->filter['pp_result'] and !$this->filter['timepick_from'] and !$this->filter['timepick_to'] and !$this->filter['data_from'] and !$this->filter['data_to']) { //если нет фильтра по результатам ПП, и времени измерения, то ищем общее кол-во по упрощенному
            if ($this->filter['cnt_pp'])    $usl.=' and cnt_pp>='.$this->filter['cnt_pp'] ;
                else $usl.=' and cnt_pp>0';
            $arr=execSQL('select pkey
                                from '.PERSONAL()->view_personal.' t1
                                where '.$usl,$options);
            return(count($arr));
        } else {
            if ($this->filter['pp_result']) $usl2_arr[]='result_code='.$this->filter['pp_result']; //условие по результату ПП

            if ($this->filter['timepick_from'] and $this->filter['timepick_to']){ //условие по времени результата ПП
                $usl2_arr[]=PP()->getTimepickQuery(0,$this->filter['timepick_from'],$this->filter['timepick_to']);
            } elseif ($this->filter['timepick_from'])  {
                $usl2_arr[]=PP()->getTimepickQuery(1,$this->filter['timepick_from']);
            } elseif ($this->filter['timepick_to']) {
                $usl2_arr[]=PP()->getTimepickQuery(2,$this->filter['timepick_to']);
            }
            if ($this->filter['data_from']) $usl2_arr[]='c_data>='.strtotime($this->filter['data_from']);
            if ($this->filter['data_to']) $usl2_arr[]='c_data<='.strtotime($this->filter['data_to']);
            if ($this->filter['cnt_pp'])    $having=' having cnt_pp>='.$this->filter['cnt_pp'] ;
            $group=' group by personal_id';
            $usl2=implode(' and ',$usl2_arr);
            //массив со всеми сотрудниками
            $arr1=execSQL('select pkey,obj_name,age,_org_id,_org_name,_otdel_id,_otdel_name,working
                                from '.PERSONAL()->view_personal.'
                                where '.$usl,$options);
            //массив с результатами сотрудников по заданным фильтрам
            $arr2=execSQL('select personal_id, count(pkey) as cnt_pp from obj_site_narko_data where '.$usl2.$group.$having,$options);
            $arr3=array_intersect_key($arr1,$arr2); //пересечение массивов
            foreach ($arr3 as &$rec) { //добавление в объединенный массив кол-ва результатов
                $rec['cnt_pp']=$arr2[$rec['pkey']]['cnt_pp'];
            }
            $this->first_array=$arr3;
            return(count($this->first_array));
        }

    }

    function get_items($usl,$options=array())
    {
        if (!$this->filter['pp_result'] and !$this->first_array['timepick_from'] and !$this->first_array['timepick_to']) { //если нет фильтра по результатам ПП, и времени измерения, то ищем общее кол-во по упрощенному
            $limit=($options['limit'])? ' '.$options['limit']:'' ;
            if ($this->filter['cnt_pp'])              $usl.=' and cnt_pp>='.$this->filter['cnt_pp'] ;
            else $usl.=' and cnt_pp>0';
            $order=($this->filter['order'])? ' order by '.$this->filter['order']:' order by obj_name' ;
            $list_rec=execSQL('select pkey,obj_name,age,_org_id,_org_name,_otdel_id,_otdel_name,working,cnt_pp
                                from '.PERSONAL()->view_personal.'
                                where '.$usl.$order.$limit,$options);
            return($list_rec) ;
        } else {
            $list_rec=$this->first_array;
            switch ($this->filter['order']){ //если сортируем массив
                case 'cnt_pp':  usort($list_rec, function($a, $b){
                                    return ($a['cnt_pp']<$b['cnt_pp'])?-1:1;
                                });
                                break;
                case 'cnt_pp desc':  usort($list_rec, function($a, $b){
                                    return ($a['cnt_pp']>$b['cnt_pp'])?-1:1;
                                });
                                break;
                case 'obj_name':  usort($list_rec, function($a, $b){
                                    return ($a['obj_name']<$b['obj_name'])?-1:1;
                                });
                                break;
            }
            if (!$options['limit']) { // разбиваем по страницам
                $lim_cnt=50;
                $lim_min=0;
            } else {
                list($lim_min,$lim_cnt)=explode(',',str_replace('limit ','',$options['limit']));
            }
            $recs=array_slice($list_rec,$lim_min,$lim_cnt);
            return($recs) ;
        }
    }

    function print_template_HTML($list_recs,$options=array())
    { $id=($options['id'])? 'id='.$options['id']:'' ;
        $pp_link='';
        $pp_link_array=[];
        if ($this->filter['pp_result']) $pp_link_array[]='pp_result='.$this->filter['pp_result'];
        if ($this->filter['timepick_from']) $pp_link_array[]='timepick_from='.$this->filter['timepick_from'];
        if ($this->filter['timepick_to']) $pp_link_array[]='timepick_to='.$this->filter['timepick_to'];
        if ($this->filter['data_from']) $pp_link_array[]='data_from='.$this->filter['data_from'];
        if ($this->filter['data_to']) $pp_link_array[]='data_to='.$this->filter['data_to'];
        if ($pp_link_array) $pp_link='['.implode(',',$pp_link_array).']/';
        ?><table class="list_personal_table_img basic fz_small full auto"<?echo $id?>>
        <colgroup><col id="c1"><col id="c2"><col id="c3"><col id="c4"></colgroup>
        <tr>
            <th>№</th>
            <th>ФИО</th>
            <th>Возраст</th>
            <th>Организация</th>
            <th>Подразделение</th>
            <th>Должность</th>
            <th>Кол-во измерений</th>
        </tr><? ;
        $i=$this->first_obj ;
        if (_sizeof($list_recs)) foreach($list_recs as $rec)
        { ?><tr class=item>
            <td><?echo $i; $i++;?></td>
            <td class="left"><a href="<?echo '/cab/personal/person/'.$rec['pkey'].'/pp/'?>" class="new_window" target="_blank" title="win_second"><?echo $rec['obj_name']?></a></td>
            <td class="age"><?echo $rec['age']?></td>
            <td class="left"><?echo $rec['_org_name']?></td>
            <td class="left"><?echo $rec['_otdel_name']?></td>
            <td class="left"><?echo _IL('IL_works')->recs[$rec['working']]['obj_name']?></td>
            <td><a href="<?echo '/cab/personal/person/'.$rec['pkey'].'/pp/'.$pp_link?>" class="new_window" target="_blank" title="win_second"><?echo $rec['cnt_pp']?></a></td>
            </tr><?
        }
        ?></table><?
        //damp_array($rec) ;
    }

    function print_template_CSV($list_recs,$options=array())
    {
        $i=0 ;
        if (_sizeof($list_recs)) foreach($list_recs as $rec)
        {
            $data=array() ;
            $data['ФИО']=$rec['obj_name']?$rec['obj_name']:'' ;
            $data['Возраст']=$rec['age']?$rec['age']:'' ;
            $data['Организация']=$rec['_org_name']?$rec['_org_name']:'';
            $data['Подразделение']=$rec['_otdel_name']?$rec['_otdel_name']:'' ;
            $data['Должность']=_IL('IL_works')->recs[$rec['working']]['obj_name']?_IL('IL_works')->recs[$rec['working']]['obj_name']:'' ;
            $data['Кол-во измерений']=$rec['cnt_pp']?$rec['cnt_pp']:'' ;


            if (_sizeof($data)) foreach($data as $fname=>$value) $data[$fname]=iconv('UTF-8','windows-1251',$value) ;
            // для первой строки выводим заголовки
            if (!$i)
            {   $arr_title=array_keys($data) ;
                foreach($arr_title as $i=>$title) $arr_title[$i]=iconv('UTF-8','windows-1251',$title) ;
                fputcsv($this->file_csv,$arr_title,';');
            }
            // вывод данных
            fputcsv($this->file_csv,$data,';');
            $i++ ;
        }

    }

}

?>
