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

class report_terminal_sanitar extends c_report
{
 var $title='Журнал санобработки терминалов' ;
 var $view_by_space_filter=1 ;


 function setting()
 {
     $arr_terminals=ESMO()->get_list_terminals(MEMBER()->cur_group_id) ;

     ?><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">
                    <? $this->filter_section_select('terminal_id','Терминал:',2,$arr_terminals,array('key_fname'=>'id')) ;
                       $this->filter_section_select('status','Статус:',2,SANITAR()->arr_status) ;
                       $this->filter_section_input_text('data_from','От:',2,array('class'=>'datetimepicker')) ;
                       $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;
                    ?>
                </div>
            </fieldset>
            <?$this->panel_button_apply();?>
        </form>
     </div>
  <?
}





 function panel_info_filter()
 { $_str=array() ; $info=array() ; $title='' ;     //damp_array($this->filter,1,-1) ;
   if ($this->filter['data_from'])                       $info['c']=$this->filter['data_from'] ;
   if ($this->filter['data_to'])                         $info['по']=$this->filter['data_to'] ;
   if ($this->filter['terminal_id'])                     $info['Терминал']=$this->filter['terminal_id']  ;
   if ($this->filter['status'])                          $info['Статус']=SANITAR()->arr_status[$this->filter['status']]  ;

   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 create_usl_select_obj($_params,&$options)
 { //damp_array($this->filter,1,-1);
   if ($this->filter['terminal_id'])        $_usl[]='t1.terminal_id='.$this->filter['terminal_id'].'' ;
   if ($this->filter['status'])             $_usl[]='t1.status='.$this->filter['status'].'' ;
   if ($this->filter['data_from'])          $_usl[]='t1.c_data>='.strtotime($this->filter['data_from']) ;
   if ($this->filter['data_to'])            $_usl[]='t1.c_data<='.strtotime($this->filter['data_to']) ;
   $usl_res=(_sizeof($_usl))? implode(' and ',$_usl):1 ;
   return($usl_res) ;
 }

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

  function get_items($usl,$options=array())
  { $limit=($options['limit'])? ' '.$options['limit']:'' ;
    $order=' order by t1.c_data desc' ;
    $options['debug']=0 ;
    $recs=execSQL('select t1.*,
                   t2.obj_name as doctor_name,
                   t3.obj_name as group_name  
                   from log_terminal_sanitar t1
                   left join obj_site_account t2 on t2.pkey=t1.doctor_id 
                   left join obj_site_account t3 on t3.pkey=t1.group_id 
                   where '.$usl.$order.$limit,$options) ;
    return($recs) ;
  }

 // шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  {  $options['id']='panel_last_mo' ;
     $options['base_dir']='' ;
     if (!isset($options['no_reverse_indx'])) $options['no_reverse_indx']=$this->filter['skoro'] ;
     ?><table class="basic fz_small full auto">
      <tr class="head"><th>ID</th><th>Дата/время</th><th>Группа ЭСМО</th><th>Терминал</th><th>Фельдшер</th><th>Статус</th><th>Доп.информация</th><th>Фото</th><th>Роспись</th></tr><?

          if (_sizeof($list_recs)) foreach($list_recs as $rec)
          {
              if ($rec['status']==2)
              {
                  $options=array('check_directory'=>0,'no_check_exist_file'=>1,'base_dir'=>'/public/sanitar/sign_image/') ;
                  $DTW_dir=ENGINE()->get_dir_by_id($rec['pkey'],'relative','_DTW.png',$options) ;
                  $options=array('check_directory'=>0,'no_check_exist_file'=>1,'base_dir'=>'/public/sanitar/photo/') ;
                  $photo_dir=ENGINE()->get_dir_by_id($rec['pkey'],'relative','.jpg',$options) ;
              }


              ?><tr>
                <td><?echo $rec['pkey']?></td>
                <td><?echo date('d.m.Y H:i:s',$rec['c_data'])?></td>
                <td><?echo $rec['group_name']?></td>
                <td><?echo $rec['terminal_id']?></td>
                <td><?echo $rec['doctor_name']?></td>
                <td><?echo SANITAR()->arr_status[$rec['status']]?></td>
                <td><?if ($rec['mo_id']) echo '<a class=new_window href="/window/mo/'.$rec['mo_id'].'/">МО ID '.$rec['mo_id'].'</a>' ;
                      if ($rec['obj_name']) echo $rec['obj_name'] ;
                    ?></td>
                <td><?if ($photo_dir) echo '<img width=100 class=photo src="'.$photo_dir.'" width=100>'?></td>
                <td><?if ($DTW_dir) echo '<img width=100 src="'.$DTW_dir.'">'?></td>
             </tr><?
          }
          ?></table><div id="panel_image_preview"></div>
          <script type="text/javascript">
              $j(document).ready(function()
              {    $j('table.basic img.photo').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>
          <?
    //  damp_array($quiz_results);
      }

    // шаблон одной стоки списка сессии МО
     //include_once(_DIR_EXT.'/aspmo_signature/class.DTW.php') ;
     //include_once(_DIR_TO_MODULES.'/signature/m_signature.php') ; - нет необходимости, все модули подключаются автоматиски
     function list_mo_sessions_tr($rec,$quiz_results,$options=array())
     {   if (!$quiz_results['cnt_questions']) $td_class='' ;
         else if ($quiz_results['cnt_questions']==$quiz_results['cnt_correct']) $td_class='bg_green' ;
         else if ($quiz_results['cnt_correct']==0) $td_class='bg_red' ;
         else if ($quiz_results['cnt_questions']!=$quiz_results['cnt_correct']) $td_class='bg_yellow' ;
         else $td_class='' ;
         ?><tr class=item id="mo_tr_<?echo $rec['pkey']?>">
                   <td><a class="new_window"  target="_blank" title="win_second" href="<?echo $rec['__href']?>"><?echo $rec['pkey']?></a><?if ($rec['personal_demo_access']){?><div class="demo_access" title="Сотрудник может проходить неограниченное число МО"></div><?}?></td>
                   <td><?echo $rec['_data']?><br><?echo $rec['_doctor_name']?></td>
                   <td><?echo $rec['group_name'].'<br>' ; echo ($rec['hand_check_user_id'])? '<img src="/images/doctor2.png" title="'.$rec['_hand_check_user_name'].'"><br>'.$rec['_hand_check_user_name']:$rec['terminal_name']?>
                       <?if ($rec['_term_cam_1'] or $rec['video'] or $rec['_use_in_trassir']){?>&nbsp;<span class="v2" cmd="media_server/get_video_from_terminal" id_mo="<?echo $rec['pkey']?>"><i class="fa fa-video-camera black"></i></span><?}?>
                   </td>
                   <td><?if ($rec['mo_id']){?><a class="new_window"  target="_blank" title="win_second" href="<?echo $rec['__href_mo']?>"><?echo $rec['mo_id']?></a><?}?></td>
                   <td class="name">
                   <?  $arr_info=array() ;
                       if ($rec['personal_id']) $arr_info[]='<a class="new_window" '.($rec['personal_danger_work']?'style="background-color:orange"':'').' target="_blank" title="win_second" href="'.$rec['__href'].'">'.$rec['personal_name'].'</a>' ;
                       if ($rec['_org_name']) $arr_info[]=$rec['_org_name'] ;
                       if ($rec['_otdel_name']) $arr_info[]=$rec['_otdel_name'] ;
                       if (MEMBER()->rol==1 and $rec['propusk']) $arr_info[]='Пропуск: '.$rec['propusk'] ;
                       if (_sizeof($arr_info)) echo implode('<br>',$arr_info) ;
                   ?>
                   </td>
                   <td class="photo"><div>
                       <div class="img"><? if ($rec['_personal_img']) { ?><img width=100 src="<?echo $rec['_personal_img']?>"><?}?></div>
                       <div class="img"><? if ($rec['_personal_img_auth']) {?><img width=100 src="<?echo $rec['_personal_img_auth']?>"><?}?></div>
                       <div class="clear"></div></div>
                   </td>
                   <td><?echo $rec['event_name']?></td>
                   <td class="left"><?if (_sizeof($quiz_results['themes'])) echo implode('<br>',$quiz_results['themes'])?></td>
                   <td class="result <?echo $td_class?>"><?if ($quiz_results['cnt_questions']){?><span class="result"><?echo $quiz_results['cnt_correct']?></span> ИЗ <span class="result"><?echo $quiz_results['cnt_questions']?></span><?}?></td>
                   <td class="comment"><?  if ($rec['status']==2) echo '<div class=ok>'.$rec['_status_name'].'</div>' ;
                                           echo $rec['_comment'];
                                           $rec['terminal_comment']=str_replace($rec['comment'],'',$rec['terminal_comment']) ;  // убираем дублирующиемся надписи, пока временно, так
                                           if ($rec['terminal_comment']) {?><div class="terminal_comment"><i class="fa fa-desktop" aria-hidden="true"></i> <?echo $rec['terminal_comment']?></div><?}
                                           // тут идет лишний запрос к БД, в записи $rec уже присутствуют все значения, которые выбираются в функции get_result_sign_verification
                                          // можно передавать сразу массив $rec: signature()->get_result_sign_verification($rec)
                                          // а в функции просто анализировать переданные значения
                                           //print_r($rec);
                                          //$res_DTW=signature()->get_result_sign_verification($rec) ;
                                          // если у человека есть подпись и МО пройден
                                          if ($rec['sign_id'] > 0 and ($rec['status']==2 or $rec['status']==3))
                                          { if ($rec['DTW_res']) echo '<div class="green">Подпись верна</div>';
                                            else                 echo '<div class="red">Подпись неверна</div>' ;
                                          }
                                          //if (stripos('intrusion',$rec['reason'])!==false) echo '<div class="red">Требуется подтверждение личности</div>' ;
                                       ?>
                       <?if ($rec['__dlit_mo']) echo '<br>'.$rec['__dlit_mo'].' c' ;?>
                       <?
                       // ищем в таблице выданных направлений участие в событии "выдача направлений по АГ" сотрудника с признаком "ag"  - участия во внедрении
                       if ($GLOBALS['_SETTING']['plugins']['esmo_intro'] and $rec['intro_level'] and $GLOBALS['LS_esmo_ag_event'])
                       {   $esmo_intro_rec=execSQL_van('select pkey,status from obj_site_events_pass where event_id='.$GLOBALS['LS_esmo_ag_event'].' and personal_id='.$rec['personal_id'].' and status<5 limit 1') ;
                       if (($esmo_intro_rec['pkey'] or $rec['personal_demo_access']) and $esmo_intro_rec['status']==1)
                       {?><br><form><input type="hidden" name="filter[obj_reffer]" value="<?echo $rec['_reffer']?>">
                                    <input type="hidden" name="filter[doc_code]" value="napravlenie">
                                    <input type="hidden" name="filter[mo_id]" value="<?echo $rec['pkey']?>">
                                    <input type="hidden" name="filter[report_seria]" value="<?echo htmlspecialchars(MEMBER()->cur_group_name)?>">
                                    <input type="hidden" name="filter[pdf_options]" value=" --copies 1">
                                    <button class="v2" cmd="docs/doc_create_in_window">Направление по АГ</button>
                              </form><?
                           } else if ($esmo_intro_rec['status']>1) echo '<br><i class="fa fa-info-circle"></i> Внедрение ЭСМО, этап '.$rec['intro_level'].'<br>';
                       }
                       ?>
                        <?

                       if (stripos('intrusion',$rec['reason'])!==false and $rec['status']==2 and !$rec['dopusk']) {
                          ?><br><br><button class="v2 button_red" cmd="aspmo_mo/hand_dopusk_clear" mo_id="<?echo $rec['pkey']?>">Аннулировать МО</button><?
                       }
                       ?>


                   </td>
               </tr>
         <?
     }


  // шаблон - вывод ссылками без разделитея
  function print_template_HTML_small($list_recs,$options=array())
  {  $options['id']='panel_last_mo' ;
     $options['base_dir']='' ;
     if (!isset($options['no_reverse_indx'])) $options['no_reverse_indx']=$this->filter['skoro'] ;
     $id=($options['id'])? 'id='.$options['id']:'' ;
     ?><div class=list_mo_sessions <?echo $id?>>
        <table>
        <colgroup><col id="c0"><col id="c1"><col id="c2"><col id="c22"><col id="c3"><col id="c_photo"><col id="c_result"><col id="c12"><col id="c13"></colgroup>
        <tr class="head"><th>№</th><th>Дата/время</th><th>Терминал</th><th>Тип<br>контроля</th><th>ФИО<br>сотрудника</th><th>Фото</th><th>Результат осмотра</th><th>Комментарий доктора</th><th>Допуск</th></tr><?
        $i=($options['no_reverse_indx'])? 1:_sizeof($list_recs) ;


        if (_sizeof($list_recs)) foreach($list_recs as $rec)
          {   $options['i']=$i ;
              ?><tr class=item id="mo_tr_<?echo $rec['pkey']?>">
                  <td><?echo $options['i'] ; ?><br><br><a class="new_window"  target="_blank" title="win_second" href="<?echo $rec['__href']?>"><?echo $rec['pkey']?></a><?if ($rec['personal_demo_access']){?><div class="demo_access" title="Сотрудник может проходить неограниченное число МО"></div><?}?></td>
                  <td><?echo $rec['_data']?><br><?echo $rec['_doctor_name']?></td>
                  <td><?echo $rec['group_name'].'<br>' ; echo ($rec['hand_check_user_id'])? '<img src="/images/doctor2.png" title="'.$rec['_hand_check_user_name'].'"><br>'.$rec['_hand_check_user_name']:$rec['terminal_name']?>

                      <?if ($rec['_term_cam_1'] or $rec['video']){?>&nbsp;<span class="v2" cmd="media_server/get_video_from_terminal" id_mo="<?echo $rec['pkey']?>"><i class="fa fa-video-camera"></i></span><?}?>
                  </td>
                  <td><?echo $rec['_tk_name']?><!--<br><?echo $rec['model']?>--><br><?echo $rec['_model_name']?></td>
                  <td class="name"><a class="new_window"  target="_blank" title="win_second" href="<?echo $rec['__href']?>"><?echo $rec['personal_name']?></a><br><?echo $rec['_otdel_name']?><? if (MEMBER()->rol==1) echo '<br>Пропуск: '.$rec['propusk']?></td>
                  <td class="photo"><div>
                      <div class="img"><? if ($rec['_personal_img']) { ?><img width=100 src="<?echo $rec['_personal_img']?>"><?}?></div>
                      <div class="img"><? if ($rec['_personal_img_auth']) {?><img width=100 src="<?echo $rec['_personal_img_auth']?>"><?}?></div>
                      <div class="clear"></div></div>
                  </td>
                  <td class="comment"><?  if ($rec['status']==2) echo '<div class=ok>'.$rec['_status_name'].'</div>' ;
                                          echo $rec['_comment'];
                                         if ($rec['sign_id'] > 0 and ($rec['status']==2 or $rec['status']==3))
                                         { if ($rec['DTW_res']) echo '<div class="green">Подпись верна</div>';
                                           else                 echo '<div class="red">Подпись неверна</div>' ;
  }
                                      ?>
                  </td>
                  <td>
                      <? if ($rec['doctor_comment'])  echo $rec['doctor_comment'] ; ?>
                  </td>
                  <td class="dopusk_<?echo $rec['dopusk']?><?if ($rec['tk']==1 and $GLOBALS['LS_alternative_color_for_postshift_medexam']) echo " tk_".$rec['tk']?>">
                      <? echo $rec['_dopusk_status'] ;
                         if ($rec['status']==2 and !$rec['dopusk']) {?><button class="v2 button_green" cmd="aspmo_mo/mo_dopusk_allow" mo_id="<?echo $rec['pkey']?>">Допустить</button><?}
                         if ($options['show_button_dopusk'] and ESMO()->get_allow_view_button_hand_check_in_mo_tr($rec)) {?><button class="v1" window="sec_win" href="/cab/rmv/hand_mo/<?echo $rec['personal_id']?>/">Ручная проверка</button><?}
                      ?>
                  </td>
              </tr>
        <?

              if ($options['no_reverse_indx']) $i++ ; else $i-- ;
          }


      ?></table><div id="panel_image_preview"></div></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>

      <?
  }


}
?>
