<?
// вниамение!!!
// во всех фильтрах:
// data_from, data_to - дата в текстовом формате
// time_from, time_to - дата в UNIX формате

class report_kt extends c_report
{
 var $title='Журнал КТ' ;
 var $view_only_model=1 ;
 var $mo_sort='pkey' ;
 var $allow_export_to_csv=1 ;

 function setting()
{ //if (isset($this->filter['time_from'])) $this->filter['data_from']=date('d.m.Y',$this->filter['time_from']);
  //if (isset($this->filter['time_to'])) $this->filter['data_to']=date('d.m.Y',$this->filter['time_to']);
  if (isset($this->filter['personal_id'])) $this->filter['name']=PERSONAL()->get_name_by_id($this->filter['personal_id']);

  $arr_accounts=ACCOUNTS()->get_list_members(array('group_id'=>MEMBER()->cur_group_id,'rol'=>'2,3')) ;
  $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) ;
  $arr_terminals=DEVICE()->get_list_terminals(MEMBER()->cur_zone_id,'kt') ;

  ?><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',KT()->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_input_text('name','ФИО:',2,array('auto_complete'=>"autocomplette_personal_name")) ;
                    ?>
                </div>
                <div class="row">
                    <? if (MEMBER()->rol!=2) $this->filter_section_select('doctor_id','Фельдшер:',2,$arr_accounts,array('space_element'=>1)) ;
                       $this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
                       $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;
                       $this->filter_section_select('tk','Тип контроля:',2,$_SESSION['ARR_mo_tk_type'],array('use_id_plus_1'=>1)) ;
                       $this->filter_section_select('terminal_id','Терминал:',2,$arr_terminals,array('key_fname'=>'id')) ;
                    ?>
                    <section class="col col-2">
                        <label class="label">Допуск:</label>
                        <label class="radio">
                        <?
                        if (_sizeof(KT()->ARR_status_dopusk)) foreach(KT()->ARR_status_dopusk as $id=>$value)
                           {?><label class="radio"><input type="checkbox" name="filter[dopusk][]" value="<?echo $id?>" <?if (($this->filter['dopusk'][$id])) echo 'checked'?>><i></i><?echo $value?></label><?}
                        ?>
                    </section>
                </div>
            </fieldset>
            <?$this->panel_buttons();?>
        </form>
     </div>
  <?
}

