<?php
namespace catchAdmin\api\service;

use catchAdmin\tag_history\model\Dormitory;

class dispose
{
    private $redis;
    private $stations="stations";
    public function __construct($redis){

        $this->redis=$redis;

    }
    
    // public function computeData($data){
    //     debug_log("InAndOUT","基站:".$data['mac'] .' label :'.$data['label']);
    //     debug_log("InAndOUT","新数据:".json_encode($data));
    //     $hashKey=$data['mac'].'station';
    //     $key=$data['label'];
    //     $list=[];
    //     $length=0;
    //     $res= $this->selectHash($hashKey,$key);
       
    //     if($res==false){
    //         debug_log("InAndOUT","redis没有数据,存入新数据");
    //         array_push($list,$data);
    //         debug_log("InAndOUT","当前数据队列",json_encode($list));
            
    //     }else{
    //         debug_log("InAndOUT","redis初始数据 :".json_encode($res));
    //         $list=$res;
    //         debug_log("InAndOUT","上次上报的数据 :".json_encode($list[count($list)-1],true));
           
    //         // if(($data['report_time']-$list[count($list)-1]['report_time'])>=120){
    //         //     debug_log("InAndOUT","上报次数间隔超过120s,清空redis缓存,从新存入数据");
    //         //     $list=[];
    //         //     array_push($list,$data);
    //         // }else{
    //             $list=$res;
    //             array_push($list,$data);
               
    //             //按照个数
    //             while(count($list)>5){
    //                 array_shift($list);
    //             }


    //        // }  

    //     }
    //     //数据
    //     $count=count($list);
    //     debug_log("InAndOUT","当前数据队列 :".json_encode($list));
    //     debug_log("InAndOUT","新数据长度 :".$count);
    //     //现在的数据长度

      
    //     //获取配置
    //     $config= $this->selectHash("anbang_four_wire",$data['mac']);
        

    //     if(empty($config)){
    //         debug_log("InAndOUT","没有配置");
    //     }else{
    //         debug_log("InAndOUT","配置参数为:".json_encode($config));

    //     }
    //     $sortlist=  $this->sortlist($list);
       
        
    //     $data["rssi1"]=$sortlist[0];
    //     $data["rssi2"]=$sortlist[1];
    //     $data["rssi3"]=$sortlist[2];
    //     $data["rssi4"]=$sortlist[3];
    //     debug_log("InAndOUT","计算出的平均数据 :".json_encode($data));
    //     //保存到hash中
    //     debug_log("InAndOUT","存入redis缓存的数据 :".json_encode($list));
    //     $this->setHash($hashKey,$key,$list);
    //     debug_log("InAndOUT","=======================================");
    //     return $data;
    // }


    public function check_data($data){
        $this->setStations($data['mac']);
        $res='';
        $hashKey=$data['mac'].'station';
        $key=$data['label'];
        $old_data=$this->selectHash($hashKey,$key);
        if($data["rssi1"]==90&&!empty($old_data)){
            if($old_data["rssi1"]<90){  
                $data["rssi1"]=$old_data["rssi1"]+8;
                $data["rssi1"]= $data["rssi1"]>90 ? 90:$data["rssi1"];
                $res=$res."rssi1 ";
            }
        }
        if($data["rssi2"]==90&&!empty($old_data)){
            if($old_data["rssi2"]<90){
                $data["rssi2"]=$old_data["rssi2"]+8;
                $data["rssi2"]= $data["rssi2"]>90 ? 90:$data["rssi2"];
                $res=$res."rssi2";
            }
        }
        $this->setHash($hashKey,$key,$data);
        return $data;
    }













