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

class report_mo_result extends c_report
{
 var $title='Журнал МО - форма № 3' ;
 var $view_only_model=1 ;
 var $mo_sort='pkey' ;
 var $allow_export_to_csv=1 ;
 var $allow_export_to_excel=1 ;

 function setting()
{

  $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) ;

  ?><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) ;
                       $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('data_from','От:',2,array('class'=>'datetimepicker')) ;
                       $this->filter_section_input_text('data_to','До:',2,array('class'=>'datetimepicker')) ;
                                ?>
                </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 (_sizeof($this->filter['dopusk']))                  foreach($this->filter['dopusk'] as $dopusk_id=>$value) $info['Допуск'][]=$_SESSION['ARR_status_dopusk'][$dopusk_id]  ;
   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']) and _sizeof($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' ;  // только конечные МО с моделью
   }
   if (!is_array($this->filter['dopusk']) and $this->filter['dopusk']) $options_select['dopusk']=$this->filter['dopusk'] ;
   if (!is_array($this->filter['dopusk']) and $this->dopusk) $options_select['dopusk']=$this->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->personal_id)  $options_select['personal_id']=$this->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=ESMO()->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 '.ESMO()->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 pkey desc' ;
    //if (_IS_SYSTEM_IP) $options['debug']=1 ;
    $recs=execSQL('select * from '.ESMO()->view_mo_session.' where '.$usl.$order.$limit,$options) ;
    if (_sizeof($recs)) foreach($recs as $id=>$rec) {
        ESMO()->prepare_public_info_to_mo($recs[$id],$options) ;
        $recs[$id]['_personal_info']=PERSONAL()->get_personal_by_id($rec['personal_id']);
    }
    return($recs) ;
  }

 // шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  {  $id=($options['id'])? 'id='.$options['id']:'' ;
    ?><div id="reports_mo"><div class=list_mo_sessions_report <?echo $id?>>
      <table class="basic fz_small" >
        <colgroup><col id="c0"><col id="c1"><col id="c3"><col id="c4"><col id="c11"><col id="c12"><col id="c13"></colgroup>
        <tr><th>№</th>
            <th>Табельный номер</th>
            <th>Фамилия медицинского работника</th>
            <th>Имя медицинского работника</th>
            <th>Отчетсво медицинского работника</th>
            <th>Номер карты</th>
            <th>Дата начала МО</th>
            <th>Время начала МО</th>
            <th>Краткий результат прохождения МО</th>
            <th>Полный результат МО</th>
          </tr>
        <?
        $i=$this->first_obj ; ;
        if (_sizeof($list_recs)) foreach($list_recs as $rec)
        {   if (!isset($recs_doctor[$rec['doctor_id']])) $recs_doctor[$rec['doctor_id']]=ACCOUNTS()->get_member_by_id($rec['doctor_id']) ;

            list($lastname,$firstname,$secondname)=$this->get_person_name($rec['_doctor_name_small']);

            ?><tr class=item>
                <td><?echo '<a href="/cab/mo/'.$rec['pkey'].'/" target=_blank>'.$i.'</a>' ;  $i++ ;?></td>
                <td><?echo $rec['_personal_info']['tab_number']?></td>
                <td><?echo $lastname?></td>
                <td><?echo $firstname?></td>
                <td><?echo $secondname?></td>
                <td><?echo $rec['_personal_info']['propusk']?></td>
                <td><?echo date('d.m.Y',$rec['c_data'])?></td>
                <td><?echo date('H:i',$rec['c_data'])?></td>
                <td><?echo ($rec['dopusk'])? $_SESSION['ARR_status_dopusk'][$rec['dopusk']]:'' ;?></td>
                <td>
                    <?
                    if ($rec['_question']) echo 'Жалобы: '.$rec['_question'].'<br>';
                    if ($rec['_alko']) echo 'Алкоголь: '.$rec['_alko'].'<br>';
                    if ($rec['_sd']) echo 'Давление: '.$rec['_sd'].'<br>';
                    if ($rec['_pulse']) echo 'Пульс: '.$rec['_pulse'].'<br>';
                    if ($rec['_temperature']) echo 'Температура: '.$rec['_temperature'].'<br>';
                    ?>
                </td>
            </tr><?
        }
      ?></table></div></div><?
  }

    function print_template_CSV($list_recs,$options=array())
    { $i=$options['from'] ;
      if (_sizeof($list_recs)) foreach($list_recs as $rec)
        {
            list($lastname,$firstname,$secondname)=$this->get_person_name($rec['_doctor_name_small']);
            $result_mo = $this->get_mo_result_full_string($rec);

            $data=array() ;

            $data['Табельный номер']=($rec['_personal_info']['tab_number'])?$rec['_personal_info']['tab_number']:'';
            $data['Фамилия медицинского работника']=$lastname;
            $data['Имя медицинского работника']=$firstname;
            $data['Отчество медицинского работника']=$secondname;
            $data['Номер карты']=($rec['_personal_info']['propusk'])?$rec['_personal_info']['propusk']:'';
            $data['Дата начала МО']=date('d.m.Y',$rec['c_data']);
            $data['Время начала МО']=date('H:i',$rec['c_data']);
            $data['Краткий результат прохождения МО']=($rec['dopusk'])? $_SESSION['ARR_status_dopusk'][$rec['dopusk']]:'' ;
            $data['Полный результат МО']=$result_mo;

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

            $i++ ;
        }

    }

    function print_template_XLS($list_recs, $options = array())
    {
        $this->fields=array(
            'tab_num'=>array('title'=>'Табельный номер','width'=>10,'align'=>'left'),
            'lastname_medic'=>array('title'=>'Фамилия медицинского работника','width'=>10,'align'=>'left'),
            'firstname_medic'=>array('title'=>'Имя медицинского работника','width'=>10,'align'=>'left'),
            'secondname_medic'=>array('title'=>'Отчество медицинского работника','width'=>10,'align'=>'left'),
            'pass'=>array('title'=>'Номер карты','width'=>10,'align'=>'left'),
            'date_mo'=>array('title'=>'Дата начала МО','width'=>10,'align'=>'left'),
            'time_mo'=>array('title'=>'Время начала МО','width'=>10,'align'=>'left'),
            'mo_result'=>array('title'=>'Краткий результат прохождения МО','width'=>10,'align'=>'left'),
            'mo_result_full'=>array('title'=>'Полный результат МО','width'=>10,'align'=>'left'),
        ) ;

        // шапка таблицы
        $this->XLS_print_table_header() ;
        // данные таблицы
        if (_sizeof($list_recs)) foreach($list_recs as $rec)
        {
            list($lastname,$firstname,$secondname)=$this->get_person_name($rec['_doctor_name_small']);

            $result_mo = $this->get_mo_result_full_string($rec);

            $cur_col_char=$this->first_col_char ;
            if (_sizeof($this->fields)) foreach($this->fields as $fname=>$options)
            {  $value='' ;
                switch($fname)
                {
                    case 'tab_num':        $value=$rec['_personal_info']['tab_number'] ;  break ;
                    case 'lastname_medic':        $value=$lastname ;  break ;
                    case 'firstname_medic':        $value=$firstname ;  break ;
                    case 'secondname_medic':        $value=$secondname ;  break ;
                    case 'pass':        $value=$rec['_personal_info']['propusk'] ;  break ;
                    case 'date_mo':        $value=date('d.m.Y',$rec['c_data']) ;  break ;
                    case 'time_mo':        $value=date('H:i',$rec['c_data']) ;  break ;
                    case 'mo_result':        $value=$_SESSION['ARR_status_dopusk'][$rec['dopusk']] ;  break ;
                    case 'mo_result_full':        $value=$result_mo ;  break ;
                }

                $col_char=iconv('windows-1251','UTF-8',chr($cur_col_char)) ;
                //$this->aSheet->setCellValueByColumnAndRow($col_char,$this->cur_row,$value);
                $this->aSheet->setCellValue($col_char.$this->cur_row,$value);
                if ($options['align']=='center') $this->aSheet->getStyle($col_char.$this->cur_row)->applyFromArray($this->style['center']);
                if ($options['align']=='left')   $this->aSheet->getStyle($col_char.$this->cur_row)->applyFromArray($this->style['left']);
                $cur_col_char++ ;
            }

            $this->cur_row++ ;
        }

    }

    function get_person_name($full_name) {
        $personal_name=explode(' ',$full_name);
        if ($personal_name[0]) {
            $lastname=$personal_name[0];
            if ($personal_name[1]) {
                $firstname=$personal_name[1];
                unset($personal_name[0]); unset($personal_name[1]);
                $secondname=implode(' ',$personal_name);
            } else {
                $firstname=''; $secondname='';
            }
        } else {
            $lastname=''; $firstname=''; $secondname='';
        }
        return (array($lastname,$firstname,$secondname)) ;
    }

    function get_mo_result_full_string($rec) {
        $result_mo='';
        if ($rec['_question']) $result_mo.='Жалобы: '.$rec['_question'];
        if ($rec['_alko']) {
            if ($result_mo) $result_mo.=', Алкоголь: '.$rec['_alko']; else $result_mo.='Алкоголь: '.$rec['_alko'];
        }
        if ($rec['_sd']) {
            if ($result_mo) $result_mo.=', Давление: '.$rec['_sd']; else $result_mo.='Давление: '.$rec['_sd'];
        }
        if ($rec['_pulse']) {
            if ($result_mo) $result_mo.=', Пульс: '.$rec['_pulse']; else $result_mo.='Пульс: '.$rec['_pulse'];
        }
        if ($rec['_temperature_csv']) {
            if ($result_mo) $result_mo.=', Температура: '.$rec['_temperature_csv']; else $result_mo.='Температура: '.$rec['_temperature_csv'];
        }
        return strip_tags($result_mo);
    }


}
?>
