<?php
include_once(_DIR_TO_CLASS."/c_page.php");
class c_page_cab_scan_working extends c_page
{
  public $h1='Обработка скана документа' ;
  public $scan_id=array() ;
  public $rec_personal=array() ;
  public $rec_scan=array() ;
  public $rec_doc=array() ;
  public $valid_image_format=0 ;
  public $count_pages=0 ;
  public $read_only=0 ;
  // !!! временное решение
  public $arr_doc_types=array('events_docs/i_event_docs'=>'Направление по АГ','esmo_magnit_pmo/i_event_pmo'=>'Заключение ПМО') ;
  public $arr_doc_types_register=[];
  public $no_change_personal_id=0;
  public $edit_mode=0;
  public $close_page_after_scan_apply=1;

  function set_head_tags()
  {   parent::set_head_tags() ;
      $this->HEAD['css'][]='/'._CLASS_.'/ext/scan/style.css' ; //
  }

 function upload_scan_rec()
 {
   if ($this->scan_id) $this->rec_scan=DOCS()->get_scan_by_id($this->scan_id) ;
   elseif (_CUR_ID) $this->rec_scan=DOCS()->get_scan_by_id(_CUR_ID) ;
   if ($this->rec_scan['status']==6)
   { DOCS()->scan_update($this->rec_scan['pkey'],['status'=>2]) ;
     $this->rec_scan['status']=2 ;
   }
   return($this->rec_scan['pkey']!=0) ;
 }

 function select_obj_info()
 { //damp_array($this->filter,1,-1) ;
   if ($this->upload_scan_rec())
     {  //if ($this->rec_scan['parent']!=1 and $this->rec_scan['status']==5) $this->rec_scan['status']=6 ;


        if ($this->rec_scan['personal_id']) $this->rec_personal=PERSONAL()->get_personal_by_id($this->rec_scan['personal_id']) ;
        if (!$this->rec_personal['pkey']) $this->rec_scan['personal_id']=0 ; // если в скане указан несуществующий сотрудник
        if ($this->rec_scan['doc_id']>0)    $this->rec_doc=DOCS()->get_doc_by_id($this->rec_scan['doc_id']) ;

        // проверяем не пакет ли это и общее число страниц в пакете
        if ($this->rec_scan['parent']==1) $this->count_pages=execSQL_value('select count(pkey) from obj_site_scan where parent='.$this->rec_scan['pkey'])+1 ;
        else                              $this->count_pages=execSQL_value('select count(pkey) from obj_site_scan where parent='.$this->rec_scan['parent'])+1 ;
        if ($this->count_pages>1) $this->h1.=', страница '.$this->rec_scan['indx'].' из '.$this->count_pages ;

        // проверяем что файл - изображение
        if (file_exists(_DIR_TO_ROOT.$this->rec_scan['obj_name']))
        { $fsize=filesize(_DIR_TO_ROOT.$this->rec_scan['obj_name']) ;
          $this->rec_scan['_file_size']=$fsize ;
          if ($fsize>100) // jpeg не может быть менее 100 байт
        { $images = new Imagick();
          $images->readImage(_DIR_TO_ROOT.$this->rec_scan['obj_name']);
          $mime=$images->getImageMimeType() ;
          if ($mime=='image/jpeg') $this->valid_image_format=1 ;
        } else $this->valid_image_format=0 ;
        } else $this->valid_image_format=0 ;

        //// если изображение корректно и
        //if ($this->valid_image_format and !$this->rec_personal)

//        $this->read_only=(MEMBER()->rol==1)? 0:1 ;
     }
   else $this->result=404 ;
   $this->arr_doc_types_register=execSQL_row('select code,obj_name from reports where type=2 order by obj_name') ;
 }


 function menu_config()
 { // вкладки для сотрудника
   if ($this->rec_scan['pkey'])
      { $this->menu[$this->rec_scan['__href']]='Обработка' ;
        $this->menu[$this->rec_scan['__href'].'log/']='История' ;
        $this->menu[$this->rec_scan['__href'].'db/']='Исходные данные' ;
        $this->page_type='window' ;
      }
   else parent::menu_config() ;
 }

 // статусы скана
 // 1 - новый
 // 2 - в работе
 // 3 - принят