    //计算结果设计
    public function computeResout($data){
  
        debug_log("InAndOUT","=======================================");
        debug_log("InAndOUT",'接收新数据'.json_encode($data));   
        debug_log("InAndOUT","=======================================");    
       $res=0;
       //进出
    

       $hashkey='res'.$data['mac'];
       $key=$data['label'];
       //存入redis的数据
       $json_list= $this->selectHash($hashkey,$key);
       //最新时间
       $time=$data['report_time'];
       //进出结果
       $inAndOut=0;
       //是否参与计算
       $calculate=true;
       
       if($data['rssi1']==$data['rssi2']){
            $calculate=false;
       }
       $t1s= $data['rssi1']-$data['rssi2'];
       if(abs($t1s)<3){
          debug_log("InAndOUT","差值小于3不做计算");
          $calculate=false;
       }

       if($calculate==false){
            if(!$json_list){
                $arr=[
                    "a"=>[],
                    'status'=> ['time'=>null,'dirt'=>null],
                    "time"=>$time, //最新时间 
                    "in_and_out"=>0   //进出结果
                ];   
            }else{
                $json_list['time']=$time;
            }
            $this->setHash($hashkey,$key,$json_list);
            return;
       }

      
       if($data['rssi1']<$data['rssi2']){
            $res=1;  
       }
       if($data['rssi1']>$data['rssi2']){
            $res=2;  
       }
    
       if(!$json_list){
       
            $arr=[
                "a"=>[['time'=>$time,'dirt'=>$res]],
                'status'=> ['time'=>null,'dirt'=>null],
                "time"=>$time, //最新时间
                "in_and_out"=>0
            ];
            debug_log("InAndOUT","数据不存在,直接存储新数据".json_encode($arr));
            $this->setHash($hashkey,$key,$arr);
            return;
       }else{


         $resArray=['time'=>$data['report_time'],'dirt'=>$res];
         debug_log("InAndOUT","缓存的数据".json_encode($json_list));
         $s=$json_list;
         //数据列表
         $list=$s['a'];
        //进出结果
         $inAndOut=$s["in_and_out"];
        //状态
         $status=$s['status'];
         array_push($list,$resArray);
        while(count($list)>5){
                array_shift($list);
                debug_log("InAndOUT","数据超过5条,剔除一条旧数据");
        }
        debug_log("InAndOUT","当前队列数据:".json_encode($list));
         $front=0;
         $back=0;
        if(count($list)>2){
            //
            debug_log("InAndOUT","当前队列超过两条可以计算前后:".count($list));
            //校验权柄
                foreach($list as $item){
                    if($item['dirt']==1){   
                        $front+=1;
                    }
                    if($item['dirt']==2){
                        $back+=1;
                    }
                }
                 $res=$front>$back?1:2;

            if(empty($status['dirt'])){
                $status['dirt']= $res;
                $status['time']= $resArray['time'];
                debug_log("InAndOUT","初始化状态为:".json_encode($status));
            }else{

                //判断是否连贯
               $IS_OK=true;
               $res=0;
               $reverse=array_reverse($list);
               $res=$reverse[0]['dirt'];
               foreach($reverse as $aitem){
                   if($aitem['dirt']!=$res){
                      $IS_OK=false;
                   } 
               }
            //    if(($reverse[0]['dirt']==$reverse[1]['dirt'])&&($reverse[1]['dirt']==$reverse[2]['dirt'])){
            //       $res=$reverse[0]['dirt'];
            //       $IS_OK=true;
            //    }

                //进行保存
                if($res!=$status['dirt']&&$IS_OK){
                  
                    // if(!empty($status['status']['dirt'])){

                    //     if($resArray['time']-$status['status']['time']>5){

                            $data_array=[];
                            $data_array[]=[
                                "label"=>$data['label'],
                                'time'=>$resArray['time'],
                                'dirt'=> $status['dirt']==1?1:2 //1是进 2是出
                            ];
                            $inAndOut=$status['dirt']==1?1:2;
                            $url_data=[
                                "mac"=>$data['mac'],
                                "data"=>$data_array
                            ];
                            //设定最后结果
                            $this->set_time_results($data['mac'],$data['label'],$resArray['time'],$inAndOut);
                            //推送远程数据
                            $this->getRemoteData($url_data);
                            //清除缓存数据
                            $this->get_label_history(3,$data['mac'],$data['label']);
                            $this->temporary_label($this->redis,$data['label'],2);
                          $status['dirt']=$res;
                          $status['time']=$time;

                }else{
                   
                    debug_log("InAndOUT","无计算结果",json_encode($status));
                }
                

            }
         }
            $arr=array(
                "a"=>$list,
                'status'=>$status,
                "time"=>$time,
                "in_and_out"=>$inAndOut
            );
            debug_log("InAndOUT","存入缓存中:".json_encode($arr));
            $this->setHash($hashkey,$key,$arr);
            debug_log("InAndOUT",'操作结束');
       }

    }



