<?php
class report_magnit_scan extends c_report
{
 var $title='Сканы документов' ;
 var $view_by_space_filter=1 ;
 var $allow_org_ids=1 ;
 var $usl_select_org='' ;
 var $doc_types_names=array() ;
    var $allow_export_to_csv=1 ;
    var $arr_docs_codes=[] ;

 function setting($options=array())
 {
   //damp_array(ENGINE()->reports_list['napravlenie']['']) ;
   $arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;
   $usl=(_sizeof($arr_groups))? 'and t1.group_upload in ('.implode(',',array_keys($arr_groups)).')':'' ;
   $recs_accounts_upload=execSQL_row('select distinct(account_upload) as account_id,t2.obj_name as account_name
                                    from obj_site_scan t1
                                    left join obj_site_account t2 on t2.pkey=t1.account_upload
                                    where  account_upload>0  '.$usl.'
                                    order by account_name
                                   ') ;
   $recs_accounts_work=execSQL_row('select distinct(account_work) as account_id,t2.obj_name as account_name
                                    from obj_site_scan t1
                                    left join obj_site_account t2 on t2.pkey=t1.account_work
                                    where  account_work>0
                                    order by account_name
                                   ') ;
   $recs_source_email=execSQL_line('select distinct(source) as source_email from obj_site_scan t1 where source>"" order by source') ;

   $arr_events_select=[] ;
   $arr_docs_types_by_scan=execSQL_line('select distinct(report_code) from obj_site_scan where report_code!="" and not report_code is null',0,1) ;
   if (_sizeof($arr_docs_types_by_scan)) foreach($arr_docs_types_by_scan as $doc_type)
   { $doc_obj=ENGINE()->get_report_obj_by_code($doc_type) ;
     $arr_events_select[$doc_obj->report_code]=$doc_obj->title ;
     // собираем все всепдоними документа, чтобы при поиске документа по коду искатьвсе всевдонимы документа
     $this->arr_docs_codes[$doc_obj->report_code][$doc_type]=$doc_obj->title ;
   }
   $arr_docs_types_by_docs=execSQL_line('select distinct(_doc_report_code) from view_scan where _doc_report_code!=""',0,1) ;
   if (_sizeof($arr_docs_types_by_docs)) foreach($arr_docs_types_by_docs as $doc_type)
   { $doc_obj=ENGINE()->get_report_obj_by_code($doc_type) ;
     $arr_events_select[$doc_obj->report_code]=$doc_obj->title ;
     // собираем все всепдоними документа, чтобы при поиске документа по коду искатьвсе всевдонимы документа
     $this->arr_docs_codes[$doc_obj->report_code][$doc_type]=$doc_obj->title ;
   }

   //damp_array($this->arr_docs_codes,1,-1);

   /*if (_sizeof($arr_events)) foreach($arr_events as $event_code)
   {  $obj_event=EVENTS()->get_event_obj_by_ext($event_code) ;
      $arr_events_select[str_replace('/','.',$event_code)]=$obj_event->name ;
   }*/

   // проверка
   //damp_array($arr_events_select);
   /*if (sizeof($arr_events_select)) foreach($arr_events_select as $doc_code=>$doc_title)
    {
         ?><strong><?echo $doc_code?></strong><?
              $doc_obj=ENGINE()->get_report_obj_by_code($doc_code) ;
              damp_array($doc_obj,1,-1) ; echo '<br>' ;
   }
   */

      ?><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) ;?>
                          <?if (MEMBER()->rol!=12)
                          {?> <section class="col col-2">
                                  <label class="label">Фельдшер:</label>
                                  <label class="select">
                                      <select id=doctor_id name="filter[doctor_id]"><option value="0">Все</option>
                                          <? $members=ACCOUNTS()->get_list_members() ;
                                             if (_sizeof($members))foreach($members as $rec_member) if ($rec_member['rol']==2 or $rec_member['rol']==3)
                                            {?><option value="<?echo $rec_member['pkey']?>" <?if ($this->filter['doctor_id']==$rec_member['pkey']) echo 'selected'?>><?echo $rec_member['_rol_name'].' '.$rec_member['obj_name']?></option><?}
                                          ?>
                                      </select><i></i>
                                  </label>
                              </section><?
                          }?>
                          <section class="col col-2">
                              <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-2">
                              <label class="label">Дата приема скана, до:</label>
                              <label class="input"><input type="text" name="filter[data_to]" class="datepicker" value="<?echo $this->filter['data_to']?>"></label>
                          </section>
                        <section class="col col-2">
                             <label class="label">Статус:</label>
                             <label class="select">
                                 <select name="filter[status]"><option></option><?
                                     if (_sizeof($_SESSION['ARR_status_scan'])) foreach($_SESSION['ARR_status_scan'] as $id=>$name) if ($id!=1) {?><option value="<?echo $id?>" <?if ($id==$this->filter['status']) echo 'selected'?>><?echo $name?></option><?} ?>
                                 </select><i></i>
                             </label>
                           </section>
                        <section class="col col-2">
                             <label class="label">Документ:</label>
                             <label class="checkbox">
                                 <label><input type="checkbox" name="filter[doc_mode]" value="non_doc" <?if ($this->filter['doc_mode']=='non_doc') echo 'checked'?>><i></i> Принят без документа</label>
                             </label>
                             <label class="checkbox">
                                 <label><input type="checkbox" name="filter[doc_mode]" value="no_doc_date" <?if ($this->filter['doc_mode']=='no_doc_date') echo 'checked'?>><i></i> Без даты документа</label>
                             </label>
                           </section>
                          <!--<section class="col col-1">
                              <label class="label">Номер НАГ</label>
                              <label class="input">
                                  <input type="text" name="filter[doc_number]" placeholder="" value="<?echo $this->filter['doc_number']?>">
                              </label>
                          </section>-->
                          </div>
                          <div class="row">
                          <section class="col col-2">
                             <label class="label">Загрузка (оператор)</label>
                             <label class="select">
                              <select name="filter[account_upload]"><option></option><?
                                  if (_sizeof($recs_accounts_upload)) foreach($recs_accounts_upload as $id=>$name) {?><option value="<?echo $id?>" <?if ($id==$this->filter['account_upload']) echo 'selected'?>><?echo $name?></option><?} ?>
                              </select><i></i>
                             </label>
                           </section>
                          <section class="col col-2">
                             <label class="label">Загрузка (email)</label>
                             <label class="select">
                              <select name="filter[email_upload]"><option></option><?
                                  if (_sizeof($recs_source_email)) foreach($recs_source_email as $name) {?><option value="<?echo $name?>" <?if ($name==$this->filter['email_upload']) echo 'selected'?>><?echo $name?></option><?} ?>
                              </select><i></i>
                              </label>
                           </section>
                          <section class="col col-2">
                             <label class="label">Обработка (оператор)</label>
                             <label class="select">
                              <select name="filter[account_work]"><option></option><?
                                  if (_sizeof($recs_accounts_work)) foreach($recs_accounts_work as $id=>$name) {?><option value="<?echo $id?>" <?if ($id==$this->filter['account_work']) echo 'selected'?>><?echo $name?></option><?} ?>
                              </select><i></i>
                             </label>
                           </section>
                          <section class="col col-2">
                              <label class="label">ФИО сотрудника</label>
                              <label class="input">
                                  <input type="text" name="filter[personal_name]" placeholder="" SetAutoComplete cmd="autocomplette_personal_name" value="<?echo $this->filter['personal_name']?>">
                              </label>
                          </section>
                          <? $this->filter_section_select('group_upload_id',$GLOBALS['LS_person_group_title'].' выдачи:',2,$arr_groups) ;?>
                          <? $this->filter_section_select('report_code','Тип документа:',2,$arr_events_select) ;?>

                        </div>
                  </fieldset>
                  <?$this->panel_buttons();?>
              </form>
       </div><br>
     <?
  }

  function create_usl_select_obj($_params,&$options)
  {  //damp_array($this->filter) ;
     $usl=array() ;
     $usl[]='clss=218' ;
     $usl[]='parent=1' ;
     //$usl[]='status!=1' ; // не включать, иначе АТП не видят загруженные имя сканы
     if (MEMBER()->rol==12) $usl[]='(group_upload in ('.MEMBER()->cur_groups_visible.') or account_upload='.MEMBER()->id.')' ;
     if (MEMBER()->rol==14) $usl[]='(group_upload in ('.MEMBER()->cur_groups_visible.') or account_upload='.MEMBER()->id.')' ;
     if ($this->filter['account_upload'])        $usl[]='account_upload='.$this->filter['account_upload'] ;
     if ($this->filter['account_work'])        $usl[]='account_work='.$this->filter['account_work'] ;
     if ($this->filter['email_upload'])        $usl[]='source like "'.$this->filter['email_upload'].'%"' ;
     if ($this->filter['group_id'])        $usl[]='group_upload='.$this->filter['group_id'] ;
     if ($this->filter['group_upload_id'])        $usl[]='_doc_group_id='.$this->filter['group_upload_id'] ;
     if ($this->filter['personal_id'])        $usl[]='personal_id='.$this->filter['personal_id'] ;
     if ($this->filter['doc_type'])           $usl[]='report_code="'.$this->filter['doc_type'].'"' ;
     if ($this->filter['doc_number'])           $usl[]='indx="'.$this->filter['doc_number'].'"' ;
     if ($this->filter['status'])           $usl[]='status="'.$this->filter['status'].'"' ;
     if ($this->filter['is_sign']==1)           $usl[]='sign_member>0' ;
     if ($this->filter['is_sign']==2)           $usl[]='sign_member=0' ;
     if ($this->filter['doc_mode']=='non_doc')           $usl[]='doc_id=-1' ;
     if ($this->filter['doc_mode']=='no_doc_date')           $usl[]='(data_doc=0 or data_doc is null)' ;
     if ($this->filter['report_code'])
     {  $arr_docs=[] ;
        $arr_docs[]='report_code="'.$this->filter['report_code'].'"' ;
        $arr_docs[]='_doc_report_code="'.$this->filter['report_code'].'"' ;
        if (sizeof($this->arr_docs_codes[$this->filter['report_code']])) foreach($this->arr_docs_codes[$this->filter['report_code']] as $doc_code=>$doc_title) if ($doc_code!=$this->filter['report_code'])
        {
          $arr_docs[]='report_code="'.$doc_code.'"' ;
          $arr_docs[]='_doc_report_code="'.$doc_code.'"' ;
        }
        $usl[]='('.implode(' or ',$arr_docs).')' ;
     }
     //if ($this->filter['events_type']=='esmo_magnit_pmo.i_event_pmo')           $usl[]='_doc_name like "Заключение пери%"' ;
     //if ($this->filter['events_type']=='events_docs.i_event_docs')           $usl[]='_doc_name like "Направление%"' ;
     //if ($this->filter['events_type']=='events_opo.i_event_opo')           $usl[]='source_obj="events_opo/i_event_opo"' ;
     //if
     $personal_id=(int)$this->filter['personal_name'] ;
     if ($personal_id)           $usl[]='personal_id='.$personal_id ;
     elseif ($this->filter['personal_name'])           $usl[]='_personal_name like "'.$this->filter['personal_name'].'%"' ;
     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']) ;
     $usl_res=implode(' and ',$usl) ;
     //damp_array($usl) ;
     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['group_upload_id'])        $info['Группа выдачи']=ACCOUNTS()->get_member_name_by_id($this->filter['group_upload_id']) ;
   if ($this->filter['personal_id'])     $info['Сотрудник']=PERSONAL()->get_name_by_id($this->filter['personal_id']) ;
   if ($this->filter['email_upload'])     $info['Скан загружен c']=$this->filter['email_upload'] ;
   if ($this->filter['account_upload'])     $info['Скан загружен']=PERSONAL()->get_name_by_id($this->filter['account_upload']) ;
   if ($this->filter['account_work'])     $info['Скан обработан']=PERSONAL()->get_name_by_id($this->filter['account_work']) ;
   if ($this->filter['doc_type'])                       $info['Тип документа']=$this->doc_types_names[$this->filter['doc_type']] ;
   if ($this->filter['doc_number'])                       $info['№']=$this->filter['doc_number'] ;
   if ($this->filter['status'])                       $info['Статус']=$_SESSION['ARR_status_scan'][$this->filter['status']] ;

   if ($this->filter['is_sign']==1)           $info['Подпись']='Есть' ;
   if ($this->filter['is_sign']==2)          $info['Подпись']='Нет' ;
   if ($this->filter['doc_mode']=='non_doc')   $info['Принят без документа']='Да' ;
   if ($this->filter['doc_mode']=='no_doc_date')   $info['Принят без даты документа']='Да' ;
   if ($this->filter['events_type'])
   {   $event_code=str_replace('.','/',$this->filter['events_type']);
       $obj_event=EVENTS()->get_event_obj_by_ext($event_code) ;
       $info['Тип мероприятия']=$obj_event->name;
   }
   $personal_id=(int)$this->filter['personal_name'] ;
   if ($personal_id)          $info['ID сотрудника']=$personal_id ;
   elseif ($this->filter['personal_name'])          $info['ФИО сотрудника']=$this->filter['personal_name'] ;
   if ($this->filter['data_from'])                     $info['дата от']='"'.$this->filter['data_from'].'"' ;
   if ($this->filter['data_to'])                     $info['дата до']='"'.$this->filter['data_to'].'"' ;
   if (_sizeof($info)) foreach($info as $title=>$value) $_str[]=$title.': <strong>'.$value.'</strong>' ;
   if (_sizeof($_str)) $title='<p class=center>'.implode(' ',$_str).'</p>' ;
   return $title ;
 }

