<?php
// специальный отчет для добавления сотрудников в группы
include_once(_DIR_EXT.'/esmo_magnit_pmo/i_event_pmo.php') ;
class report_opo_inrm_vpf extends c_report
{
 var $title='Редактирование ВПФ ОПО для ИНРМ' ;
 var $view_by_space_filter=0 ;
 var $SQL_left_join='' ;
 var $t='' ;
 var $arr_view_modes=['no_group_orgs'=>'Не группировать организации в ИНРМ',
                      'no_group_otdes'=>'Не группировать подразделения в ИНРМ',
                     ] ;

function setting($options=array())
 {   if (!is_array($options['disabled_filter'])) $options['disabled_filter']=array() ;

     list($arr_orgs_ids,$arr_otdel_ids,$arr_workd_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter) ;

     $form=new i_form;
     $form->form_open();
     $form->fieldset_open() ;
     $form->row_open() ;
     $this->filter_section_select_multiple('org_ids','Организация:',4,$arr_orgs_ids) ;
     $this->filter_section_select_multiple('otdel_ids','Подразделение:',4,$arr_otdel_ids) ;
     $this->filter_section_select_multiple('working_ids','Должность:',2,$arr_workd_ids) ;
     $form->row_close_open() ;
     $this->filter_section_input_text('inrm','ИНРМ:',2) ;
     $this->filter_section_input_text('vpf','Номер раздела ВПФ:',2) ;
     $this->filter_section_select_multiple('view_modes','Отображение:',2,$this->arr_view_modes) ;
     $form->row_close() ;

     $form->fieldset_close();
     $this->panel_button_apply(['buttons'=>['apply',
                                            ['cmd'=>'ot/get_panel_setting_vpf'],
                                             'source'=>'opo'
                                            ]
                                ]);
     $form->form_close() ;
  }

  function panel_report_buttons()
  {
      ?><button class="button v2" cmd="ot/get_panel_setting_vpf" source="opo" >Настроить ВПФ для всех</button><?
  }

  function create_usl_select_obj($_params=[],&$options=[])
  {  //damp_array($this->filter,1,-1) ;
     $usl=array() ;
     $usl[]='t1.clss=212' ;
     $usl[]='t1.enabled=1' ;
     $usl[]='t1.parent2>0' ;
     if ($this->filter['org_id']) $usl[]='t1.parent2='.$this->filter['org_id'] ;
     if (_sizeof($this->filter['org_ids'])) $usl[]='t1.parent2 in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
     if (_sizeof($this->filter['working_ids'])) $usl[]='t1.work_id in ('.implode(',',array_keys($this->filter['working_ids'])).')' ;
     if (_sizeof($this->filter['otdel_id']))
     { $level=execSQL_value('select level from obj_site_personals where pkey='.$this->filter['otdel_id']) ;
       $usl[]='t1.parent'.$level.'='.$this->filter['otdel_id'] ;
     }
     if (_sizeof($this->filter['otdel_ids']))
     { $arr_ordels_levels=execSQL_row('select pkey,level from obj_site_personals where pkey in ('.implode(',',array_keys($this->filter['otdel_ids'])).')') ;
       $_usl=[] ;
       if (_sizeof($arr_ordels_levels)) foreach($arr_ordels_levels as $otdel_id=>$level) $_usl[]='t1.parent'.$level.'='.$otdel_id ;
       $usl[]='('.implode(' or ',$_usl).')' ;
     }
     if ($this->filter['inrm'])  $usl[]='inrm like "%'.$this->filter['inrm'].'%"' ;
     if ($this->filter['vpf'])
     {   $sql='select t2.inrm 
               from opo_list_vpf t1
               left join opo_inrm_vpf t2 on t2.vpf_id=t1.pkey
               where t1.number like "'.$this->filter['vpf'].'%"' ;
         SETUP()->create_temporary_table('temp_arr_inrm',$sql);
         //$arr=execSQL('select * from temp_arr_inrm',2) ;
         $this->SQL_left_join='left join temp_arr_inrm t_vpf on t_vpf.inrm=t1.inrm' ;
         $usl[]='not t_vpf.inrm is null' ;

     }
     //if (_sizeof($this->filter['group_ids'])) $usl[]='pkey in ('.implode(',',array_keys($this->filter['group_ids'])).')' ;
     $usl_res=implode(' and ',$usl) ;
     return($usl_res) ;
  }