    //获取所有基站
    public function getStations(){
        $key=$this->stations;
        $list= $this->redis->hKeys($key);
        return $list;
    }
    //存入基站号
    public function setStations($Stations){
        $key=$this->stations;
        if(!$this->redis->hExists($key,$Stations)){
            $this->redis->hSet($key,$Stations,0);
        }  
    }


    //排序
    // public function sortlist($list){
    //     $list01=[];
    //     $list02=[];
    //     $list03=[];
    //     $list04=[];
    //     debug_log("InAndOUT","排序的数据:".json_encode($list));
    //     foreach($list as $item){
    //        array_push($list01,$item['rssi1']);
    //        array_push($list02,$item['rssi2']);
    //        array_push($list03,$item['rssi3']);
    //        array_push($list04,$item['rssi4']);
    //     }

    //     if(count($list)>=3){
    //         sort($list01);
    //         sort($list02);
    //         sort($list03);
    //         sort($list04);
    //         array_pop($list01);
    //         array_pop($list02);
    //         array_pop($list03);
    //         array_pop($list04);
    //         array_shift($list01);
    //         array_shift($list02);
    //         array_shift($list03);
    //         array_shift($list04);
    //     }
    //     debug_log("InAndOUT","排序后的队列:".json_encode($list01));
    //     debug_log("InAndOUT","排序后的队列:".json_encode($list02));
    //     debug_log("InAndOUT","排序后的队列:".json_encode($list03));
    //     debug_log("InAndOUT","排序后的队列:".json_encode($list04));
    //     $rssi1= array_sum($list01)/count($list01);
    //     $rssi2= array_sum($list02)/count($list02);
    //     $rssi3= array_sum($list03)/count($list03);
    //     $rssi4= array_sum($list04)/count($list04);
    //     $res=[$rssi1,$rssi2,$rssi3,$rssi4];
    //     debug_log("InAndOUT","结算后的结果:".json_encode($res));
    //     return $res;
    // }
/**
 * 获取远程推送的数据
 *
 * @param [type] $url
 * @param [type] $data
 * @return void
 */

public function getRemoteData($data){

    $key="push_data";
    $redis=$this->redis;
    $redis->Rpush($key,json_encode($data));
    
}
/**
 * 历史标签信号
 *
 * @return void
 */
public function set_label_history($data){
    $MAC=$data["mac"];
    $key=$MAC."_label_history";
    $head=$data['label']."_head";
    $tail=$data["label"]."_tail";
    $frontMaxKey=$data['label'].'_frontMax';
    $backMaxKey=$data['label'].'_backMax';
    $frontMax=null;
    $backMax=null;
   
    //保存头部
    $head_data= $this->selectHash($key,$head);
    $tail_data=$this->selectHash($key,$tail);
    //保存朝外的信号最大值
    $frontMax=$this->selectHash($key,$frontMaxKey);
    //保存朝内的信号最大值
    $backMax=$this->selectHash($key,$backMaxKey);
    if(empty($frontMax)){
        $frontMax=$data["rssi1"];
    }else{
        $frontMax=$data["rssi1"]<$frontMax?$data["rssi1"]:$frontMax;    
    }
    if(empty($backMax)){
        $backMax=$data["rssi2"];
    }else{
        $backMax=$data["rssi2"]<$backMax?$data["rssi2"]:$backMax;    
    }
    $this->setHash($key,$frontMaxKey,$frontMax);
    $this->setHash($key,$backMaxKey,$backMax);

    if(!empty($tail_data)){
        if(($data["report_time"]-$tail_data[count($tail_data)-1]["report_time"])>6){
          $head_data=[];
          $tail_data=[];
        }
     }

    if(empty($head_data)||count($head_data)<3){
       
        $head_data=empty($head_data)?[]: $head_data;
        
        array_push($head_data,$data);
        $this->setHash($key,$head,$head_data);
    }
    //保存尾部标签数据
    
    $tail_data=empty($tail_data)?[]: $tail_data;
    array_push($tail_data,$data);
    while(count($tail_data)>3){
        array_shift($tail_data);
    }
    $this->setHash($key,$tail,$tail_data);
}
/**
 * 获取基站
 *
 * @param [type] $type  1 头部  2 尾部 3清空
 * @param [type] $mac  
 * @param [type] $label 
 * @return void
 */
public function get_label_history($type,$mac,$label){
 
    $key=$mac."_label_history";
    $head=$label."_head";
    $tail=$label."_tail";
    $frontMaxKey=$label.'_frontMax';
    $backMaxKey=$label.'_backMax';
    if($type==1){
        $head_data= $this->selectHash($key,$head);
        return $head_data;
    }
    if($type==2){
        $tail_data= $this->selectHash($key,$tail);
        return $tail_data;
    }
    if($type==3){
        debug_log("InAndOUT","清空头部和尾部历史:".$mac." ".$label);
        $this->delHash($key,$head);
        $this->delHash($key,$tail);
        $this->delHash($key,$frontMaxKey);
        $this->delHash($key, $backMaxKey);
    }
    if($type==4){
        $frontMax= $this->selectHash($key,$frontMaxKey);
        return $frontMax;
    }
    if($type==5){
        $backMax= $this->selectHash($key,$backMaxKey);
        return $backMax;
    }




}
/**
 * 二次生成进出
 *
 * @return void
 */
public function second_create_direction($mac,$label){
    debug_log("second_dirt","==============mac:".$mac."=======label".$label."================================");
    $key=$mac."_label_history";
    $head=$label."_head";
    $tail=$label."_tail";
    $head_dir=0;
    $tail_dir=0;
    $front=0;
    $behind=0;
    $res=0;
    $time=0;

   $head_data= $this->get_label_history(1,$mac,$label);
   $tail_data= $this->get_label_history(2,$mac,$label);
   debug_log("second_dirt","头部标签数据".json_encode($head_data));
   debug_log("second_dirt","尾部标签数据".json_encode($tail_data));
   if(empty($head_data)){
       return false; 
   }
   
   if(empty($tail_data)){
        return false; 
    }

   if(count($head_data)<3){
        return false;
   }
   foreach($head_data as $item){
        if($item["rssi1"]<$item["rssi2"]){
            $front+=1;
        }else{
            $behind+=1;
        }
   }
   
    $head_dir=$front>$behind?1:2;
    $front=0;
    $behind=0;

    foreach($tail_data as $item){
        if($item["rssi1"]<$item["rssi2"]){
            $front+=1;
        }else{
            $behind+=1;
        } 
        $time=$item['report_time'];
   }
   $tail_dir=$front>$behind?1:2;
   if($tail_dir== $head_dir){
        return false;
   }
   if($head_dir==1){
        $res=1;
   }else{
        $res=2;
   }
   //早上对"进寝室不做二次计算

   $start_time=strtotime(date("Y-m-d",time()));
   $end_time=$start_time+60*60*8;
   debug_log("second_dirt","判断的时间".date("Y-m-d H:i:s",$end_time));
   debug_log("second_dirt","判断的时间".date("Y-m-d H:i:s",$time));
   //当天结束之间 当天早上7点之前进寝室,不做二次计算
    if($time<$end_time&&$res==1){
        debug_log("second_dirt","当天早上7点之前进寝室,不做二次计算");
        return false;
    }
    $befor_res= $this->get_time_results($mac,$label,2);
  
    if(!empty($befor_res)){
        debug_log("second_dirt","间隔时间".json_encode($befor_res));
        if($befor_res['dir']==$res){
            $interval_time=$time-$befor_res["time"];
            debug_log("second_dirt","间隔时间".$interval_time);
            debug_log("second_dirt","间隔时间第一个小时,且方向相同 不做二次计算".$interval_time);
            if($interval_time<1*60*60){
                return false;
            }else{
                $frontMax= $this->get_label_history(4,$mac,$label);
                //$backMax=$this->get_label_history(5,$mac,$label);
                debug_log("second_dirt","标签.$label.的最朝外的最大值".$frontMax);
                if($frontMax>65){
                    debug_log("second_dirt","标签.$label.的最朝外的最小值大于65不参与计算");
                    return false;
                }


            }
        }

    }else{
        debug_log("second_dirt","数据为空,进行生成");
    }
    


   debug_log("second_dirt","最终结果".json_encode(["dirt"=>$res,"time"=>$time]));
    return ["dirt"=>$res,"time"=>$time];

}
/**
 * Undocumented function 基站配置
 *
 * @param [type] $mac
 * @return void
 */

public function get_station_config($mac){
     
     $Key="station_config";
     $mackey=$mac;
     $data=[
        "filter_signal"=>72,//过滤信号强度
        "history_filter_signal"=>82,//历史记录过滤的信号强度
        "init_data"=>3, //需要三条数据确定初始方向
        "change_data"=>5, //需要5条数据确定变换的方向
        "timeout"=>6,
        "second_create_res"=>[]//二次根据历史记录生成配置 数组中的参数配置  start_time,end_time,dir 1 前 2后;
     ];
     $config_data=$this->selectHash($Key,$mackey);
     if(!empty($config_data)){
        foreach($data as $key=>$value){
            $data[$key]=empty($config_data[$key])?$data[$key]:$config_data[$key];
        }
     }
    return $data;

}