 // скан может быть доступен только для чтения всем
 // для оператора что загрузил или администрата - доступно редактирования
 function block_main()
 { $this->page_title() ;
   $this->edit_mode=($this->rec_scan['status']==2 and ($this->rec_scan['account_work']==MEMBER()->id or MEMBER()->rol==1))? 1:0 ;
   //damp_array($this->rec_scan);
   //echo 'qrcode='.$this->rec_scan['qrcode'].'<br>' ;
   ?><table class="work_area">
           <tr>
             <td class="tdcol"><?if ($this->valid_image_format) $this->panel_img() ;
                               else $this->panel_alert_not_valid_img() ;
                              ?>
             </td>
             <td class="tdcol">
                 <div id="panel_scan_info">
                     <?  //  панели информации по скану
                         $this->panel_scan_info_view() ;

                         // если qrcode=0 - значит он еще не распозновался. Там должно быть значение, или -1 если не удалось распознать
                         if (!$this->rec_scan['qrcode']) $this->panel_JS_capture_QR_code() ;
                         // только в режиме редактирования
                         if ($this->edit_mode)
			    {
				?><button class="button v2" cmd="scan/ScanCaptureCancel"  scan_id="<?echo $this->rec_scan['pkey']?>">Отклонить</button><?
				?><button class="button v2" cmd="scan/ScanCaptureRepeat"  scan_id="<?echo $this->rec_scan['pkey']?>" no_change_personal_id="<?echo $this->no_change_personal_id?>">Распознать QR-код повторно</button><?
			    }
                         // только в режиме редактирования и только при нераспозном/отстутствии QR-кода
                         if ($this->edit_mode and $this->rec_scan['qrcode']==-1)
                         {
                             // если QR код не распознан, но сотрудник был задан вручную - показываем кнопку "Сбросить сотрудника"
                             // эта панель не будет показываться на обработке скана на странице сотрудника
                             if ($this->rec_scan['personal_id'] and !$this->rec_scan['doc_id'] and !$this->no_change_personal_id) {?><button class="button v2" cmd="scan/scan_personal_clear" scan_id="<?echo $this->rec_scan['pkey']?>">Сбросить сотрудника</button><?}
                             if ($this->rec_scan['personal_id'] and $this->rec_scan['doc_id'] and !$this->no_change_personal_id) {?><button class="button v2" cmd="scan/scan_personal_clear" scan_id="<?echo $this->rec_scan['pkey']?>" doc_id="<?echo $this->rec_scan['doc_id']?>">Сбросить сотрудника/документ</button><?}
                             // карточка сотрудника, определен сотрудник скана и определен документ - кнопка "Сбросить документ", сбрасывать сотрудника нельзя
                             if ($this->rec_scan['personal_id'] and $this->rec_scan['doc_id'] and $this->no_change_personal_id) {?><button class="button v2" cmd="scan/scan_doc_clear" scan_id="<?echo $this->rec_scan['pkey']?>">Сбросить документ</button><?}
                             // документ не определен, тип документа задан - кнопка "Сбросить документ"
                             if (!$this->rec_scan['doc_id'] and $this->rec_scan['doc_type']) {?><button class="button v2" cmd="scan/scan_doc_clear" scan_id="<?echo $this->rec_scan['pkey']?>">Сбросить документ</button><?}
                         }
                         ?><div class="clear"></div><?


                         // информация по сотруднику
                         if ($this->rec_personal['pkey'])
                         {   $this->panel_card_personal_view() ;
                             $this->panel_cur_group_medic_view() ;
                         }

                         if ($this->edit_mode and (!$this->rec_scan['personal_id'] or !$this->rec_scan['doc_type'])) $this->panel_search_personals() ; // панель поиска по сотруднику + тип документа

                         // информация по скану/документу скана
                         $this->panel_card_doc_view() ;

                         if ($this->edit_mode) $this->panel_scan_edit() ;
                         else                  $this->panel_scan_view() ;

                     ?>
                 </div>
             </td>
           </tr>
     </table>
   <?
/*     echo 'status='.$this->rec_scan['status'].'<br>' ;
                              echo 'error='.$this->rec_scan['error'].'<br>' ;
                              echo 'qrcode='.$this->rec_scan['qrcode'].'<br>' ;
                              echo 'personal_id='.$this->rec_scan['personal_id'].'<br>' ;
                              echo 'doc_id='.$this->rec_scan['doc_id'].'<br>' ;
                              //echo 'qrcode='.$this->rec_scan['qrcode'].'<br>'

     damp_array($this->rec_scan,1,-1);
     //     execSQL('select * from reports where type=2 order by obj_name',2) ;
     $rec_doc=DOCS()->get_doc_by_id($this->rec_scan['doc_id']) ;
     damp_array($rec_doc);
*/
}

 function panel_scan_edit()
 {   // если сотрудик сопоставен и нет ошибки по скану - показываем информацию по медгруппам сотрудника
     if ($this->rec_personal['pkey'])
     {
         if (($this->rec_scan['status']==3 or $this->rec_scan['status']==4) and $this->rec_scan['diagnoz'])  $this->panel_view_diagnoz() ;
     }

     // если скан не содержит QR-кода - показываем панель выбора типа документа вручную
     //if ($this->rec_scan['qrcode']==-1) $this->panel_select_doc_type() ;

     // если задано мероприятие скана или документа - используем панель приема скана от этого мероприятия
     if ($this->rec_scan['doc_type'] and $this->rec_scan['personal_id'])
     {?><h2>Принятие скана документа</h2><?
         $options=['scan_id'=>$this->rec_scan['pkey'],
                   'personal_id'=>$this->rec_personal['pkey'],
                   'close_page_after_scan_apply'=>$this->close_page_after_scan_apply
              ];
     if ($this->rec_doc['source_obj']) ENGINE()->on_event_obj($this->rec_doc,'on_scan_doc_OCR',$options) ;
     elseif ($this->rec_scan['source_obj']) ENGINE()->on_event_obj($this->rec_scan,'on_scan_doc_OCR',$options) ;
     // иначе - используем стандартую панель приема скана
     else $this->scan_doc_OCR_default() ;
     }
     //else $this->panel_set_diagnoz() ;


 }


