<?php

namespace app\shared\controller;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Queue;
use think\queue\Job;
use app\shared\model\Electricity;
use app\shared\model\ElectricityLog;
use Electronic\Lvmi;
use app\task\controller\Task as TaskEle;
use app\shared\model\HouseOrder;
use app\shared\model\HouseOrderContinue;
class Task{

	//曼顿队列接收处理
	public function receiveOn($data=[],$immediately=0){
		if(isset($data['electronic_id'])){
			if($data['electronic_id']){
				$value=Electricity::where(['id'=>$data['electronic_id']])->field('id,mac,config,start_time,end_time,status,order_id,line,type')->find();
				if($value){
					$config=json_decode($value->config,1);
				  	$form=new \Electronic\Mandun($config);
				  	if($value->start_time<time()&&$value->status==0){
				  		$res=$form->sceneServicePuls($value->mac,$value->line,1);//副设备
				  		$config['log']=json_encode($res,JSON_UNESCAPED_UNICODE);
				  		$electric=Electricity::where(['id'=>$value->id])->find();
				  		$electric->config=json_encode($config);
				  		$electric->save();
				  		if($res['code']==0){
				  			///
				  			///曼顿自身BUG优化处理
				  		    $ret=$form->getBoxchannelsOc($value->mac,$value->line);
				  		    //设备不在线
				  		    if($ret['code']==1){
				  		    	if(!Cache::get('get_electonic_id'.$data['electronic_id'])){
				  		    		Cache::set('get_electonic_id'.$data['electronic_id'],4,86400);
				  		    	}
				  		    	if(Cache::get('get_electonic_id'.$data['electronic_id'])<=1){
									return false;
				  		    	}else{
				  		    		$num=Cache::get('get_electonic_id'.$data['electronic_id']);
				  		    		$num-=1;
				  		    		Cache::set('get_electonic_id'.$data['electronic_id'],$num,86400);
				  		    		self::receiveOn([
										'electronic_id'=>$data['electronic_id'],
									]);
									return false;
				  		    	}
				  		    }
				  		    $electric->status=1;
				  		    $electric->save();
                            (new ElectricityLog)->save([
								'order_id'=>$value->order_id,
								'electronic_id'=>$value->id,
								'mac'=>$value->mac,
								'line'=>$value->line,
								'des'=>"开始 ".date('Y-m-d H:i:s').' 取电',
							]);
					  	}else{
					  		if(!Cache::get('get_electonic_id_error'.$data['electronic_id'])){
			  		    		Cache::set('get_electonic_id_error'.$data['electronic_id'],2,7200);
			  		    	}
			  		    	if(Cache::get('get_electonic_id_error'.$data['electronic_id'])<=1){
								return false;
			  		    	}else{
			  		    		$num=Cache::get('get_electonic_id_error'.$data['electronic_id']);
			  		    		$num-=1;
			  		    		Cache::set('get_electonic_id_error'.$data['electronic_id'],$num,7200);
			  		    		self::receiveOn([
									'electronic_id'=>$data['electronic_id'],
								]);
								return false;
			  		    	}
					  	}
					  	
				  	}
				  	if(time()>$value->end_time&&$value->status!=2){
				  		//判断关电时间是否在线路内
				  		$is_door=Electricity::where(['mac'=>$value->mac,'line'=>$value->line])->where('start_time','<',time())->where('end_time','>',time())->count();
				  		if($is_door){
				  			return false;
				  		}
				  		$res=$form->sceneServicePuls($value->mac,$value->line,0);//副设备
                        (new ElectricityLog)->save([
							'order_id'=>$value->order_id,
							'electronic_id'=>$value->id,
							'mac'=>$value->mac,
							'line'=>$value->line,
							'des'=>"开始 ".date('Y-m-d H:i:s').' 关电',
						]);
						$electric=Electricity::where(['id'=>$value->id])->find();
				  		$electric->status=2;
				  		$electric->save();
				  	}
				  	if($immediately==1){
				  		//判断关电时间是否在线路内
				  		$is_door=Electricity::where(['mac'=>$value->mac,'line'=>$value->line])->where('start_time','<',time())->where('end_time','>',time())->count();
				  		if($is_door){
				  			return false;
				  		}
				  		$res=$form->sceneServicePuls($value->mac,$value->line,0);//副设备
                        (new ElectricityLog)->save([
							'order_id'=>$value->order_id,
							'electronic_id'=>$value->id,
							'mac'=>$value->mac,
							'line'=>$value->line,
							'des'=>"开始 ".date('Y-m-d H:i:s').' 关电',
						]);
						$electric=Electricity::where(['id'=>$value->id])->find();
				  		$electric->status=2;
				  		$electric->save();
				  	}
				}
			}
		}
	}
	//房间取电
	//其他
	public function handleOther($electronic_id=0,$start_time=0,$end_time=0,$book_type=1){
		//php think queue:listen --queue QYTASKELE
		$data=[
			'electronic_id'=>$electronic_id,
		];
		self::receiveOn($data);
	}