    /**
     * function 设置存储结果的时间
     *
     * @param [type] $mac
     * @param [type] $label
     * @param [type] $time
     * @param [type] $dir 进出结果
     * @return void
     */
    public function set_time_results($mac,$label,$time,$dir){
        $mac_key=$mac."res_time";
        $array=["time"=>$time,"dir"=>$dir];
        $this->setHash($mac_key,$label,$array);
    }
    /**
     * function 获取存储结果的时间
     *
     * @param [type] $mac
     * @param [type] $label 
     * @param [type] $type 类型
     * @return void
     */
    public function get_time_results($mac,$label,$type=1){
        $mac_key=$mac."res_time";
        $data=$this->selectHash($mac_key,$label);
        if(empty($data)){
            return false;
        }
        if($type==1){
            return $data["time"];
        }else{
            return $data;
        }
    }



    //查询key hash
    public function selectHash($hashKey,$key){
        $res= $this->redis->hGet($hashKey,$key);
        if(empty($res)){
            return false;
        }else{
            return json_decode($res,true);
        }
    }

    public function setHash($hashKey,$key,$data){
       $this->redis->hSet($hashKey,$key,json_encode($data));
      
    } 
    public function delHash($hashKey,$key){
        $this->redis->hDel($hashKey,$key);
    }