 function panel_scan_view()
 { // диагноз
   if ($this->rec_scan['diagnoz'])  $this->panel_view_diagnoz() ;
   // комментарий к диагнозу
   if ($this->rec_scan['data_doc'])  $this->panel_view_data_doc() ;
   // комментарий к диагнозу
   if ($this->rec_scan['comment'])  $this->panel_view_comment() ;
   // решение по МО
   if ($this->rec_scan['status']!=4 and $this->rec_scan['after_block_mo']) $this->panel_view_after_block_mo() ;



  if (($this->rec_scan['status']==3 or $this->rec_scan['status']==4) and ($this->rec_scan['account_work']==MEMBER()->id or MEMBER()->rol==1))
   {?><button class="button v2" cmd="scan/ScanToEditMode"  scan_id="<?echo $this->rec_scan['pkey']?>">Редактировать скан</button>&nbsp;&nbsp;<?}
 }

 function panel_old()
 { ?><table class="work_area">
           <tr>
             <td class="tdcol"><?if ($this->valid_image_format) $this->panel_img() ;
                               else $this->panel_alert_not_valid_img() ;
                              ?>
             </td>
             <td class="tdcol"><div id="panel_scan_info">
                 <? $this->panel_scan_info_view() ;
                    echo 'status='.$this->rec_scan['status'].'<br>' ;

                    if ($this->valid_image_format and $this->rec_scan['status']==6)
                    { $this->panel_JS_capture_QR_code() ;
                      $this->panel_scan_capture_repeat() ;
                      $this->panel_search_personals() ;
                    }

                     if ($this->rec_personal['pkey'])
                     {
                         $this->panel_card_personal_view() ;
                         $this->panel_cur_group_medic_view() ;
                     }
                     if ($this->rec_doc['pkey']) $this->panel_card_doc_view() ;
                     else $this->panel_card_scan_source_view() ;

                     // все действия со сканом - только после связи скана с сотрудником
                     if ($this->rec_personal['pkey'])
                     { $this->panel_cur_group_medic_view() ;
                       //if ($this->rec_scan['status']==3 or $this->rec_scan['status']==4 or $this->rec_scan['diagnoz'] or $this->rec_scan['comment'])  $this->panel_view_diagnoz() ;
                       if ($this->rec_scan['diagnoz'])  $this->panel_view_diagnoz() ;
                       if ($this->rec_scan['comment'])  $this->panel_view_comment() ;

                       // режим обработки скана

                       if ($this->rec_scan['status']==2 and $this->rec_scan['account_work']==MEMBER()->id)
                       { // если указан объект связанный с данным сообщением - дергаем его
                         //damp_array($this->rec_doc) ;

                         // в докуменах попадаются документы, не связанные с мероприятием
                         if (function_exists('EVENTS'))
                         {   if ($this->rec_doc['pkey']) $rec_event_pass=execSQL_van('select * from obj_site_events_pass where doc_id='.$this->rec_doc['pkey']) ; else $rec_event_pass=array() ;
                             if ($rec_event_pass['pkey'])
                             { $rec_event=EVENTS()->get_event_by_id($rec_event_pass['event_id']);
                               if ($rec_event['ext']) update_rec_in_table('obj_site_docs',array('source_obj'=>$rec_event['ext'],
                                                                                                'source_pkey'=>$rec_event_pass['pkey'],
                                                                                                'source_tkey'=>$rec_event_pass['tkey']
                                                                                                ),'pkey='.$this->rec_doc['pkey']) ;
                               $this->rec_doc=DOCS()->get_doc_by_id($this->rec_doc['pkey']) ;
                             }
                         }

                         // если скан не содержит QR-кода - показываем панель выбора типа документа вручную
                         //if (!$this->rec_doc['qrcode']) $this->panel_select_doc_type() ;

                         // если задано мероприятие скана или документа - используем панель приема скана от этого мероприятия
                         if ($this->rec_doc['source_obj']) ENGINE()->on_event_obj($this->rec_doc,'on_scan_doc_OCR',array('scan_id'=>$this->rec_scan['pkey'],'personal_id'=>$this->rec_personal['pkey'],'ext'=>'scan','no_button_clear_personal'=>1)) ;
                         elseif ($this->rec_scan['source_obj']) ENGINE()->on_event_obj($this->rec_scan,'on_scan_doc_OCR',array('scan_id'=>$this->rec_scan['pkey'],'personal_id'=>$this->rec_personal['pkey'],'ext'=>'scan','no_button_clear_personal'=>1)) ;
                         // иначе - используем стандартую панель приема скана
                         else if ($this->rec_scan['doc_type']) $this->scan_doc_OCR_default() ;
                         //else $this->panel_set_diagnoz() ;
                       }
                     }

                     if ($this->rec_scan['account_work']==MEMBER()->id or MEMBER()->rol==1)
                     {
                         // echo $this->rec_scan['personal_id'] ;
                         // 3=>'Принят', 4=>'Отклонен',
                         //if ($this->rec_scan['status']==3 or $this->rec_scan['status']==4) $this->panel_change_diagnoz_button() ;
                         if ($this->rec_scan['diagnoz']) $this->panel_change_diagnoz_button() ;
                       // если не удалось распознать qr-код (doc_id=-1) и не определен сотрудник (personal_id=0) и нормальный формат изображения - показываем кнопку "распознать еще раз"
                       //if (
                       //        ($this->rec_scan['doc_id']==-1 and !$this->rec_scan['personal_id'])
                       //    or  (!$this->rec_scan['personal_id'] and $this->rec_scan['parent']!=1)
                       //
                       //    /* and $this->valid_image_format*/) $this->panel_scan_capture_repeat() ;

                         if (!$this->rec_scan['personal_id']/* and $this->rec_scan['parent']!=1*/) $this->panel_scan_capture_repeat() ;
                     }
                     /*elseif (MEMBER()->rol==1 and $this->rec_scan['personal_id']) {?><button class="button v2" cmd="esmo_magnit/ScanCaptureRepeat"  scan_id="<?echo $this->rec_scan['pkey']?>" url_page="<?echo _CUR_REPORT_DIR?>">Распознать повторно</button><?}*/


                     // если документ не распознан
                     if (/*$this->rec_scan['account_work']==MEMBER()->id and */!$this->rec_scan['personal_id'] and $this->valid_image_format and $this->rec_scan['status']!=6 and !$this->read_only)
                         $this->panel_search_personals() ;

                     if ($this->rec_scan['status']==3 and ($this->rec_scan['account_work']==MEMBER()->id or MEMBER()->rol==1))
                     {?><button class="button v2" cmd="scan/ScanToEditMode"  scan_id="<?echo $this->rec_scan['pkey']?>">Редактировать скан</button>&nbsp;&nbsp;<?}

                 ?>
                 </div>
             </td>
           </tr>
       </table>
     <?
     //$this->panel_scan_debug_info() ;
     ?>
       <style type="text/css">

       </style>
     <?

   ?><br><br>
     <script type="text/javascript">
         window.opener.location.reload() ;  // перегружаем основное окно после каждого обновления дочернего окна
     </script>

     <?


 }

function scan_doc_OCR_default()
{   ?><div id="panel_set_diagnoz"><?
    $form=new i_form() ;
    $form->form_open() ;
    $form->fieldset_open();
    $form->row_open() ;
    $data_doc=($this->rec_scan['data_doc'])? date('d.m.Y',$this->rec_scan['data_doc']):'' ;
    $form->filter_section_input_text('data_doc','Дата документа',4,['cur_value'=>$data_doc,'class'=>'datepicker','required'=>1,'data-mask'=>"00.00.0000",'placeholder'=>'дд.мм.ггггг']) ;
    $form->row_close() ;
    $form->row_open() ;
    $form->filter_section_textarea('comment','Ваш комментарий к скану',11,['cur_value'=>$this->rec_scan['comment']]) ;
    $form->row_close() ;
    ?><h3>После обработки документа:</h3><br>
     <div>
         <section class="col col-6">
             <label class="radio"><input type="radio" name="action_after" value="1" <?if ($this->rec_scan['after_block_mo']!=2) echo 'checked'?>><i></i> Прохождение МО разрешено</label>
         </section>
         <section class="col col-6">
             <label class="radio"><input type="radio" name="action_after" value="2" <?if ($this->rec_scan['after_block_mo']==2) echo 'checked'?>><i></i> Прохождение МО запрещено</label>
         </section>
     </div><?
    $form->button('Принять','scan/ScanCaptureApply',['scan_id'=>$this->rec_scan['pkey'],'close_page_after_scan_apply'=>$this->close_page_after_scan_apply]);
    $form->button('Отклонить','scan/ScanCaptureCancel',['scan_id'=>$this->rec_scan['pkey'],'close_page_after_scan_apply'=>$this->close_page_after_scan_apply]);
    //$form->button('Сбросить сотрудника','scan/ScanPersonClear',['scan_id'=>$this->rec_scan['pkey'],'after'=>'update_page']);
    $form->fieldset_close();
    $form->form_close() ;
    ?></div><?
//    damp_array($this->rec_scan);
}