  function get_cnt_items($usl,$options=array())
  { $cnt=execSQL_value('select count(pkey)
                        from  view_scan
                        where '.$usl,$options) ;
    return($cnt) ;
  }

  function get_items($usl,$options=array())
  { $limit=($options['limit'])? ' '.$options['limit']:'' ;
    //$order=($this->filter['order'])? ' order by '.$this->filter['order']:' order by pkey desc' ;
    //$options['debug']=2 ;
    $order=($options['order'])? ' order by '.$options['order']:' order by pkey desc' ;
 	$list_rec=execSQL('select * from  view_scan where '.$usl.$order.$limit,$options) ;
    if (_sizeof($list_rec)) foreach($list_rec as $id=>$rec) DOCS()->prepare_public_info_to_scan($list_rec[$id],$options) ;
    return($list_rec) ;
  }


// шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  { $id=($options['id'])? 'id='.$options['id']:'' ;
    $recs_account=execSQL_row('select pkey,obj_name from obj_site_account where clss=210') ;
    ?><table class="basic fz_small full auto"<?echo $id?>>
        <tr><th>№</th><th>Дата/время<br>загрузки</th><th>АТП загрузки</th><th>Источник</th><th>Дата/время<br>обработки</th><th>Обработан</th><th>Длительность ожидания</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['code']) $rec['code']='PDF' ; // для совместимости с документами прежней версии
              ?><tr>
                  <td><?echo $rec['pkey']?></td>
                  <td><?echo date('d.m.Y H:i',$rec['c_data'])?><??></td>
                  <td><?echo $rec['_group_upload_name']?><??></td>
                  <td class="left"><?echo $rec['_source']?><??></td>
                  <td><?if ($rec['data_work']) echo date('d.m.Y H:i',$rec['data_work'])?></td>
                  <td><?echo $rec['_account_work_name']?></td>
                  <td><?if ($rec['data_work'])  echo ENGINE()->get_text_time_diff($rec['c_data'],$rec['data_work']) ?></td>
                  <td><?if ($rec['data_set'])  echo ENGINE()->get_text_time_diff($rec['data_work'],$rec['data_set'])?></td>
                  <td><span class="nowrap"><a href="<?echo $rec['__href']?>" class="new_window" target="_blank" title="window_scan">Открыть скан</a></span></td>
                  <td class="color: <?if ($rec['status']==3) echo 'green'; if ($rec['status']==4) echo 'red';?>"><?echo $_SESSION['ARR_status_scan'][$rec['status']]?></td>
                  <td><?
                    if ($rec['doc_id']>0) echo '<a href="'.$rec['__doc_href'].'" class="new_window" target="_blank" title="window_doc">'.$rec['_doc_name'].'</a>';
                       else if($rec['report_code'])
                       { $doc_obj=ENGINE()->get_report_obj_by_code($rec['report_code']) ;
                         if (is_object($doc_obj)) echo $doc_obj->title ;
                         else echo $rec['report_code'] ;
					   }
                       // старая старая схема, когда по типу мероприятиия определялся тип документа
                       else switch($rec['source_obj'])
                       {  case 'events_docs/i_event_docs' : echo 'Направление по АГ' ; break ;
                          case 'esmo_magnit_pmo/i_event_pmo': echo 'Заключение ПМО' ; break ;
                       }
                      ?></td>
                  <td><?echo $rec['_doc_group_name']?></td>
                  <td><?if ($rec['_personal_id']) echo '<a href="'.$rec['__personal_href'].'" class="new_window" target="_blank" title="window_doc">'.$rec['_personal_name'].'</a>'?></td>
                  <td><?echo $rec['diagnoz']?></td>
                  <td><div class="comment"><?echo $rec['comment']?></div></td>