 function panel_info_filter()
 { $_str=array() ; $info=array() ; $title='' ;
   if ($this->filter['name'])                  $info['Наименование группы']='"'.$this->filter['name'].'"' ;
   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())
  { //$options['debug']=2 ;
    $cnt=execSQL_value('select count(*) from (
                        select t1.parent1,t1.parent2,t1.parent3,t1.parent4,t1.parent5,t1.parent6,t1.parent7,t1.parent8,t1.parent9,t1.work_id 
                        from obj_site_workers t1
                        '.$this->SQL_left_join.' 
                        where '.$usl.'
                        group by t1.parent1,t1.parent2,t1.parent3,t1.parent4,t1.parent5,t1.parent6,t1.parent7,t1.parent8,t1.parent9,t1.work_id
                        ) as tt
                    ',$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 parent2,parent3,parent4,parent5,parent6,parent7,parent8,parent9,work_id ' ;
    //$options['debug']=1 ;
 	$list_recs=execSQL('
 	             select t1.parent1,t1.parent2,t1.parent3,t1.parent4,t1.parent5,t1.parent6,t1.parent7,t1.parent8,t1.parent9,t1.work_id,
 	             t1.inrm,count(distinct(t1.personal_id)) as cnt_person
 	             from obj_site_workers t1 
                 '.$this->SQL_left_join.'
                 where '.$usl.'
                 group by parent2,parent3,parent4,parent5,parent6,parent7,parent8,parent9,work_id
 	            '.$order.$limit,array('debug'=>$options['debug'],'no_indx'=>1)) ;


 	// заполняем поля наименования подразделений и должностей в списке сотрудников
    $this->full_org_othdels_work_names($list_recs) ;



     // print_2x_arr($list_rec);


    return($list_recs) ;
  }

  // заполняем поля
  // parentX_name
  // _work_name
  // _dep_id
  // _otdel_path
  function full_org_othdels_work_names(&$list_recs)
  {
      $arr_ids_orgs=[] ; $names_orgs=[] ; $names_works=[] ; $arr_ids_workings=[] ;
       	if (_sizeof($list_recs)) foreach($list_recs as $rec)
       	{ for($i=1;$i<=9;$i++) if ($rec['parent'.$i]) $arr_ids_orgs[$rec['parent'.$i]]=1 ;
       	  if ($rec['work_id']) $arr_ids_workings[$rec['work_id']]=1 ;
          }
       	//damp_array($arr_ids_workings);

    //damp_array($this->filter);

       	if (_sizeof($arr_ids_orgs)) $names_orgs=execSQL_row('select pkey,obj_name from obj_site_personals where pkey in ('.implode(',',array_keys($arr_ids_orgs)).')') ;
          if (_sizeof($arr_ids_workings)) $names_works=execSQL_row('select id,obj_name from view_IL_works where id in ('.implode(',',array_keys($arr_ids_workings)).')') ;
       	//damp_array($names_orgs);
          if (_sizeof($list_recs)) foreach($list_recs as &$rec)
          { $arr_otdel_path=[] ; $dep_id=0 ;
            for($i=1;$i<=9;$i++)
            { $parentX='parent'.$i ;
              $parentXname='_parent'.$i.'_name' ;
              if ($rec[$parentX]) $rec[$parentXname]=($names_orgs[$rec[$parentX]])? $names_orgs[$rec[$parentX]]:'Организация ID '.$rec[$parentX] ; else $rec[$parentXname]='-' ;
              if ($i>=3 and $rec[$parentX]>0) $arr_otdel_path[]=$rec[$parentXname] ;
               if ($rec[$parentX]) $dep_id=$rec[$parentX] ; // запоминаем ID последнего подразделения
            }
            $rec['_otdel_path']=(_sizeof($arr_otdel_path))? implode(' / ',$arr_otdel_path):'-' ;
            if ($rec['work_id']) $rec['_work_name']=($names_works[$rec['work_id']])? $names_works[$rec['work_id']]:'Должность ID '.$rec['work_id'] ; else  $rec['_work_name']='-' ;
            $rec['_dep_id']=$dep_id ;
          }

  }

  function get_items_only_inrm($usl,$options=array())
  { //$options['debug']=1 ;
    $list_rec=execSQL_line('
 	             select t1.inrm
                 from obj_site_workers t1 
                 '.$this->SQL_left_join.'
                 where '.$usl.'
                 group by parent2,parent3,parent4,parent5,parent6,parent7,parent8,parent9,work_id
                 order by t1.inrm
 	            ',array('debug'=>$options['debug'])) ;
    return($list_rec) ;
  }


  // шаблон - вывод ссылками без разделитея
  function print_template_HTML($list_recs,$options=array())
  { // массив разделов ВПФ
    $arr_vpf_sections=execSQL_row('select pkey as id,obj_name from opo_list_vpf where clss=233 and level=2 order by indx') ;
    $inrm_min_period=execSQL_row('select inrm,min(t2.period) 
                                    from opo_inrm_vpf t1
                                    left join opo_list_vpf t2 on t2.pkey=t1.vpf_id
                                    where t2.period>0
                                    group by t1.inrm
                                    ') ;

    // список вредных производсьвенных факторов ддя РМ
    $arr_rm_vpf2=array() ;
    $arr_rm_vpf=execSQL('select t1.inrm,t1.vpf_id,t2.number,t2.parent2 as section_id,t2.period 
                           from opo_inrm_vpf t1 
                           left join opo_list_vpf t2 on t2.pkey=t1.vpf_id
                           order by t1.inrm,t2.number 
                           ',0,1) ;
    if (_sizeof($arr_rm_vpf)) foreach($arr_rm_vpf as $rec_rm_vpf)
    {
      $arr_rm_vpf2[$rec_rm_vpf['inrm']][$rec_rm_vpf['vpf_id']]='<span class="period_'.$rec_rm_vpf['period'].'">'.trim($rec_rm_vpf['number']).'</span>' ;
    }
    //damp_array($arr_rm_vpf2);

    // вспомогательные массивы для объединения строк ячеек
    $row_stats=[] ;$row_stats2=[] ;
    if ($list_recs) foreach($list_recs as $rec)
    { if (!$this->filter['view_modes']['no_group_orgs']) $row_stats[$rec['parent2']]++ ;
      if (!$this->filter['view_modes']['no_group_otdes']) $row_stats2[$rec['_dep_id']]++ ;
    }
    //damp_array($row_stats);
    //damp_array($row_stats2);
    //print_2x_arr($list_recs);

    $this->form->form_open();
    $row_group_open=0 ;$row_group_open2=0 ;
    ?><table class="basic fz_small full auto">
        <tr>
           <th>Организация</th>
           <th>Подразделение</th>
           <th>Должность</th>
           <th>ИНРМ</th>
           <th>Кол-во</th>
           <th>Период ОПО</th>
           <th>ВПФ</th>
        </tr>
        <?if ($list_recs) foreach($list_recs as $rec)
            {   if ($row_group_open!=$rec['parent2']) $row_group_open=0  ;
                if ($row_group_open2!=$rec['_dep_id']) $row_group_open2=0  ;

                ?><tr><?if (!$row_group_open) {?><td class="left" <?if ($row_stats[$rec['parent2']]>1) {echo 'rowspan='.$row_stats[$rec['parent2']]; $row_group_open=$rec['parent2'] ;} ?>><a class="fa fa-sliders v2" cmd="ot/get_panel_setting_vpf" source="opo"  org_id="<?echo $rec['parent2']?>">&nbsp;</a>&nbsp;<?echo $rec['_parent2_name']?></td><?}?>
                      <?if (!$row_group_open2){?><td class="left" <?if ($row_stats2[$rec['_dep_id']]>1) {echo 'rowspan='.$row_stats2[$rec['_dep_id']]; $row_group_open2=$rec['_dep_id'] ;} ?>><?if ($rec['_dep_id']!=$rec['parent2']){?><a class="fa fa-sliders v2" cmd="ot/get_panel_setting_vpf" source="opo"  otdel_id="<?echo $rec['_dep_id']?>">&nbsp;</a><?}?>&nbsp;<?echo $rec['_otdel_path']?></td><?}?>
                      <td class="left"><?echo $rec['_work_name']?></td>
                      <td><a class="fa fa-sliders v2" cmd="ot/get_panel_setting_vpf" source="opo" inrm="<?echo $rec['inrm']?>">&nbsp;</a>&nbsp;<?echo $rec['inrm']?></td>
                      <td><a href="/cab/personal/[org_ids=(<?echo $rec['parent2']?>),otdel_ids=(<?echo $rec['_dep_id']?>),working_ids=(<?echo $rec['work_id']?>)]/" target="_blank"><?echo $rec['cnt_person']?></a></td>
                      <td><?echo OPO()->arr_opo_len[$inrm_min_period[$rec['inrm']]]?></td>
                      <td><?if (_sizeof($arr_rm_vpf2[$rec['inrm']])) echo implode(' ',$arr_rm_vpf2[$rec['inrm']])?></td>
                </tr><?
             }?>
         </table>
    <?
      $this->form->form_close();
      ?>
        <style type="text/css">
                span.period_0{color:#aaaaaa;}
                span.period_60{color: #6aaa0c;}
                span.period_24{color: #6aaa0c;}
                span.period_12{color: #272727;}
                span.period_6{color: #aa2e00;}
            </style>
      <?
  }


}

?>