 function panel_img()
 {   ?><link rel="stylesheet" type="text/css" href="<?echo _PATH_TO_EXT?>/esmo_magnit/style.css" charset="utf-8">
         <!--<script type="text/javascript" src="/AddOns/zoom-master/jquery.zoom.min.js"></script>-->
         <div id="panel_img">
           <img id="doc_image" src='<?echo $this->rec_scan['obj_name']?>?r=<?rand(1,5000)?>' width='600' />
         </div>
       <br>
       <div id="img_action" class="sky-form no_box_shadow">
           <? // если несколько страниц - кнопка для выделения страницы из пакета
              if ($this->count_pages>1){?><button class="button v2" cmd="esmo_magnit/ScanExlude"  scan_id="<?echo $this->rec_scan['pkey']?>">Выделить лист в отдельный скан</button><?}
           ?>
           <?if (!$this->read_only){?>
           <button class="button rotate_r v2" cmd="esmo_magnit/rotate_r_image" scan_id="<?echo $this->rec_scan['pkey']?>"><i class="fa fa-repeat" aria-hidden="true"></i></button>
           <button class="button rotate_l v2" cmd="esmo_magnit/rotate_l_image" scan_id="<?echo $this->rec_scan['pkey']?>"><i class="fa fa-undo" aria-hidden="true"></i></button>
           <?}?>
           <button class="button print" id="print_doc_over_window" href="<?echo $this->rec_scan['obj_name']?>"><i class="fa fa-print" aria-hidden="true"></i></button>

           <div class="clear"></div>
       </div>
       <?  $list_images=execSQL('select * from obj_site_scan where (parent='.$this->rec_scan['pkey'].' or pkey='.$this->rec_scan['parent'].') and clss=218',0,1) ;
       ?><div id="panel_second_images"><?
       if (_sizeof($list_images)) foreach($list_images as $i=>$rec_image)
       {  ?><div class="item"><a href="/window/esmo_magnit/pdd/scan/<?echo $rec_image['pkey']?>/"><img src="<?echo $rec_image['obj_name']?>" width="200"></a><div class="title">Страница <?echo $rec_image['indx']?></div> </div><?

       }
       ?></div><?


       ?>



        <script type="text/javascript">
            /*$j(document).ready(function(){
                $j('img#doc_image')
                   .wrap('<span style="display:inline-block"></span>')
                   .css('display', 'block')
                   .parent()
                   .zoom();

            });    */
        </script>
        <style type="text/css">
            div#img_action{position:relative;width:100%;height:30px;}
            div#img_action div.title{float:left;height:20px;font-size:14px;}
            div#panel_card_personal_view{margin-top:10px;}
            div#panel_second_images{}
            div#panel_second_images{margin-top:30px;}
            div#panel_second_images div.item{float:left;margin:15px;}
            div#panel_second_images div.item img{-webkit-box-shadow: 0px 0px 14px 0px rgba(50, 50, 50, 0.75);
            -moz-box-shadow:    0px 0px 14px 0px rgba(50, 50, 50, 0.75);
            box-shadow:         0px 0px 14px 0px rgba(50, 50, 50, 0.75);}
            div#panel_second_images div.item div.title{text-align:center;}