function panel_info_filter()
 { $_str=array() ; $info=array() ; $title='' ;
   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['org_id'])                          $info['организация']=PERSONAL()->get_name_by_id($this->filter['org_id']) ;
   if ($this->filter['org_ids'])                         $info['Организации']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['org_ids']))  ;
   if ($this->filter['otdel_ids'])                       $info['Подразделения']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['otdel_ids']))  ;
   if ($this->filter['otdel_id'])                        $info['подразделение']=PERSONAL()->get_name_by_id($this->filter['otdel_id']) ;
   if ($this->filter['name'])                            $info['ФИО']='"'.$this->filter['name'].'"' ;
   if ($this->filter['propusk'])                         $info['Пропуск']='"'.$this->filter['propusk'].'"' ;
   if ($this->filter['doctor_id'])                       $info['Доктор']=ACCOUNTS()->get_member_name_by_id($this->filter['doctor_id'])  ;

   if ($this->filter['terminal_id'])                       $info['Терминал']=$this->filter['terminal_id']  ;
   if ($this->filter['tk'])                              $info['Тип контроля']=$_SESSION['ARR_mo_tk_type'][$this->filter['tk']-1]  ;
   if ($this->filter['status'])                          $info['Осмотр на терминале']=$_SESSION['ARR_status_sess'][$this->filter['status']]  ;
   if (is_array($this->filter['dopusk']))                  foreach($this->filter['dopusk'] as $dopusk_id=>$value) $info['Допуск'][]=KT()->ARR_status_dopusk[$dopusk_id]  ;
   else if ($this->filter['dopusk'])                     $info['Допуск']=KT()->ARR_status_dopusk[$this->filter['dopusk']]  ;
   if ($this->filter['a'])                               $info['Причина отказа'][]='Алкоголь'  ;
   if ($this->filter['d'])                               $info['Причина отказа'][]='Давление'  ;
   if ($this->filter['p'])                               $info['Причина отказа'][]='Пульс'  ;
   if ($this->filter['t'])                               $info['Причина отказа'][]='Температура'  ;
   if ($this->filter['q'])                               $info['Причина отказа'][]='Жалобы'  ;
   if ($this->filter['n'])                               $info['Причина отказа'][]='ПП'  ;
   if ($this->filter['v'])                               $info['Причина отказа'][]='ТКТ'  ;
   if ($this->filter['other'])                            $info['Причина отказа'][]='Другое'  ;
   if ($this->filter['other2'])                            $info['Причина отказа'][]='Другое'  ;
   if ($this->filter['ef'])                               $info['Ошибка оборудования'][]='Да'  ;
   if ($this->filter['equipmentErrorOrCancelTimeout'])    $info['Не удалось провести измерение'][]='Да'  ;
   if ($this->filter['equipmentFailure'])                $info['Ошибка оборудования'][]='Да'  ;
   if ($this->filter['equipment'])                       $info['Устройство'][]=$this->filter['equipment']  ;
   if (_sizeof($this->filter['model']))                   foreach($this->filter['model'] as $model_id=>$value) $info['Модель МО'][]=$_SESSION['ARR_model_osmotr'][$model_id]  ;
   if ($this->filter['mo_ids'])    { $info['ID MO']=implode(',',array_keys($this->filter['mo_ids'])) ; unset($info['Модель МО']) ; }
   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>' ;
   $this->report_info=$info ;
   return $title ;

 }

 function create_usl_select_obj($_params,&$options)
 { //damp_array($this->filter) ;
 if (MEMBER()->rol==2) $this->filter['group_id']=MEMBER()->cur_group_id ;
     $options_select=array() ;
   if (is_array($this->filter['dopusk']))
   { $arr=array() ;
     foreach($this->filter['dopusk'] as $dopusk_id=>$value) $arr[]=$dopusk_id ;
     $options_select['dopusk']=implode(',',$arr) ;

     //$options_select['status']='2,3' ;  // только завершенные МО
     $options_select['only_model']='all' ;  // только конечные МО с моделью
   } elseif ($this->filter['dopusk']) $options_select['dopusk']=$this->filter['dopusk'] ;
   if ($this->filter['status'])    $options_select['status']=$this->filter['status'] ;
   if ($this->filter['status'])    $options_select['status']=$this->filter['status'] ;
   if ($this->filter['group_id'])  $options_select['group_id']=$this->filter['group_id'] ;
   if ($this->filter['doctor_id']) $options_select['doctor_id']=$this->filter['doctor_id'] ;
   if ($this->filter['terminal_id']) $options_select['terminal_id']=$this->filter['terminal_id'] ;
   if ($this->filter['time_from']) $options_select['time_from']=$this->filter['time_from'] ;
   if ($this->filter['data_from']) $options_select['data_from']=$this->filter['data_from'] ;
   if ($this->filter['time_to'])   $options_select['time_to']=$this->filter['time_to'] ;
   if ($this->filter['data_to'])   $options_select['data_to']=$this->filter['data_to'] ;
   if ($this->filter['tk'])        $options_select['tk']=$this->filter['tk'] ;
   if ($this->filter['dep_id'])    $options_select['dep_id']=$this->filter['dep_id'] ;
   if ($this->filter['org_id'])    $options_select['org_id']=$this->filter['org_id'] ;
   if ($this->filter['org_ids'])  $options_select['org_ids']=implode(',',array_keys($this->filter['org_ids'])) ;
   if ($this->filter['otdel_ids'])  $options_select['otdel_ids']=implode(',',array_keys($this->filter['otdel_ids'])) ;
   if ($this->filter['otdel_id'])  $options_select['otdel_id']=$this->filter['otdel_id'] ;
   if ($this->filter['personal_id'])  $options_select['personal_id']=$this->filter['personal_id'] ;
   if ($this->filter['name'])      $options_select['name']=$this->filter['name'] ;
   if ($this->filter['propusk'])   $options_select['propusk']=$this->filter['propusk'] ;
   if ($this->filter['no_a'])         $options_select['res_stat']['no_a']=1 ;
   if ($this->filter['a'])         $options_select['res_stat']['a']=1 ;
   if ($this->filter['d'])         $options_select['res_stat']['d']=1 ;
   if ($this->filter['p'])         $options_select['res_stat']['p']=1 ;
   if ($this->filter['t'])         $options_select['res_stat']['t']=1 ;
   if ($this->filter['q'])         $options_select['res_stat']['q']=1 ;
   if ($this->filter['n'])         $options_select['res_stat']['n']=1 ;
   if ($this->filter['v'])         $options_select['res_stat']['v']=1 ;
   if ($this->filter['min_s'])     $options_select['min_s']=$this->filter['min_s'] ;
   if ($this->filter['max_s'])     $options_select['max_s']=$this->filter['max_s'] ;
   if ($this->filter['ssz'])       $options_select['res_stat']['ssz']=1 ;
   if ($this->filter['other'])     $options_select['res_stat']['other']=1 ;
   if ($this->filter['other2'])       $options_select['res_stat']['other2']=1 ;
   if (isset($this->filter['only_model']))     $options_select['only_model']=$this->filter['only_model'] ;
  // if (isset($this->filter['only_model_0']))     $options_select['only_model']=0 ;
   if ($this->filter['ef'])        $options_select['_use_usl'][]='reason="equipmentFailure"' ;
   if ($this->filter['equipmentError'])  $options_select['_use_usl'][]='reason="equipmentError"' ;
   if ($this->filter['equipmentErrorOrCancelTimeout'])  $options_select['_use_usl'][]='(reason="equipmentError" or reason="cancelTimeout")' ;
   if ($this->filter['equipmentFailure'])  $options_select['_use_usl'][]='reason="equipmentFailure"' ;
   if ($this->filter['equipment'])  $options_select['_use_usl'][]='equipment="'.$this->filter['equipment'].'"' ;
   if ($this->filter['cancelTimeout'])     $options_select['_use_usl'][]='reason="cancelTimeout"' ;

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

   if (_sizeof($this->filter['model'])) $options_select['only_model']=implode(',',array_keys($this->filter['model'])) ;
   elseif ($this->view_only_model)  $options_select['only_model']='all' ;
   elseif ($this->filter['model_all'])  $options_select['only_model']='all' ;
   if ($this->filter['mo_ids'])    { $options_select['mo_ids']=implode(',',array_keys($this->filter['mo_ids'])) ; unset($options_select['only_model']) ; }

   // было OR, но это не позволяло делать корректные выборки при наличии нескольких условий
   if (_sizeof($options_select['_use_usl'])) $options_select['use_usl']='('.implode(' and ',$options_select['_use_usl']).')' ;

   //damp_array($this->filter) ;
   //damp_array($options_select,1,-1) ;
   $options_select['debug']=0 ;
   $usl_res=KT()->get_usl_select_mo_by_filter($options_select) ;
   //echo $usl_res ;
   return($usl_res) ;
 }

  function get_cnt_items($usl,$options=array())
  { //$options['debug']=2 ;
    $this->cnt_items=execSQL_value('select count(pkey) from '.KT()->view_mo_session.' where '.$usl,$options) ;
    return($this->cnt_items) ;
  }

  function get_items($usl,$options=array())
  { $limit=($options['limit'])? ' '.$options['limit']:'' ;
    $order=($options['order'])? ' order by '.$options['order']:' order by '.$this->mo_sort ;
    //$order=' order by '.$this->mo_sort ;
    //if (_IS_SYSTEM_IP) $options['debug']=1 ;
    $recs=execSQL('select * from '.KT()->view_mo_session.' where '.$usl.$order.$limit,$options) ;
    if (_sizeof($recs) and !$options['no_public_info']) foreach($recs as $id=>$rec) KT()->prepare_public_info_to_mo($recs[$id],$options) ;
    return($recs) ;
  }

 // шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  {

    ?><table class="basic fz_small auto full" id="report_kt" >
        <tr><th>ID</th>
            <th>Дата/время</th>
            <th>Тип контроля</th>
            <th>Фото</th>
            <th>ФИО<br>сотрудника</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 '<a href="/cab/kt/card/'.$rec['pkey'].'/" target=_blank>'.$rec['pkey'].'</a>' ;  $i++ ;?></td>
                <td><?echo date('d.m.Y',$rec['c_data']).'<br>'.date('H:i',$rec['c_data'])?></td>
                <td><?echo $rec['_tk_name']?></td>
                <td class="photo"><div>
                    <div class="img" style="float:left;"><? if ($rec['_member_img']) { ?><img width=100 src="<?echo $rec['_member_img']?>"><?}?></div>
                    <div class="img" style="float:left;"><? if ($rec['_member_img_auth']) {?><img width=100 src="<?echo $rec['_member_img_auth']?>"><?}?></div>
                    <div class="img" style="float:left;"><? if ($rec['_member_img_alco']) {?><img width=100 src="<?echo $rec['_member_img_alco']?>"><?}?></div>
                    <div class="clear"></div></div>
                </td>
                <td class="name"><?echo $rec['member_name']?></td>
                <td class="name"><?echo ($rec['member_pol'])? 'Женский':'Мужской' ;?></td>
                <td class="name"><?if ($rec['member_dr']) echo $rec['member_dr'];?></td>
                <td class="left"><?echo $rec['_org_name'].'<br>'.$rec['_otdel_name']?></td>
                <td <?if ($rec['res_a']>1) echo 'class=red'?>><?if ($rec['status']>=2 and $rec['status']<=3 and $rec['alcotester']) echo $rec['_alko'] ;
                        //if ($rec['alko']>0 and $rec['alko_value']==0) echo 'есть' ; else echo($rec['alko_value']>0)? ' '.$rec['alko_value'].' промиле':'нет'; else echo '-'
                    ?></td>
                <?  // убрано слово "не выявлено", так как непонятно что именно "не выявлено" ?>
                <td class="left"><?
                    if ($rec['comment']) { $arr=explode('<br>',$rec['comment']) ; echo '<ul>' ; if (_sizeof($arr)) foreach($arr as $value)  echo '<li>'.$value.'</li>' ; echo '</ul>' ; }
                                                      if ($rec['status']==2) echo '<div class=ok>'.$rec['_status_name'].'</div>' ;
                                                   ?>
                </td>
                <td class=dopusk_<?echo $rec['dopusk']?>><?echo $rec['_dopusk_name']?></td>
            </tr><?
        }
      ?></table><div id="panel_image_preview"></div>
      <script type="text/javascript">
          $j(document).ready(function()
          {    $j('div.list_mo_sessions td.photo div.img img').hover(
                  function() { $j('div#panel_image_preview').addClass('active').html('<img src="'+$j(this).attr('src')+'">');},
                  function() {  $j('div#panel_image_preview').removeClass('active');}
                ) ;
          }) ;
      </script>
      <style type="text/css">
          table#report_kt{}
          table#report_kt td.photo{width:320px;}
          table#report_kt td.photo img{float:left;margin:0 5px 5px 0;}
          table#report_kt td.dopusk_1{background:rgba(0, 128, 0, 0.53);color:white;;}
          table#report_kt td.dopusk_2{color: white;background: rgba(255, 0, 0, 0.51);}
      </style>



      <?

     //damp_array($rec,1,-1) ;
  }

    function print_template_CSV($list_recs,$options=array())
            { $i=$options['from'] ;
              if (_sizeof($list_recs)) foreach($list_recs as $rec)
                { $rec_doctor=_IL('ARR_accounts')->recs[$rec['doctor_id']] ;

                  $data=array() ;
                    // обязательные поля в каждой выгрузке
                    $data['MO ID']=$rec['pkey'] ;
                    $data['Дата']=date('d.m.Y H:i:s',$rec['c_data']) ;
                    $data[$GLOBALS['LS_person_group_title'].' КТ']=SKD()->tree[$rec['group_id']]->name ;
                    $data['UID сотрудника']=$rec['member_uid'];
                  $data['ФИО сотрудника']=$rec['member_name'] ;
                    $data['Организация']=$rec['_org_name'];
                    $data['Подразделение']=$rec['_otdel_name'];
                    $data['Должность']=_IL('IL_works')->recs[$rec['working']]['obj_name'];
                  $data['Пол']=($rec['member_pol'])? 'Женский':'Мужской' ;
                  $data['ДатаРожд']=$rec['member_dr'] ;

                  $data['Жалобы']=($rec['status']==2 or $rec['status']==3)? ($rec['question'])? 'Есть':'Нет':'-'   ; if ($rec['question_comment']) $data['Жалобы'].=' '.$rec['question_comment'] ;
                  $data['Давление систолическое']=$rec['_systolic']  ;
                  $data['Давление диастолическое']=$rec['_diastolic']  ;
                  $data['Пульс']=$rec['_pulse'] ;
                  $data['Температура']=$rec['_temperature_csv'] ;
                  $data['Алкоголь']=($rec['alko']>0)? 'Есть '.(($rec['alko_value']>0)? ' ('.$rec['alko_value'].')':''):($rec['alcotester']? 'Нет':'-')  ;
                  $pzipr='' ;
                  if ($rec['status']>=2 and $rec['status']<=3) $pzipr=($rec['simptoms'])? _IL('IL_diagnoz')->recs[$rec['simptoms']]['obj_name']:'Не выявлено'; else echo '-' ;
                  //if ($rec['comment']) $pzipr.=' '.$rec['comment']  ;
                  //if ($rec['status']==2) $pzipr.=' '.$rec['_status_name'] ;
                  $data['ПЗиПР']=$pzipr ;
                  $data['Допуск']=$rec['_dopusk_name'];
                  $data['Врач']=$rec_doctor['obj_name']  ;
                  $data['Длительность сеанса']=$rec['__dlit_mo']  ;

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

                  $i++ ;
                }

            }


}
?>
