<?
include_once(_DIR_EXT.'/HTML/c_page_XML_AJAX.php') ;
class c_page_ajax extends c_page_XML_AJAX
{
    function get_panel_setting_vpf()
    {   //damp_array($_POST,1,-1) ;
        ?><div id="panel_select_item_vpf"><?
        $arr=array() ; $arr_inrm=[] ;

        if ($_POST['org_id']) $_POST['filter']['org_id']=$_POST['org_id'] ;
        if ($_POST['otdel_id']) $_POST['filter']['otdel_id']=$_POST['otdel_id'] ;
        $source=($_POST['source'])?:'pmo' ;
        $table_vpf=($source=='opo')? 'opo_list_vpf':'list_vpf'  ;
        $table_inrm_vpf=($source=='opo')? 'opo_inrm_vpf':'list_rm_fvp'  ;

        if (_sizeof($_POST['filter']))
        { include_once(_DIR_EXT.'/ot/report_inrm_vpf.php') ;
          $report_obj=new report_inrm_vpf(['source'=>$source]) ;
          $report_obj->filter=$report_obj->filter_array_flip($_POST['filter']);
          $usl=$report_obj->create_usl_select_obj() ;
          //echo 'usl='.$usl.'<br>' ;
          $arr_inrm=$report_obj->get_items_only_inrm($usl) ;

        }
        //print_r($arr_inrm);

        // если передается конерктный ИНРМ - получаем список выбранных ВПФ для него
        $arr_checked_ids=array() ;
        if ($_POST['inrm'])
        {  $arr_checked_ids=execSQL_row('select vpf_id,pkey 
                                         from '.$table_inrm_vpf.'
                                         where inrm="'.$_POST['inrm'].'"') ;
           unset($arr_checked_ids[1]) ;
           $arr_inrm[]=$_POST['inrm'] ;
        }

        $setting_uid=ENGINE()->save_temp_setting(['arr_inrm'=>$arr_inrm]) ;
        //damp_array($arr_inrm,1,-1);

        $recs=execSQL('select pkey,parent,concat(number," ",obj_name) as obj_name from '.$table_vpf.' order by pkey',0) ;
        convert_list_to_tree2($recs,$arr) ;
        $arr[1]['name']='ВПФ' ;

        //$org_name=($org_id)? PERSONAL()->get_full_dep_name_by_dep_id($org_id):'' ;
        //$otdel_name=PERSONAL()->get_full_dep_name_by_dep_id($dep_id) ;
        //$work_name=($working_id)? execSQL_value('select obj_name from list_workings where pkey='.$_POST['working_id']):'' ;
        //$work_name=($working_id)? execSQL_value('select obj_name from view_IL_works where id='.$_POST['working_id']):'' ;
        if (_sizeof($arr_inrm)>1) {?><div id="panel_mode">&nbsp;<input type="radio" id="check_mode" name=check_mode value="set" checked> Добавить выбранные ВПФ <input type="radio" id="check_mode" name=check_mode value="unset"> Удалить выбранные ВПФ</div><div class="clear"></div><?}
        ?><div id="panel_search">Поиск: <input type="text" id="plugins4_q" value="" class="input"></div><?
        // если ИНРМ не один - то режим добавления/удаления ВПФ

        ?><div class="clear"></div>
          <div id="panel_info">
              <?if ($otdel_name){?>Организация/Подразделение: <strong><?echo $otdel_name?></strong><br><?}?>
              <?if ($work_name){?>Должность: <strong><?echo $work_name?></strong><br><?}?>
          </div>
          <div id="panel_vpf_tree"><? $this->generate_tree($arr,$arr_checked_ids) ; ?></div>
       </div>
        <div class="center"><button id="save_checked_items" source="<?echo $source?>">Сохранить</button></div>
       <script type="text/javascript">jQuery(document).ready(function()
        {

          var to = false;
          $j('#plugins4_q').keyup(function ()
          { if(to) { clearTimeout(to); }
            to = setTimeout(function ()
            { var v = $j('#plugins4_q').val();
              $j('#panel_vpf_tree').jstree(true).search(v);
            }, 250);
          });

            $j('#panel_vpf_tree').jstree({
              "plugins" : [ "wholerow", "checkbox",'search' ],
              "checkbox" : {"keep_selected_style" : true,'whole_node':false,'tie_selection':false}
            });

          $j('#save_checked_items').on('click',function()
          { var selectedElmsIds = [];
            var selectedElms = $j('#panel_vpf_tree').jstree("get_checked", true);
            //console.log('selectedElms '+selectedElms) ;
            $j.each(selectedElms, function() {
                selectedElmsIds.push(this.id);
            });
            //console.log('selectedElmsIds '+selectedElmsIds) ;
            var mode='as_is' ;
            var source=$j(this).attr('source') ;
            if ($j('#check_mode').length) mode=$j('#check_mode:checked').val() ;

            send_ajax_request({cmd:'ot/save_checked_vpf',source:source,items:selectedElmsIds,setting_uid:"<?echo $setting_uid?>",mode:mode}) ;
            console.log(selectedElmsIds) ;
          }) ;


        });</script>
       <style type="text/css">
            div#panel_select_section_vpf select{width:290px;font-size:14px;}
            div#panel_select_item_vpf{height:600px;overflow-y:scroll;font-size:14px;}
            #panel_search{margin-bottom:10px;float:left}
            #panel_mode{margin-bottom:10px;float:left}
            #panel_info{margin-bottom:10px;}
            #panel_vpf_tree{margin-bottom:10px;}
            #plugins4_q{padding:4px; border-radius:4px; border:1px solid silver;width:250px;}
       </style>
       <?

      $this->add_element('show_modal_window','HTML',array('title'=>'Настройка вредных производственных факторов','width'=>'1200px')) ;
    }

    function generate_tree($recs,$checked_ids)
    {  if (_sizeof($recs)) foreach($recs as $id=>$item)
        { ?><ul>
               <li data-jstree='{ "opened" : <?echo ($id==1)? 'true':'false'?>,"checked":<?echo (isset($checked_ids[$id]))? 'true':'false'?>}' id="item_<?echo $id?>"><?echo $item['name']?>
               <? unset($item['name']) ;
                  if (_sizeof($item)) $this->generate_tree($item,$checked_ids) ;
               ?>
               </li>
            </ul><?
        }
    }

    function save_checked_vpf()
    {   if (!$_POST['setting_uid']) return ;
        //damp_array($_POST,1,-1) ;
        $mode=($_POST['mode'])? $_POST['mode']:'' ;
        $source=($_POST['source'])?:'pmo' ;
        $table_vpf=($source=='opo')? 'opo_list_vpf':'list_vpf'  ;
        $table_inrm_vpf=($source=='opo')? 'opo_inrm_vpf':'list_rm_fvp'  ;

        $setting_uid=ENGINE()->load_temp_setting($_POST['setting_uid']) ;
        //damp_array($setting_uid);

        ob_start() ;
        $arr=[] ;
        if (_sizeof($setting_uid['arr_inrm'])) foreach($setting_uid['arr_inrm'] as $inrm) $arr[]='"'.$inrm.'"' ;
        $recs_inrm=execSQL('select t1.inrm,t1.vpf_id,t1.pkey as id,t2.number 
                            from '.$table_inrm_vpf.' t1 
                            left join '.$table_vpf.' t2 on t2.pkey=t1.vpf_id
                            where t1.inrm in ('.implode(', ',$arr).')
                            order by t2.number
                            ',0,1) ;

        $arr_exists_inrm=array() ;
        if (_sizeof($recs_inrm)) foreach($recs_inrm as $rec) $arr_exists_inrm[$rec['inrm']][$rec['vpf_id']]=$rec['id'] ;

        $arr_vpf=execSQL_row('select pkey,number from '.$table_vpf) ;

        $arr_vpf_to_set=array() ;
        if (_sizeof($_POST['items'])) foreach($_POST['items'] as $fvp_name) $arr_vpf_to_set[(int)str_replace('item_','',$fvp_name)]=1 ;
        $result=array() ;
        if (_sizeof($setting_uid['arr_inrm'])) foreach($setting_uid['arr_inrm'] as $inrm)
        {  $irnm_fvp=$arr_exists_inrm[$inrm] ;
           switch($mode)
           { case 'as_is': // удаляем из списка те ВПФ, что нет в списке выбранных
                           if (sizeof($irnm_fvp)) foreach($irnm_fvp as $vpf_id=>$vpf_rm_id) if (!isset($arr_vpf_to_set[$vpf_id]))
                           { if ($vpf_rm_id)
                             { execSQL_update('delete from '.$table_inrm_vpf.' where pkey='.$vpf_rm_id) ;
                               echo $inrm.': удален ВПФ <strong>'.$arr_vpf[$vpf_id].'</strong> <br>' ;
                               $result['remove']++ ;
                             }
                           }
                           // добавляем отсутствующее
                           foreach($arr_vpf_to_set as $vpf_id=>$enabled) if (!isset($irnm_fvp[$vpf_id]))
                           { multiSQL_insert($table_inrm_vpf)->append(array('clss'=>235,'inrm'=>$inrm,'vpf_id'=>$vpf_id,'c_data'=>time(),'r_data'=>time(),'parent'=>1,'enabled'=>1)) ;
                             echo $inrm.': добавлен ВПФ <strong>'.$arr_vpf[$vpf_id].'</strong>'.$vpf_id.'<br>' ;
                             $result['insert']++ ;
                           }
                           break ;
             case 'set':   foreach($arr_vpf_to_set as $vpf_id=>$enabled) if (!isset($irnm_fvp[$vpf_id]))
                           { multiSQL_insert($table_inrm_vpf)->append(array('clss'=>235,'inrm'=>$inrm,'vpf_id'=>$vpf_id,'c_data'=>time(),'r_data'=>time(),'parent'=>1,'enabled'=>1)) ;
                             echo $inrm.': добавлен ВПФ <strong>'.$arr_vpf[$vpf_id].'</strong> <br>' ;
                             $result['insert']++ ;
                           }
                           break ;
             case 'unset': foreach($arr_vpf_to_set as $vpf_id=>$enabled) if (isset($irnm_fvp[$vpf_id]))
                           { execSQL_update('delete from '.$table_inrm_vpf.' where inrm="'.$inrm.'" and vpf_id='.$vpf_id) ;
                             echo $inrm.': удален ВПФ <strong>'.$arr_vpf[$vpf_id].'</strong> <br>' ;
                             $result['remove']++ ;
                           }
           }
        }
        multiSQL_insert($table_inrm_vpf)->flush() ;

        //$rec_event=EVENTS()->get_event_by_id($GLOBALS['LS_esmo_PMO_event']) ;
        //$obj_event=EVENTS()->get_event_obj_by_id($GLOBALS['LS_esmo_PMO_event']) ;
        //$obj_event->check_pmo_len_for_status_7_8($rec_event,['arr_inrm'=>$setting_uid['arr_inrm']]) ;

        $text=ob_get_clean() ;
        ?><textarea style="width:100%;height:200px;"><?
        echo strip_tags(str_replace('<br>',"\n",$text)) ;
        ?></textarea><?
        $this->add_element('show_modal_window','HTML',array('title'=>'Настройка вредных производственных факторов','_width'=>'1200px','after_close_update_page'=>1)) ;

        if (_sizeof($result))
        {   ?><div class="center"><button class="cancel">Закрыть</button></div><?
            $this->add_element('show_modal_window','HTML',array('title'=>'Настройка вредных производственных факторов','_width'=>'1200px','after_close_update_page'=>1)) ;
        }
        else $this->add_element('show_notife','Изменений не обнаружено',array('color'=>'green')) ;
        //$this->update_page=1 ;
    }

    // назначение балла для ВПФ
    function set_vpf_ball_by_pkey()
    { $ball=$_POST['ball'] ;
      $id=(int)$_POST['id'] ;
      if ($ball and $id)
      {  update_rec_in_table('list_workings_fvp',array('ball'=>$ball),'pkey='.$id) ;
         $this->add_element('show_notife','Сохранено',array('type'=>'info')) ;
      }
    }

    function remove_file_doc()
    {
        $id=(int)$_POST['file_id'] ;
        if ($id) execSQL_update('delete from files where pkey='.$id) ;
        $this->update_page=1 ;
    }

    function save_vpf()
    {   // damp_array($_POST) ;
        $source=($_POST['source'])?:'pmo' ;
        $table_vpf=($source=='opo')? 'opo_list_vpf':'list_vpf'  ;

        //$this->add_element('show_modal_window','HTML',array('title'=>'Настройка вредных производственных факторов','_width'=>'1200px','after_close_update_page'=>1)) ;
        if (_sizeof($_POST['recs_vpf'])) foreach($_POST['recs_vpf'] as $pkey=>$data)
        { update_rec_in_table($table_vpf,$data,'pkey='.$pkey) ;
        }
        $this->update_page=1 ;
    }

    function get_panel_vpf_apeend_child()
    {
      FORM()->form_open(['post_array_name'=>'data']) ;

        FORM()->row_open() ;
        FORM()->filter_section_input_text('number','Номер ВПФ',4,['required'=>1,'value'=>'']);
        FORM()->section_select(['name'=>'period','title'=>'Период ОПО','recs'=>OPO()->arr_opo_len,'col_count'=>7]);
        FORM()->filter_section_textarea('obj_name','Раздел ВПФ',11,['required'=>1,'value'=>'']);
        FORM()->filter_section_textarea('comment','Комментарии',11,['required'=>0,'value'=>'']);
        FORM()->row_close() ;

        FORM()->button('Добавить','ot/vpf_apeend_child',['class'=>'v2','parent'=>$_POST['parent']]) ;

      $this->add_element('show_modal_window','HTML',array('title'=>'Добавление вредных производственных факторов','_width'=>'1200px','_after_close_update_page'=>1)) ;
	}

   function get_panel_vpf_edit_child()
    { $rec=execSQL_van('select * from opo_list_vpf where pkey='.$_POST['vpf_id']) ;
        //print_2x_arr([$rec]);
       // echo 'period='.$rec['period'].'<br>' ;
      FORM()->form_open(['post_array_name'=>'data']) ;

        FORM()->row_open() ;
        FORM()->filter_section_input_text('number','Номер ВПФ',4,['required'=>1,'value'=>$rec['number']]);
        FORM()->section_select(['name'=>'period','title'=>'Период ОПО','recs'=>OPO()->arr_opo_len,'col_count'=>7,'cur_value'=>$rec['period'],'value'=>$rec['period']]);
        FORM()->filter_section_textarea('obj_name','Раздел ВПФ',11,['required'=>1,'value'=>$rec['obj_name']]);
        FORM()->filter_section_textarea('comment','Комментарии',11,['required'=>0,'value'=>$rec['comment']]);
        FORM()->row_close() ;

        FORM()->button('Сохранить изменения','ot/vpf_edit_child',['class'=>'v2','vpf_id'=>$_POST['vpf_id']]) ;

      $this->add_element('show_modal_window','HTML',array('title'=>'Добавление вредных производственных факторов','_width'=>'1200px','_after_close_update_page'=>1)) ;
	}

	function vpf_apeend_child()
    {   //damp_array($_POST,1,-1);
        //$this->add_element('show_modal_window','HTML',array('title'=>'Добавление вредных производственных факторов','_width'=>'1200px','after_close_update_page'=>1)) ;
        $data=$_POST['data'] ;
        $data['parent']=$_POST['parent'] ;
        TREE('opo_list_vpf')->full_parent_levels_to_rec($data);
        adding_rec_to_table('opo_list_vpf',$data) ;
        $this->update_page=1 ;
	}

	function vpf_edit_child()
    {
        $data=$_POST['data'] ;
        update_rec_in_table('opo_list_vpf',$data,'pkey='.$_POST['vpf_id']) ;
        $this->update_page=1 ;
	}




}