	//队列接收处理
	static public function receiveIntime($data=[]){
		if(isset($data['config'])&&isset($data['mac'])&&isset($data['line'])){
			$form=new \Electronic\Mandun($data['config']);
			$res=$form->sceneServicePuls($data['mac'],$data['line'],$data['status']);//副设备
			if($res['code']==0){
				$status_title=$data['status']==1?'取电':'关电';
	           (new ElectricityLog)->save([
					'order_id'=>0,
					'electronic_id'=>0,
					'mac'=>$data['mac'],
					'line'=>$data['line'],
					'des'=>"开始 ".date('Y-m-d H:i:s').$status_title,
				]);
			}           
		}
	}
	//门锁取电
	//处理及时
  public function handleIntime($config=[],$mac="",$line="",$status=1,$delay=0){
	    	$open=Cache::get('manduan_door_open_off'.$mac.'_'.$line);
	    	if($open){
	    		return false;
	    	}
	    	$data=[
				'class'=>base64_encode('\app\shared\controller\Task'),
				'action'=>'receiveIntime',
				'data'=>[
					'config'=>$config,
					'mac'=>$mac,
					'line'=>$line,
					'status'=>$status
				],
			];
	    	if($status==1){
	    		$status=0;
	    	}else{
	    		$status=1;
	    	}
	    	$form=new \Electronic\Mandun($data['data']['config']);
		    $res=$form->sceneServicePuls($data['data']['mac'],$data['data']['line'],$data['data']['status']);//副设备  
			if($res['code']==0){
				$status_title=$status==1?'取电':'关电';
	            (new ElectricityLog)->save([
					'order_id'=>0,
					'electronic_id'=>0,
					'mac'=>$mac,
					'line'=>$line,
					'des'=>"开始 ".date('Y-m-d H:i:s').$status_title,
				]);
				Cache::set('manduan_door_open_off'.$mac.'_'.$line,1,10);
			}
			$data['data']['status']=$status;
			$res=TaskEle::UrlHandleDelay($data,$delay);
  }
  //----------------------------------------------------------------------------------------
  //队列接收处理
	public function lvreceiveOn($data=[],$immediately=0){
		if(isset($data['electronic_id'])){
			if($data['electronic_id']){
				$value=Electricity::where(['id'=>$data['electronic_id']])->field('id,mac,config,start_time,end_time,status,order_id,line,type')->find();
				if($value){
					$config=json_decode($value->config,1);
				  	if($value->start_time<time()&&$value->status===0){
				  		$res=self::lvmiotherele($value->mac,$value->config,1);//绿米设备
				  		if($res['code']==0){
						  		$value->status=1;
						  		$value->config=json_encode($config);
						  		$value->save();
						        (new ElectricityLog)->save([
									'order_id'=>$value->order_id,
									'electronic_id'=>$value->id,
									'mac'=>$value->mac,
									'line'=>'绿米取电',
									'des'=>"开始 ".date('Y-m-d H:i:s').' 取电',
								]);
						}
    				}
				  	if(time()>$value->end_time&&$value->status!=2){
				  		$is_door=Electricity::where(['mac'=>$value->mac,'config'=>$value->config])->where('start_time','<',time())->where('end_time','>',time())->count();
				  		if($is_door){
				  			return false;
				  		}
				  		
				  		$res=self::lvmiotherele($value->mac,$value->config,0);//绿米设备
						if($res['code']==0){
							$value->status=2;
				  		    $value->save();
							(new ElectricityLog)->save([
								'order_id'=>$value->order_id,
								'electronic_id'=>$value->id,
								'mac'=>$value->mac,
								'line'=>'绿米关电',
								'des'=>"开始 ".date('Y-m-d H:i:s').' 关电',
							]);
						}
				  	}
				  	if($immediately==1){
				  		$res=self::lvmiotherele($value->mac,$value->config,0);//绿米设备
						if($res['code']==0){
							$value->status=2;
				  		    $value->save();
							(new ElectricityLog)->save([
								'order_id'=>$value->order_id,
								'electronic_id'=>$value->id,
								'mac'=>$value->mac,
								'line'=>'绿米关电',
								'des'=>"开始 ".date('Y-m-d H:i:s').' 关电',
							]);
						}
				  	}
				}
			}
		}
	}