    public function temporary_label($redis,$label,$type){

        return;
        $key="temporary_label";
        if($type==1){
            $res= $redis->hGet($key,$label);
            if($res==false){
                $redis->hSet($key,$label,1);
            }
        }else{
            $redis->hSet($key,$label,2);
        }

    }
    /**
     * 解析日志
     */
    public function analysisLog(){
        $path=app()->getRootPath()."runtime/log/2023-05-28/label_log.log";
        var_dump($path);
        var_dump(is_file($path));
        $file = fopen($path, "rb");
        debug_log("in_label","开始解析标签");
        $array=[];
        $readCvs=function($file){
            while (feof($file)===false) {
                # code...
                yield fgets($file);
            }
            fclose($file);

        };  
        debug_log("in_label","解析运行中");

    foreach ($readCvs($file) as $data) {
        
        if(strstr($data,"xsj")){
           
            $arr=  explode("{",$data);
                
            $data= json_decode("{".trim($arr[1]),true);
            debug_log("in_label",$data);
            if(!in_array($data['label'],$array)&&$data["rssi1"]>$data["rssi2"]){
                array_push($array,$data['label']);
            }
         }

    }

        foreach($array as $item){
            debug_log("in_label",$item);
        }
        debug_log("in_label","标签总数".count($array));
          


    }

    








}