<?php
class report_poll_section_stats_angulargauge extends c_report_graf
{
 var $title='Результаты опроса (Рейтинг)' ;
 var $question_name='' ;

 function __construct($create_options=array())
 { parent::__construct($create_options);
   //if ($this->filter['section_id']) $this->section_id=$this->filter['section_id'] ;
   //print_r($this) ;
 }

 function setting()
       { list($arr_orgs_ids,$arr_otdel_ids,$arr_works_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter) ;

         $_usl=array() ;
         $_usl[]='not t2.parent is null' ;
         if ($this->personal_id)    $_usl[]='t1.personal_id='.$this->personal_id ;
         if ($this->event_id)       $_usl[]='t1.event_id='.$this->event_id ;

         $usl_theme_select=(_sizeof($_usl))? implode(' and ',$_usl):'1' ;

        if ($this->filter['theme_id'])
        {   $questions_ids=[] ;
            if (!_sizeof($this->filter['section_ids'])) $section_ids=execSQL_line('select pkey as id from poll_themes where parent2='.$this->filter['theme_id'].' ') ;
            else if ($this->section_id)
            {   $childs_sections=TREE('poll_themes')->get_list_child($this->section_id) ;
                $childs_sections[$this->section_id]=1 ;
                $section_ids=array_keys($childs_sections) ;
            }
            else  $section_ids=array_keys($this->filter['section_ids']) ;

            if (_sizeof($section_ids)) $questions_ids=execSQL_line('select pkey as id from poll_questions where parent in ('.implode(',',$section_ids).')') ;
            if (_sizeof($questions_ids)) $_usl[]='question_id in ('.implode(',',$questions_ids).')';
        }
        if (_sizeof($this->filter['org_ids']))    $_usl[]='_org_id in ('.implode(',',array_keys($this->filter['org_ids'])).')' ;
        if (_sizeof($this->filter['otdel_ids']))  $_usl[]='_otdel_id in ('.implode(',',array_keys($this->filter['otdel_ids'])).')' ;

        $this->usl_poll_result=(_sizeof($_usl))? implode(' and ',$_usl):'1' ;

         // получаем список всех ТЕМ вопросов, которые задавались сотруднику
         $theme_recs=execSQL('select t4.pkey as theme_id,t4.obj_name as theme_name,
                             t3.pkey as section_id,t3.obj_name as section_name
                             from poll_result t1 
                             left join poll_questions t2 on t2.pkey=t1.question_id 
                             left join poll_themes t3 on t3.pkey=t2.parent 
                             left join poll_themes t4 on t4.pkey=t3.parent2 
                             where '.$usl_theme_select.'   
                             group by t4.pkey,t3.pkey
                             order by t4.indx,t3.indx
                             ',0,1) ;
          $arr_themes=array() ; $arr_themes_section=array() ;
         if (_sizeof($theme_recs)) foreach($theme_recs as $rec)
         {  $arr_themes[$rec['theme_id']]=$rec['theme_name'] ;
            $arr_themes_section[$rec['theme_id']][$rec['section_id']]=$rec['section_name'] ;

         }
             //damp_array($arr_themes);

     $this->form_open() ;
     $this->row_open() ;
     $this->fieldset_open() ;
     if (!$this->personal_id) $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
     if (!$this->personal_id) $this->filter_section_select_multiple('otdel_ids','Подразделение:',2,$arr_otdel_ids) ;
     //$this->filter_section_select('view_mode','Обзор:',2,$this->view_mode,array('nospace_element'=>1)) ;
     //$this->filter_section_select('cnt_days','Обзор за:',2,$this->cnt_days,array('nospace_element')) ;
     $this->row_close() ;
     $this->panel_buttons();
     $this->fieldset_close() ;
     $this->form_close() ;
  }

  function prepare_data($recs=[])
  {
      //if (MEMBER()->personal_viewer_name) $usl_str=' and personal_id in (select pkey from '.MEMBER()->personal_viewer_name.')' ;
      $data['question_name']=execSQL_value('select obj_name from view_poll_questions where pkey='.$this->filter['question_id']) ;

      $data['avg_answer_ball']=execSQL_value(
              'select avg(answer_ball) as avg_answer_ball
               from poll_result 
               where question_id='.$this->filter['question_id'].' 
              ',0,1) ;

      return $data;
  }

  function radar_chart($data=[])
  {   ?><div id="<?echo $this->graf_div_id?>" class="radar_chart"></div>
         <script type="text/javascript">
             $j(document).ready(function()
             {
                 let js_<?=$this->report_UID?> = new FusionCharts({
                     type: 'angulargauge',
                     renderAt: "<?echo $this->graf_div_id?>",
                     width: '500',
                     height: '300',
                     dataFormat: '<?echo (_sizeof($data))? 'json':'jsonurl'?>', // dataSource будут подготвлены методом view_as_FusionCharts_JSON
                     dataSource: '<?echo (_sizeof($data))? json_encode($data,JSON_UNESCAPED_UNICODE):$this->get_services_upload_json_data_url()?>' // учесть возможность передачи параметров отчета скрипту
                 });

                 js_<?=$this->report_UID?>.render();
             });
         </script>
    <?
  }

  function prepare_FusionCharts_data($data)
   {
       $chart=['caption'=>$data['question_name'],
               'captionOnTop'=>0,
               'alignCaptionWithCanvas'=>1,
               'captionHorizontalPadding'=>10,
               'captionFontSize'=>11,
               'captionFontBold'=>0,
               "theme"=>"fusion",
               "use3DLighting"=>"0",
               "showShadow"=>"0",
               "showlegend"=>"1",
               "showvalue"=>"1",
               "showpercentvalues"=>"1",
               "legendposition"=>"bottom",
               "lowerlimit"=>"0",
               "upperlimit"=>"5",
               "valueFontSize"=>"18",
               "valueFontBold"=>"1",
               //"numbersuffix"=>"балл.",
               //"animation"=>"3",
               "showtooltip"=>"1",
               "showBorder"=>"0",
               "bgColor"=>"#ffffff",
               "pieRadius"=>"50",

                //"origw"=>"400",
                //"origh"=>"300",
                "gaugeOriginX"=>"195",
                "gaugeOriginY"=>"190",
                "gaugeOuterRadius"=>"150", // радиус шкалы
               //"palettecolors"=>"#0050aa"
               ] ;

       $colorrange=['color'=>[["minvalue"=>"0","maxvalue"=>"1","code"=>"#fe453d"],
                              ["minvalue"=>"1","maxvalue"=>"2","code"=>"#F2726F"],
                              ["minvalue"=>"2","maxvalue"=>"3","code"=>"#FFC533"],
                              ["minvalue"=>"3","maxvalue"=>"4","code"=>"#62B58F"],
                              ["minvalue"=>"4","maxvalue"=>"5","code"=>"#4d9172"],
                             ]
                    ] ;
       $dials=['dial'=>[['value'=>$data['avg_answer_ball']]]] ;

       $arr_json=[] ;
       $arr_json['chart']=$chart ;
       $arr_json['colorrange']=$colorrange ;
       $arr_json['dials']=$dials ;

       return($arr_json) ;
   }

  // основная функция в которорой будет фрмироваться тело отчета
  function HTML_report_body($options=array())
  {  // данные готовим только для отладки, в режиме jsonurl данные будут подгружены через сервис
     $arr_json=[] ;
     //$data=$this->prepare_data() ;
     //$arr_json=$this->prepare_FusionCharts_data($this->prepare_data()) ;
     //damp_array($data);
     //damp_array($arr_json);
     $this->radar_chart($arr_json) ;
  }


 function view_as_FusionCharts_JSON()
 {  // получаем статистику в табличном виде
   $data=$this->prepare_data() ;
   $arr_json=$this->prepare_FusionCharts_data($data) ; // преобразуем таблиццу в JSON для FusionCharts
   return($arr_json) ;
 }

}

?>
