<?php

namespace App\Http\Controllers\Server;

use App\Http\Controllers\Controller;
use GuzzleHttp\Pool;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Illuminate\Support\Facades\Redis;
use App\Http\Models\OrderModel;
use App\Http\Models\PollingModel;
use App\Http\Models\DiepollingpaymentModel;
use App\Http\Models\LivepollingpaymentModel;
use GatewayClient\Gateway;
use App\Http\Controllers\Common\Order_Redis;
use Illuminate\Support\Facades\DB;
use Log;

class Server extends Controller
{
  public function update_daili_money( $v) {
    //file_put_contents("success3.txt", "----------------------------\n".date('y-m-d H:i:s', time()).json_encode($v)."\n", FILE_APPEND);
    $user_info = DB::table('user')->where('Id', $v['form']['user_id'])->first();

    file_put_contents("success3.txt", date('y-m-d H:i:s', time()).json_encode($user_info)."\n", FILE_APPEND);

    if (!DB::table('daili_amount_change')->where('order_id', $v['form']['order_id'])->count()) {
      if ($user_info->daili_id) {
        file_put_contents("success6.txt", "1\n", FILE_APPEND);
        $change_data['type'] = 1; //
        $daili_info = DB::table('daili')->where('Id', $user_info->daili_id)->first();
        $change_data['user_id'] = $daili_info->Id; //代理id
        $change_data['amount'] = $v['form']['amount'] * ($user_info->order_service - $daili_info->service);
        $change_data['time'] = time();
        //file_put_contents("success7.txt", "1\n", FILE_APPEND);
        $change_data['order_id'] = $v['form']['order_id'];
        $change_data['user_price'] = $daili_info->price + $change_data['amount'];
        //file_put_contents("success8.txt", "1\n", FILE_APPEND);
        //再给商户加余额
        $status = DB::table('daili')->where('Id', $user_info->daili_id)->update(array(
            'price' => $change_data['user_price']
        ));
file_put_contents("success9.txt", json_encode($change_data). "\n", FILE_APPEND);

        //添加商户余额明细
        $addstatus = DB::table('daili_amount_change')->insert($change_data);
        //file_put_contents("success10.txt", "1\n", FILE_APPEND);
        $change_data['user_order_service'] = $user_info->order_service;
        $change_data['daili_order_service'] = $daili_info->service;
        file_put_contents("success11.txt", "----------------------------\n".date('y-m-d H:i:s', time())."\n", FILE_APPEND);
      }
    }



  }
    /****处理订单通知*****/
    public function OrderNotice(){
    	//file_put_contents("success.txt","jjjjjj", FILE_APPEND);
        $client = new Client();
        //取出所有需要回调订单
        try{
	        $ordernotice_redis =Redis::lrange("ordernotice",0,-1);
	        #file_put_contents("success2.txt", '|'.date('y-m-d H:i:s', time()).json_encode($ordernotice_redis)."\n", FILE_APPEND);
	        //file_put_contents("success1.txt", '|'.date('y-m-d H:i:s', time()).json_encode($ordernotice_redis)."\n", FILE_APPEND);
	        if(!empty($ordernotice_redis)){
	            $ordernotice_list= array();
	            foreach ($ordernotice_redis as $k => $v) {
	                if($k >= 39){
	                    break;
	                }else{
	                    $ordernotice_list[] = json_decode($v,true);
	                }
	            }
	            if(!empty($ordernotice_list)){
	            	//file_put_contents("success2.txt", '|'.date('y-m-d H:i:s', time()).json_encode($ordernotice_list)."\n", FILE_APPEND);
	                foreach($ordernotice_list as $k => $v){
                    //webtext
                    file_put_contents("success3.txt", $v['number_notice']."\n", FILE_APPEND);
                    if ($v['number_notice'] == 0 && $v['form']['success_time'] != '') {
                      $this->update_daili_money($v);
                    }
	                    $v = (array)$v;
	                    if($v['number_notice'] <= 2){
	                        try{
	                        	//file_put_contents("success3.txt", date('y-m-d H:i:s', time()).json_encode($v). "\n",  FILE_APPEND);
	                            $res = $client->request('post',$v['notify_url'],[
	                                'verify'=>false,
	                                'connect_timeout' =>2,
	                                'timeout'=>2,
	                                'http_errors' => false,
	                                'form_params'=>$v['form']
	                            ]);
	                            /****记录发送的数据****/
	                            Log::channel('order_notice')->info(json_encode($v['form'])."\r\n");
	                            //file_put_contents("success3.txt", 'get:'.$res->getStatusCode(). "\n",  FILE_APPEND);
	                            if($res->getStatusCode() == 200){
	                            	//file_put_contents("success3.txt", date('y-m-d H:i:s', time()).$res->getBody(). "\n",  FILE_APPEND);
	                                if((string)$res->getBody() == 'success'){
	                                    //修改数据库并删除Redis
                                      //file_put_contents("success3.txt", date('y-m-d H:i:s', time()).json_encode($v),  FILE_APPEND);
	                                    OrderModel::where('apiorder_id',$v['form']['apiorder_id'])->update(array('notice'=>2));
                                      //webtext 添加代理资金


                                      //$user_info = DB::table('user')->where('Id', $v['form']['user_id'])->first();

                                      //file_put_contents("success3.txt", "----------------------------\n".date('y-m-d H:i:s', time()).json_encode($v).json_encode($user_info)."\n", FILE_APPEND);

                                      /*
                                      if ($user_info->daili_id) {
                                        $change_data['type'] = 1; //
                                        $daili_info = DB::table('daili')->where('Id', $user_info->daili_id)->first();
                                        $change_data['user_id'] = $daili_info->Id; //代理id
                                        $change_data['amount'] = $v['form']['amount'] * ($user_info->order_service - $daili_info->service);
                                        $change_data['time'] = time();
                                        $change_data['user_price'] = $daili_info->price + $change_data['amount'];
                                        //再给商户加余额
                                        $status = DB::table('daili')->where('Id', $daili_id)->update(array(
                                            'price' => $change_data['user_price']
                                        ));

                                        //添加商户余额明细
                                        $addstatus = DB::table('daili_amount_change')->insert($change_data);
                                        $change_data['user_order_service'] = $user_info->order_service;
                                        $change_data['daili_order_service'] = $daili_info->service;
                                        file_put_contents("success2.txt", "----------------------------\n".date('y-m-d H:i:s', time()).json_encode($change_data)."\n", FILE_APPEND);
                                      }
                                      */

	                                    Redis::lrem('ordernotice',1,json_encode($v)) ;
	                                }else{
	                                    $v['number_notice']=$v['number_notice']+1;
	                                    Redis::lset('ordernotice',$k,json_encode($v));
	                                }
	                            }else{
	                                $v['number_notice']=$v['number_notice']+1;
	                                Redis::lset('ordernotice',$k,json_encode($v));
	                            }
	                        }catch(\Exception $e){
	                            $v['number_notice']=$v['number_notice']+1;
	                            Redis::lset('ordernotice',$k,json_encode($v));
	                        }
	                    }else{
	                        //修改数据库并删除Redis
	                        $status = OrderModel::where('apiorder_id',$v['form']['apiorder_id'])->update(array('notice'=>3));
	                        if($status){
	                            Redis::lrem('ordernotice',1,json_encode($v));
	                        }
	                    }
	                }
	            }
	        }
        } catch(\Exception $e){
            return array('code'=>'error');
        }
    }
    /****处理过期金额池****/
    public function AmountPool(){
        try{
            //取出所有正在交易金额
            $amount_redis =Redis::lrange("amountpool",0,-1);
            if(!empty($amount_redis)){
                $orderlist= array();
                foreach ($amount_redis as $v) {
                    $orderlist[] = json_decode($v,true);
                }
                //删除时间到期列
                foreach ($orderlist as $v) {
                    $v = (array)$v;
                    if($v['exptime']<= time()){
                        Redis::lrem('amountpool',1,json_encode($v));
                    }
                }
            }
            return array('code'=>'success');
        }catch(\Exception $e){
            return array('code'=>'error');
        }
    }
    /****处理发送socket订单****/
    public function Socket(){
        try{
            //取出所有单个依次发送的消息
            $socket_redis =json_decode(Redis::lindex("socket",0),true);
            if(!empty($socket_redis)){
                //推送消息
                Gateway::sendToClient($socket_redis['token'],json_encode($socket_redis['content']));
                //删除redis推送
                Redis::lrem('socket',1,json_encode($socket_redis));
            }
            return array('code'=>'success');
        }catch(\Exception $e){
            return array('code'=>'error');
        }
    }
    /****检测码商掉线处理清码****/
    public function CheckClose(){
        //查询当天登录的码商
        $map[]=['login_time','<',time() - 50];
        $map[]=['login_time','>=',time() - 86400];
        $map['status']=1;
        $list = PollingModel::where($map)->get();
        if(!$list->isEmpty()){
           $list = $list->toarray();
           $Order_Redis = new Order_Redis;
           $admin_site = DB::table('admin_site')->first();
           try{
	           foreach($list as $v){
	               $v = (array)$v;
	                //判断当前是否在线
	                if(!Gateway::isOnline($v['token'])){
	                       //修改下线
	                       $status = PollingModel::where('Id',$v['Id'])->update(array('token'=>null,'status'=>2));
	                       if($status){
	                         //清除当前账号下的二维码数据
	                         $code_type = $v['type'];
	                         /****删除支付宝二维码****/
	                         $Order_Redis->delete($admin_site->payment,'alipay',$code_type,array('polling_id'=>$v['Id']));
	                         /****删除支付宝H5二维码****/
	                         $Order_Redis->delete($admin_site->payment,'aliwap',$code_type,array('polling_id'=>$v['Id']));
	                         /****删除微信二维码****/
	                         $Order_Redis->delete($admin_site->payment,'wechat',$code_type,array('polling_id'=>$v['Id']));
	                         /****删除银联二维码****/
	                         $Order_Redis->delete($admin_site->payment,'unionpay',$code_type,array('polling_id'=>$v['Id']));
	                       }
	                }
	           }
	        }catch(\Exception $e){
	            return array('code'=>'error');
	        }
        }
    }
    /****处理码商余额不足码池****/
    public function CheckCode(){
        $type = array('alipay','aliwap','wechat','unionpay');
        $admin_site = DB::table('admin_site')->first();
        try {
            if($admin_site->payment_type == 1){
                //处理顺序码池
                foreach ($type as $k => $v) {
                    $list = empty(Redis::lrange('sort_'.$v.'_die',0,-1)) ? Redis::lrange('sort_'.$v.'_live',0,-1) : Redis::lrange('sort_'.$v.'_die',0,-1);
                    if(!empty($list)){
                        foreach ($list as $a) {
                           $info = json_decode($a,true);
                           if($info['merchant']['price'] <= 1){
                                if($info['user']['type'] == 1){
                                    $status = Redis::lrem('sort_'.$v.'_die',1,json_encode($info));
                                    if(!$status){
                                    	Redis::lrem('sort_'.$v.'_die',1,json_encode($info));
                                    }
                                }else{
                                    $status = Redis::lrem('sort_'.$v.'_live',json_encode($info));
                                    if(!$status){
                                    	Redis::lrem('sort_'.$v.'_live',1,json_encode($info));
                                    }
                                }
                           }
                        }
                    }
                }
            }else{
                //处理随机码池
                foreach ($type as $k => $v) {
                    $list = empty(Redis::smembers('random_'.$v.'_die')) ? Redis::smembers('random_'.$v.'_live') : Redis::smembers('random_'.$v.'_die');
                    if(!empty($list)){
                        foreach ($list as $a) {
                           $info = json_decode($a,true);
                           if($info['merchant']['price'] <= 1){
                                if($info['user']['type'] == 1){
                                    $status = Redis::srem('random_'.$v.'_die',1,json_encode($info));
                                    if(!$status){
                                    	Redis::srem('random_'.$v.'_die',1,json_encode($info));
                                    }
                                }else{
                                    Redis::srem('random_'.$v.'_live',json_encode($info));
                                    if(!$status){
                                    	Redis::srem('random_'.$v.'_live',json_encode($info));
                                    }
                                }
                           }
                        }
                    }
                }
            }
        } catch (\Exception $e) {
             return array('code'=>'error');
        }
    }
    /*****清除单个账户码池*****/
    public function CheckPollingClose($id,$code_type){
        $type = array('alipay','aliwap','wechat','unionpay');
        $admin_site = DB::table('admin_site')->first();
        $Order_Redis = new Order_Redis;
        try {
            foreach ($type as $v) {
              $Order_Redis->delete($admin_site->payment_type,$v,$code_type,array('polling_id'=>$id));
            }
        } catch (\Exception $e) {
            return array('code'=>'error');
        }
    }
    /****更新日志操作****/
    public function Operation(){
        //取出所有操作日志
        try {
	        $list =Redis::lrange("operation_log",0,-1);
	        if(!empty($list)){
	            foreach ($list as $v) {
	               $data = json_decode($v,true);
	               if($data['type'] == 'merchant'){
	                    $status = DB::table('member_operation')->insert($data['form']);
	                    if($status){
	                        //清除此日志
	                        Redis::lrem('operation_log',1,json_encode($data));
	                    }
	               }else{
	                    $status = DB::table('admin_operation')->insert($data['form']);
	                    if($status){
	                        //清除此日志
	                        Redis::lrem('operation_log',1,json_encode($data));
	                    }
	               }
	            }
	        }
        } catch (\Exception $e) {
            return array('code'=>'error');
        }
    }
    /****处理连续失败过多码***/
    public function Qrcode_lose(){
    	$type = array('alipay','aliwap','wechat','unionpay');
    	$admin_site = DB::table('admin_site')->first();
    	$Order_Redis = new Order_Redis;
    	try {
	    	foreach ($type as $v){
	    		$list_a = Redis::lrange($v.'_die_record',0,-1);
	    		$list_b = Redis::lrange($v.'_live_record',0,-1);
	    		if(!empty($list_a)){
	    			foreach ($list_a as $w){
	    				$info = json_decode($w,true);
	    				if($info['number']>= $admin_site->qrcode_err_num){
	    					//关闭该网关并清除该二维码
	    					$status = DiepollingpaymentModel::where('key',$info['form']['key'])->update(array('gateway_state'=>2));
	    					if($status){
	    						$Order_Redis->delete($admin_site->payment_type,$v,1,array('key'=>$info['form']['key']));
	    						//记录该失败二维码
	    						$result['number'] = $info['number'];
	    						$result['qrcode'] = $info['form']['qrcode'];
	    						$result['polling_user'] = $info['form']['user']['username'];
	    						$result['key'] = $info['form']['key'];
	    						$result['passageway_id'] = $info['form']['passageway_id'];
	    						$result['code_type'] = 1;
	    						$result['member_id'] = $info['form']['member_id'];
	    						$redis_rpu_status = Redis::rpush('qrcode_error_record',json_encode($result));
	    						if($redis_rpu_status){
	    							//清除当前出码记录
	    							$Order_Redis->query_delete($v,1,$info['form']['key']);
	    						}
	    					}
	    				}
	    			}
	    		}
	    		if(!empty($list_b)){
	    			foreach ($list_b as $e){
	    				$info = json_decode($e,true);
	    				if($info['number']>= $admin_site->qrcode_err_num){
	    					//关闭该网关并清除该二维码
	    					$status = LivepollingpaymentModel::where('key',$info['form']['key'])->update(array('gateway_state'=>2));
	    					if($status){
	    						$Order_Redis->delete($admin_site->payment_type,$v,2,array('key'=>$info['form']['key']));
	    						//记录该失败二维码
	    						$result['number'] = $info['number'];
	    						$result['polling_user'] = $info['form']['user']['username'];
	    						$result['key'] = $info['form']['key'];
	    						$result['passageway_id'] = $info['form']['passageway_id'];
	    						$result['code_type'] = 2;
	    						$result['member_id'] = $info['form']['member_id'];
	    						$redis_rpu_status = Redis::rpush('qrcode_error_record',json_encode($result));
	    						if($redis_rpu_status){
	    							//清除当前出码记录
	    							$Order_Redis->query_delete($v,2,$info['form']['key']);
	    						}
	    					}
	    				}
	    			}
	    		}
	    	}
    	} catch (\Exception $e) {
            return array('code'=>'error');
        }
    }
    /****更新失败二维码****/
    public function Qrcode_addmysql(){
    	$list =Redis::lrange("qrcode_error_record",0,-1);
    	if(!empty($list)){
    		foreach ($list as $v){
    			$status = DB::table('qrcode_error')->insert(json_decode($v,true));
    			if($status){
    				//删除当前记录
			        Redis::lrem('qrcode_error_record',1,$v);
    			}
    		}
    	}
    }
    /****处理扣款失败订单****/
    public function Order_amount_error(){
    	try{
	    	//取出所有需要处理的记录
	        $amount_list =Redis::lrange("order_amount_error",0,-1);
	        if(!empty($amount_list)){
		        	foreach ($amount_list as $v) {
			        	$form = json_decode($v,true);
			        	switch ($form['type']) {
			        		case 1001:	//获取商户余额
			        					$price = DB::table('user')->where('Id', $form['form']['user_id'])->first()->price;
			        					$status = DB::table('user')->where('Id', $form['form']['user_id'])->update(array(
				                                  'price' => $price+$form['form']['amount']
				                        ));
				                        if($status){
				                        	//删除失败记录
			                				Redis::lrem('order_amount_error',1,json_encode($form));
				                        }
			        			break;
			        		case 1002:	//添加余额明细
			        					 $status = DB::table('user_amount_change')->insert($form['form']);
			        					 if($status){
				                        	//删除失败记录
			                				Redis::lrem('order_amount_error',1,json_encode($form));
				                        }
			        			break;
			        		case 2001: //获取码商余额
			        					$price = DB::table('member')->where('Id', $form['form']['member_id'])->first()->price;
			        					$status = DB::table('member')->where('Id', $form['form']['member_id'])->update(array(
				                                  'price' => $price-$form['form']['amount']
				                        ));
				                        if($status){
				                        	//删除失败记录
			                				Redis::lrem('order_amount_error',1,json_encode($form));
				                        }
			        			break;
			        		case 2002: //添加余额明细
			        					$status = DB::table('member_amount_change')->insert($form['form']);
			        					if($status){
				                        	//删除失败记录
			                				Redis::lrem('order_amount_error',1,json_encode($form));
				                        }
			        			break;
			        		case 2003: //添加冻结余额明细
			        					$status = DB::table('member_amount_change')->insert($form['form']);
			        					if($status){
				                        	//删除失败记录
			                				Redis::lrem('order_amount_error',1,json_encode($form));
				                        }
			        			break;
			        	}
		        	}
	        }
    	} catch(\Exception $e){
	            return array('code'=>'error');
	     }

    }
}