              </tr><?
          }
      ?></table><?
      //damp_array($rec) ;
  }

  function print_template_HTML_small($list_recs,$options=array())
  { $id=($options['id'])? 'id='.$options['id']:'' ;
    $recs_account=execSQL_row('select pkey,obj_name from obj_site_account where clss=210') ;
    ?><table class="basic fz_small full auto"<?echo $id?>>
        <tr><th>№</th><th>Дата/время<br>принятия скана</th><th>АТП загрузки</th><th>Источник</th><th>Дата/время<br>обработки</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['code']) $rec['code']='PDF' ; // для совместимости с документами прежней версии
              ?><tr>
                  <td><?echo $rec['pkey']?></td>
                  <td><?echo date('d.m.Y H:i',$rec['data_set'])?><??></td>
                  <td><?echo $rec['_group_upload_name']?><??></td>
                  <td class="left"><?echo $rec['_source']?><??></td>
                  <td><?if ($rec['data_work']) echo date('d.m.Y H:i',$rec['data_work'])?></td>
                  <td><?echo $rec['_account_work_name']?></td>
                  <td class="left"><span class="nowrap"><a href="<?echo $rec['__href']?>" class="new_window" target="_blank" title="window_scan">Открыть скан</a></span></td>
                  <td class="color: <?if ($rec['status']==3) echo 'green'; if ($rec['status']==4) echo 'red';?>"><?echo $_SESSION['ARR_status_scan'][$rec['status']]?></td>
                  <td><?if ($rec['doc_id']>0) echo '<a href="'.$rec['__doc_href'].'" class="new_window" target="_blank" title="window_doc">'.$rec['_doc_name']?></a></td>
                  <td><?echo $rec['_doc_group_name']?></td>
                  <td><?echo $rec['diagnoz']?></td>
                  <td><div class="comment"><?echo $rec['comment']?></div></td>

              </tr><?
          }
      ?></table><?
      //damp_array($rec) ;
  }

  function print_template_CSV($list_recs,$options=array())
   { $i=$options['from'] ;
     if (_sizeof($list_recs)) foreach($list_recs as $rec)
       { $data=array() ;
         $data['id']=$rec['pkey'] ;
         $data['Дата/время']=date('d.m.Y H:i:s',$rec['c_data']) ;
         $data['АТП загрузки']=$rec['_group_upload_name'] ;
         $data['Источник']=strip_tags($rec['_source']) ;
         $data['Дата/время обработки']=($rec['data_work'])? date('d.m.Y H:i:s',$rec['data_work']):'' ;
         $data['Обработан']=$rec['_account_work_name'] ;
         $data['Длительность ожидания']=($rec['data_work'])? ENGINE()->get_text_time_diff($rec['c_data'],$rec['data_work']):'' ;
         $data['Длительность обработки']=($rec['data_set'])? ENGINE()->get_text_time_diff($rec['data_work'],$rec['data_set']):'' ;
         $data['Статус']=$_SESSION['ARR_status_scan'][$rec['status']] ;
         $data['Наименование документа']=$rec['_doc_name'] ;
         $data['АТП выдачи']=$rec['_doc_group_name'] ;
         $data['Сотрудник']=$rec['_personal_name'];
         $data['Диагноз']=$rec['diagnoz'] ;
         $data['Комментарий']=$rec['comment'] ;

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

   }

}

?>