        </style>
     <?
 }

 function panel_alert_not_valid_img()
 {   ?><div class="alert">Загруженный файл не является файлом изображения, распознование документа невозможно</div><?
     if ($this->rec_scan['status']!=3 and $this->rec_scan['status']!=4)
     { DOCS()->scan_update($this->rec_scan['pkey'],array('doc_id'=>-1,'status'=>5)) ;
       $this->rec_scan['doc_id']=-1 ;
       $this->rec_scan['status']=5 ;
     }
 }

function panel_JS_capture_QR_code()
{  ?><div id="panel_JS_capture_img">
      <div class="info">Ожидайте, идет поиск и распознование QR-кода <br><img src="<?echo _PATH_TO_EXT.'/esmo_magnit/img/loading14.gif'?>"></div>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/grid.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/version.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/detector.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/formatinf.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/errorlevel.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/bitmat.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/datablock.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/bmparser.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/datamask.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/rsdecoder.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/gf256poly.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/gf256.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/decoder.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/qrcode.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/findpat.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/alignpat.js"></script>
        <script type="text/javascript" src="<?echo _PATH_TO_EXT?>/interface/jsqrcode/src/databr.js"></script>
      <div id="mainbody" style="display: inline;position:absolute;top:0;left:0;"><canvas id="qr-canvas" width="800" height="600" style="width: 800px; height: 600px;"></canvas></div>
    <? // берем только верхний правый угол, где должен быть QR код
       //echo $this->rec_scan['obj_name'].'<br>' ;
       $src_scan_img=$this->rec_scan['obj_name'] ;
       //$src_scan_img_crop=$this->cropImage(_DIR_TO_ROOT.$src_scan_img) ;
       //echo $src_scan_img_crop.'<br>' ;


    if (!$this->rec_scan['pkey']) $this->rec_scan['pkey']=0 ;
    if (!$this->rec_personal['pkey']) $this->rec_personal['pkey']=0 ;
    echo $this->rec_scan['obj_name'] ;
    ?>
    <script type="text/javascript">
         $j(document).ready(function()
         {  console.log('<?echo $src_scan_img?>');
            initCanvas(640,480);
            qrcode.callback = qrcode_read;
            qrcode.decode('data:image/png;<?echo base64_encode(file_get_contents(_DIR_TO_ROOT.$this->rec_scan['obj_name']))?>');

            function qrcode_read(a)
             {
                console.log('qrcode: '+a) ;
                send_ajax_request({cmd:'scan/ScanCapture_QRcode_end',
                                   qrcode:a,
                                   scan_id:<?echo $this->rec_scan['pkey']?>,
                                   personal_id:<?echo $this->rec_personal['pkey']?>
                                  }) ;
             }


             function initCanvas(ww,hh)
             	{
             		gCanvas = document.getElementById("qr-canvas");
             		//gCanvas.addEventListener("dragenter", dragenter, false);
             		//gCanvas.addEventListener("dragover", dragover, false);
             		//gCanvas.addEventListener("drop", drop, false);
             		var w = ww;
             		var h = hh;
             		gCanvas.style.width = w + "px";
             		gCanvas.style.height = h + "px";
             		gCanvas.width = w;
             		gCanvas.height = h;
             		gCtx = gCanvas.getContext("2d");
             		gCtx.clearRect(0, 0, w, h);
             		imageData = gCtx.getImageData( 0,0,320,240);
             	}
         }) ;
   </script>
   </div><?
}

 function cropImage($imagePath)
 {   //echo '$imagePath='.$imagePath.'<br>' ;
     $arr_info=getimagesize($imagePath,$arr_info2) ;
     //echo 'Размер изображения: тип файла '.$arr_info['mime'].', разрешение '.$arr_info[0].'x'.$arr_info[1].', размер '.show_size(filesize($imagePath)).'<br>' ;
     $width=$arr_info[0]/3 ;
     $height=$arr_info[1]/4 ;
     $startX=$arr_info[0]-$width ;
     $startY=0;

     $images = new Imagick(realpath($imagePath));
     $images->setResolution(300,300);
     //$images->readImage($saved_file_dir);
     $images->cropImage($width, $height, $startX, $startY);
     //$images->rotateimage('#ffffff', 8);
     $saved_img_file_name='crop_'.basename($imagePath) ;
     $saved_img_file_dir=_TEMP_DIR.$saved_img_file_name;
     //$koof=Imagick::getQuantum() ;
     $koof=65535 ;
     $images->thresholdImage($GLOBALS['LS_qr_code_scan_threshold'] * $koof);
     //$images->setColorspace(imagick::IMGTYPE_GRAYSCALE);
     //$images->setCompression(Imagick::COMPRESSION_JPEG);
     $images->setCompressionQuality(100);
     $images->setImageFormat("jpg");
     $images->writeImage($saved_img_file_dir);
     //echo '$saved_img_file_name='.$saved_img_file_name.'<br>' ;
     /*if (file_exists($saved_img_file_dir)){?><img src="<? echo _UPLOADS_DIR.$saved_img_file_name?>" style="border:1px solid red;"><?}*/
     return(hide_server_dir($saved_img_file_dir)) ;
    }