	//绿米房间取电
	//其他
	public function lvhandleOther($electronic_id=0,$start_time=0,$end_time=0,$book_type=1){
	    $data['electronic_id']=$electronic_id;
	    self::lvreceiveOn($data);
	}
    //绿米队列接收处理13178取电方式
	static public function lvmireceiveIntime($data=[]){
		  $params=[];
    	$form=new Lvmi();
 		  $res=$form->controllerDevice($data['accessToken'],$data['params']);
	}
	//绿米取电13178取电方式
	//处理及时
    public function lvmihandleIntime($accessToken=null,$lvmi=[]){
		  $params1=[];
		  $params2=[];
		  $lvelectricty_line[]=$lvmi;
    	  foreach ($lvelectricty_line as &$vlm){
           $resources1=[];
           $resources2=[];
           $resource=$vlm['resource'];
           foreach ($resource as &$v){
              $resources1[]=[
                'resourceId'=>$v['resuors'],
                'value'=>$v['status'],
              ];
              if($v['status']==1){
		    		  $v['status']=0;
		       }else{
		    		  $v['status']=1;
		       }
		       $resources2[]=[
                'resourceId'=>$v['resuors'],
                'value'=>$v['status'],
              ];
           }
           $params1[]=[
            'subjectId'=>$vlm['dev_did'],
            'resources'=>$resources1,
           ];
           $params2[]=[
            'subjectId'=>$vlm['dev_did'],
            'resources'=>$resources2,
           ];
        }
        $delay=$lvmi['minute'];
	    $form=new Lvmi();
	 	$res1=$form->controllerDevice($accessToken,$params1);
        $data=[
			'class'=>base64_encode('\app\shared\controller\Task'),
			'action'=>'lvmireceiveIntime',
			'data'=>[
				'accessToken'=>$accessToken,
				'params'=>$params2,
			],
		];
		if($delay>0)
		$res2=TaskEle::UrlHandleDelay($data,$delay);
  }
  public function lvmiotherele($accessToken=[],$params=[],$status=0){
	   $params=json_decode($params,1);
	   if(isset($params['appKey'])){
	        return ['code'=>0];
	   }
  	   foreach ($params as &$vlm){
         foreach ($vlm['resources'] as &$v){
         	if($status==0){
              $state=$v['value']==0?1:0;
            }else if($status==-1){
              $state=0;
            }else{
              $state=$v['value'];
            }
            $v['value']=$state;
         }
       }
       sleep(1);
       $form=new Lvmi();
       $res=$form->controllerDevice($accessToken,$params);
       return $res;
  }

}