function panel_scan_info_view()
{  ?><table class="basic fz_small center full auto" id="panel_scan_info_view">
       <tr><th>Время<br>загрузки</th>
           <th>АТП<br>загрузки</th>
           <th>Источник</th>
           <th>Время<br>ожидания</th>
           <th>Оператор</th>
           <!--<th>Начало<br>обработки</th>
           <th>Время<br>обработки</th>-->
           <th>QR код</th>
           <th>Тип</th>
           <th>Документ</th>
           <th>Сотрудник</th>
           <th>Статус</th>
       </tr>
       <tr>
           <td class="center"><?echo date('d.m.Y H:i',$this->rec_scan['c_data'])?><??></td>
           <td class="center"><?
               if ($this->rec_scan['group_upload']) echo $this->rec_scan['_group_upload_name'];
               else
               {  $arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;
                  ?><form><select class=filter name="group_id"><option value="0"></option>
                      <? if (_sizeof($arr_groups)) foreach($arr_groups as $id=>$name){?><option value="<?echo $id?>"><?echo $name?></option><?} ?>
                    </select><br><br><input type="submit" class="button v2" cmd="esmo_magnit/save_scan_group" scan_id="<?echo $this->rec_scan['pkey']?>" value="Сохранить"></form><?

               }
               ?></td>
           <td class="center"><?echo $this->rec_scan['_source']?><??></td>
           <td class="center"><?if ($this->rec_scan['data_work'])  echo ENGINE()->get_text_time_diff($this->rec_scan['c_data'],$this->rec_scan['data_work']) ;?></td>
           <td class="center"><?echo $this->rec_scan['_account_work_name']?></td>
           <!--<td class="center"><?if ($this->rec_scan['data_work']) echo date('d.m.Y H:i',$this->rec_scan['data_work'])?></td>
           <td class="center"><?if ($this->rec_scan['data_set']) echo ENGINE()->get_text_time_diff($this->rec_scan['data_work'],$this->rec_scan['data_set']) ;?></td>-->
           <!--<td><?if ($this->rec_scan['qrcode']==-1) echo '<span class=red>Не удалось распознать</span>' ;
                 else if ($this->rec_scan['qrcode']!="") echo '<span class=green>'.$this->rec_scan['qrcode'].'</span>' ;
           ?></td>-->
           <td class="center"><?echo ($this->rec_scan['qrcode']>0)? '<i class="far fa-check-circle green"></i>':'<i class="fas fa-times red"></i>'?></td>
           <td class="center"><?echo ($this->rec_scan['doc_type'])? '<i class="far fa-check-circle green"></i>':'<i class="fas fa-times red"></i>'?></td>
           <td class="center"><?echo ($this->rec_scan['doc_id']>0)? '<i class="far fa-check-circle green"></i>':'<i class="fas fa-times red"></i>'?></td>
           <td class="center"><?echo ($this->rec_scan['personal_id'])? '<i class="far fa-check-circle green"></i>':'<i class="fas fa-times red"></i>'?></td>
           <td class="center"><? if ($this->rec_scan['status']==3) echo '<span class=green>'.$_SESSION['ARR_status_scan'][$this->rec_scan['status']].'</span>' ;
                                 else if ($this->rec_scan['status']==4) echo '<span class=red>'.$_SESSION['ARR_status_scan'][$this->rec_scan['status']].'</span>' ;
                                 else echo '<span>'.$_SESSION['ARR_status_scan'][$this->rec_scan['status']].'</span>' ;
                              ?>
           </td>
       </tr>
     </table>
     <?
    if ($this->rec_scan['error']) echo '<br>Причина отклонения: <span class=alert>'.$this->rec_scan['error'].'</span><br>' ;

}



function panel_card_personal_view()
 { include_once(_DIR_EXT.'/esmo_magnit/panel_personal_info_small.php') ;
   ?><div id="panel_card_personal_view">
     <?if ($this->rec_personal['pkey']){?>
       <h2>Сотрудник</h2>
       <table class="cols3">
         <tr><td class="img"><img class="shadow main" src="<?echo img_clone($this->rec_personal,'200')?>">
                             <?if (!$this->rec_personal['enabled']){?><div class="personal_fired">Уволен</div><?}?>
             </td>
             <td class="info"><?panel_personal_info_small($this->rec_personal,array()); ?></td>
             <td class="krit"></td>
         </tr>
       </table><?
     }?>

    </div>
  <?
 }
function panel_card_doc_view()
 { ?><div id="panel_card_personal_view"><?
   if (function_exists('EVENTS') and $this->rec_scan['source_obj']) $event_obj=EVENTS()->get_event_obj_by_ext($this->rec_scan['source_obj']) ;
   if ($this->rec_scan['doc_type'])
   { ?><h2>Документ</h2>
       <table class="info">
          <tr><td>Документ ЭСМО:</td>
              <td><strong><?if ($this->rec_doc['pkey']) {?><a href="<?echo $this->rec_doc['__href_window']?>" class="new_window" title="window_doc_<?echo $this->rec_doc['pkey']?>"><?echo $this->rec_doc['obj_name']?></a><?}
                    else echo '-';?>
              </td>
          </tr>
          <?if ($this->rec_scan['doc_type']){?><tr><td>Тип документа:</td><td><strong><?echo $this->arr_doc_types_register[$this->rec_scan['doc_type']]?></strong></td></tr><?}?>
          <?if ($this->rec_scan['source_obj'] and is_object($event_obj)){?><tr><td>Мероприятие документа:</td><td><strong><?echo $event_obj->name?></strong></td></tr><?}?>
          <tr><td>Дата выдачи (подписи):</td><td><strong><?echo ($this->rec_doc['sign_data'])? date('d.m.Y H:i',$this->rec_doc['sign_data']):'-'?></strong></td></tr>
          <tr><td>Документ сформирован для:</td><td><strong><?echo ($this->rec_doc['_personal_name'])? $this->rec_doc['_personal_name']:'-'?></strong></td></tr>
         </table>
    </div>
  <?}
//    damp_array($this->rec_doc) ;
 }

function panel_cur_group_medic_view()
{ ?><div id="panel_cur_group_medic_view">
    <strong>Текущие группы сотрудника по болезни</strong><br><?
    if (_sizeof($this->rec_personal['_groups_medic'])){?><div id=personal_groups style="font-size:18px;color:red;"><? if (_sizeof($this->rec_personal['_groups_medic'])) echo implode(', ',$this->rec_personal['_groups_medic']) ?></div><?}
    else echo 'не задано' ;
  ?></div><?
}



  // в дальнейшем вынести эту функцию в собственный класс мероприятия
  function panel_view_diagnoz()
  { ?><div id="panel_view_diagnoz" style="margin-bottom:20px;">
      <h2><?echo ($this->rec_scan['diagnoz'] and $this->rec_scan['status']==2)? 'Старый диагноз':'Диагноз'?></h2>
      <div style="border:1px solid #eeeeee;padding:20px;text-align:center;background:#9bdadd;font-size:16px;"><?echo $this->rec_scan['diagnoz']?></div>
      <?/*if ($this->rec_scan['data_doc']){?><div style="margin:10px 0;">Дата заключения: <span style="font-size:18px;"><?echo date('d.m.Y',$this->rec_scan['data_doc'])?></span></div><?}*/?>
    </div><?
  }

  // в дальнейшем вынести эту функцию в собственный класс мероприятия
  function panel_view_comment()
  { ?><div id="panel_view_diagnoz" style="margin-bottom:20px;">
      <strong><?echo ($this->rec_scan['diagnoz'] and $this->rec_scan['status']==2)? 'Старый комментарий':'Комментарий к скану:'?></strong>
      <span style="font-size:16px;"><?echo $this->rec_scan['comment']?></span>
    </div><?
  }

  function panel_view_data_doc()
  { ?><div id="panel_view_diagnoz" style="margin-bottom:20px;">
      <strong>Дата документа</strong>: <span style="font-size:16px;"> <?echo date('d.m.Y',$this->rec_scan['data_doc'])?></span>
    </div><?
  }

  function panel_view_after_block_mo()
  { ?><div id="panel_view_diagnoz" style="margin-bottom:20px;">
      <strong>Решение по скану документа:</strong>
      <?if ($this->rec_scan['after_block_mo']==2){?><span style="font-size:16px;color:red;">Прохождение МО запрещено</span><?}
        if ($this->rec_scan['after_block_mo']==1){?><span style="font-size:16px;color:green;">Прохождение МО разрешено</span><?}
      ?>
    </div><?
  }

  function panel_change_diagnoz_button()
  {  ?><div id="panel_filter">
                  <form id="sky-form" class="sky-form"><input type="hidden" name="filter_dir">
                       <div id="panel_buttons">
                          <button class="button v2" cmd="esmo_magnit/diagnoz_change"  scan_id="<?echo $this->rec_scan['pkey']?>">Изменить диагноз</button>&nbsp;&nbsp;
                      </div>
                   </form>
        </div>
     <?
  }


  function panel_scan_capture_repeat()
  {  ?><div id="panel_filter">
                  <form id="sky-form" class="sky-form">
                       <div id="panel_buttons">
                          <button class="button v2" cmd="esmo_magnit/ScanCaptureRepeat"  scan_id="<?echo $this->rec_scan['pkey']?>" url_page="<?echo _CUR_REPORT_DIR?>">Повторно распознать документ</button>&nbsp;&nbsp;
                          <button class="button v2" cmd="esmo_magnit/ScanCaptureError"  scan_id="<?echo $this->rec_scan['pkey']?>" url_page="<?echo _CUR_REPORT_DIR?>">Документ загружен ошибочно</button>&nbsp;&nbsp;
                      </div>
                   </form>
        </div>
     <?
  }

 function panel_search_personals()
 {

     ?><div id="panel_search_personals"><h2>Требуется поиск</h2><?
      $form=new i_form() ;
      $form->form_open() ;
      $form->fieldset_open();
      $form->row_open() ;
      if (!$this->rec_scan['personal_id']) $form->filter_section_input_text('name','ФИО',11,['_cur_value'=>$this->rec_scan['doc_type'],'auto_complete'=>'autocomplette_personal_name']) ;
      else $form->hidden_var('personal_id',$this->rec_scan['personal_id']) ;
      if (!$this->rec_scan['doc_id'] and !$this->rec_scan['doc_type'])
      { $form->filter_section_select('doc_type','Тип документа',8,$this->arr_doc_types_register,['cur_value'=>$this->rec_scan['doc_type']]) ;
        $form->filter_section_input_text('doc_number','Номер документа',3,['_cur_value'=>$this->rec_scan['doc_type']]) ;
      }
      $form->row_close() ;
      $form->button('Найти','scan/search_personal',['scan_id'=>$this->rec_scan['pkey'],'class'=>'left']);
      $form->fieldset_close();
      $form->form_close() ;
     ?></div><?
     ?><div id="panel_search_personals_result"></div><?
 }


 function panel_scan_debug_info()
 {  $arr['pkey']=$this->rec_scan['pkey'] ;
    $arr['status']=$this->rec_scan['status'] ;
    $arr['member_id']=$this->rec_scan['member_id'] ;
    $arr['doc_id']=$this->rec_scan['doc_id'] ;
    $arr['personal_id']=$this->rec_scan['personal_id'] ;
    $arr['diagnoz']=$this->rec_scan['diagnoz'] ;
    $arr['comment']=$this->rec_scan['comment'] ;
    $arr['source']=$this->rec_scan['source'] ;
    $arr['account_upload']=$this->rec_scan['account_upload'] ;
    $arr['data_work']=date('d.m.y H:i:s',$this->rec_scan['data_work']) ;
    $arr['data_set']=date('d.m.y H:i:s',$this->rec_scan['data_set']) ;
    $res[]=$arr ;
    ?><br><br><br><br><?
    print_2x_arr($res) ;

 }


}



?>
