<?php

namespace xh\run\server\controller;


use xh\unity\callbacks;
use xh\unity\encrypt;
use xh\library\request;
use xh\library\functions;
use xh\library\mysql;
use xh\unity\cog;
use xh\library\redis;

class index
{

    private $mysql;

    public function __construct()
    {
        $this->mysql = new mysql();
    }

    //服务版回调成功之后，修改用户余额
    public function updateUserAccount()
    {
        $module_name = 'service_auto';

        $order = $this->mysql->query('service_order', " status=4 and callback_status=1 and reached=0");

        foreach ($order as $obj) {
            //检测是否为用户订单
            if ($obj['user_id'] != 0) {

                $user = $this->mysql->query("client_user", "id={$obj['user_id']}")[0];
                $group = $this->mysql->query('client_group', "id={$user['group_id']}")[0];
                $authority = json_decode($group['authority'], true)[$module_name];

                //判断用户组是否存在
                if (is_array($group) || $group['authority'] != -1 || $authority['open'] == 1) {

                    //手续费扣掉后的金额
                    $fees = $obj['amount'] * $authority['cost'];
                    $user_money = $obj['amount'] - $fees;

                    //给用户加钱
                    $this->mysql->update("client_user", ['money' => $user['money'] + $user_money], "id={$user['id']}");

                    //直接强制修改reached
                    $this->mysql->update("service_order", ['reached' => 1], "id={$obj['id']}");

                }
            }

        }


        functions::json(200, 'ok');
    }


	public function query(){
		
	$find = $this->mysql->query("client_alipay_automatic_orders", "status=2");
   
    foreach($find as $val){
			
/**********************************************************************************************************************************************/
               $header="Cookie:".$val['cookie'];
                
                //请求地址
                $url = "https://pay.sc.weibo.com/aj/pc/biz/list?biz_id=".$val['order_id'];
              //  file_put_contents("log/cdurl.txt", date('Y-m-d H:i:s')."|查单url:|".$url.'|'."\n", FILE_APPEND);
                //headers请求头
                $context_options = array(
                 'http' =>
                  array(
                   'method' => "GET",
                   'header' => $header,
                  ));
                $context = stream_context_create($context_options);
                //获取资源
                $paylist = file_get_contents($url,FALSE,$context);
				 $arr = json_decode($paylist, true);
				 $res=$arr['data']['biz'];
				 $amount=$res[0]['amount'];
				 $status=$res[0]['status'];
				 $out_pay_id=$res[0]['order_id'];
				 $status_desc=$res[0]['status_desc'];	
				 
				 $status_name='交易成功';
                 $this->mysql->update('client_alipay_automatic_orders', ['aliddh' => $out_pay_id], "id={$val['id']}");

        	     //file_put_contents("log/计划任务查单.txt", date('Y-m-d H:i:s')."|订单ID:|".$val['id'].'|'."|状态:|".$status_desc.'|'."|查单url:|".$url.'|'."\n", FILE_APPEND);
				
				$a=$status;
				$b=2;
				if ($val['order_id'] > 0 && $a == $b && $status_desc == $status_name ) { 

        		 $rea = callbacks::curl(URL_ROOT . '/server/alipayAutomatic/uploadOrder', http_build_query(['key' => '12345678','uid' =>$val['order_id'],'orderid' => $out_pay_id,'id' => $val['id'],'keyid' => $val['key_id'],'rmb' => $val['amount']]));	
        			
        			file_put_contents("log/htlog.txt", date('Y-m-d H:i:s')."|回调信息:|".$rea.'|'."\n", FILE_APPEND);
					
					
				}
        		
    	
    	
    	
/**********************************************************************************************************************************************/    	
    	
    	
    	
    	
    	
    }

	
	
	
	//echo '执行成功';


		
	}








  public function upordertime(){
  
    
            $Ttime=time()-599;
   
   			$this->mysql->update("client_alipay_automatic_orders", [
                'status'=> 3
                
            ],"creation_time < {$Ttime} and status!=4");
   
			echo "订单过期状态更新成功";
    
  
  
  }

	public function maxmoney(){
		
	$find = $this->mysql->query("client_alipay_automatic_appid", "status=4");
   
    foreach($find as $val){
			
     $max_amount=$val['max_amount'];
     
     $time=time();
	
	$this->mysql->update("client_alipay_automatic_appid", ['status' => 1,'max_time'=>$time], "amount >={$max_amount}");
    
    	
    }

	
	
	
	echo '执行成功';


		
	}
	
  public function clearamount(){
		
	
   
    $this->mysql->update("client_alipay_automatic_appid", ['status' => 4,'amount'=>0,'today_number'=>0], "status!=5");

	
	
	
	echo '执行成功';


		
	}
	
	
	public function curl_post($sUrl, $aHeader, $aData){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $sUrl);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($aData));
    $sResult = curl_exec($ch);
    if($sError=curl_error($ch)){
        die($sError);
    }
    curl_close($ch);
    return $sResult;
	}	
	
	
  public function takehb(){
  
    $find = $this->mysql->query('client_alipay_automatic_orders', "status = 4 and syrmb>0 ", 'id,uid,order_id,cookie,user_id,key_id,aliddh,syrmb,alipay_id,pay_time');
     
   
//	file_put_contents("find.txt", json_encode($find));

   
     foreach($find as $val){
	
	
	  if (($val['pay_time']+ 3599) > time()) {
                
			
 /********************************************************************************************************************************************************/               
            		
     $did=$val['id'];
     $uid=$val['uid'];
     $order_id=$val['aliddh'];
     $cookie=$val['cookie'];
     $kuk=$val['cookie'];
     $user_id=$val['user_id'];
     $key_id=$val['key_id'];
     $syrmb=$val['syrmb'];
     $alipay_id=$val['alipay_id'];
     //收
     
     
           //$find_seller = $this->mysql->query("client_alipay_automatic_appid", "status=4 and user_id={$user_id} and weid={$alipay_id} and amount<10000");
           $find_seller = $this->mysql->query("client_alipay_automatic_appid", "status=4 and user_id={$user_id}  and amount<10000");
           $count_alipay = count($find_seller);
           //if ($count_alipay == 0) functions::str_json($type_content, -1, 'automatic->初始化失败,没有可用的通道');
           $find_seller = $find_seller[mt_rand(0, $count_alipay - 1)];
          
         
           
    		 $aid=$find_seller['id'];	
		     $cookieSeller=$find_seller['cookie'];
			 $shouid=$find_seller['appid'];     
			  //file_put_contents("shouid.txt", json_encode($shouid));
			 $all_amount=$find_seller['all_amount'];   
			 $max_amount=$find_seller['max_amount'];
			 $jr_amount=$find_seller['amount'];
			 $today_number=$find_seller['today_number'];
		     $all_number=$find_seller['all_number'];
			 



/********************************************************************************************************************************************************/


	        		$cookie='Cookie:'.$cookie;
            		$msgid=$shouid;
            		$payercookie=$cookie; //发包人cookie
            		
            
/********************************************************************************************************************************************************/ 
//先互相关注 在发包
//先关注发包人关注收包人微博 // 请注意 只能他妈电脑获取得cookie 否则无效！
                $addUrl = 'https://weibo.com/aj/f/followed?ajwvr=6';
                //post数据
                $addData = array(
                    'uid' => $msgid,
                    'f' => '1',
                    'refer_flag' => '1005050001_',
                    'location' => 'page_100505_home',
                    'oid' => $msgid,
                    'wforce' => '1',
                    'nogroup' => '1',
                    'refer_from' => 'profile_headerv6',
                    'template' => '7',
                    'special_focus' => '1',
                    'isrecommend' => '1',
                    'is_special' => '0',
                    'redirect_url' => '%2Fp%2F1005057345773101%2Fmyfollow%3Fgid%3D4444185002098079%23place',
                    '_t' => '0'
                );
                
                $refer='https://weibo.com/u/'.$msgid.'?is_hot=1&noscale_head=1';
                
			    $Referer='Referer:'.$refer;
                $addHeader = array('Host:weibo.com','Origin:https://weibo.com','Content-type:application/x-www-form-urlencoded','User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36','X-Requested-With:XMLHttpRequest',$Referer,$payercookie);
                
                
                
                $addResult = $this->curl_post($addUrl, $addHeader, $addData);
                //file_put_contents("addpayResult.txt", $addResult);
                
                $addResData = json_decode($addResult, true);
                $addcode=$addResData['code'];
                //100000 代表成功 详情看日志 
                file_put_contents("log/DaEpaycode.txt", date('Y-m-d H:i:s')."|发包关注收包:|".$addcode.'|'."\n", FILE_APPEND);
                
                //file_put_contents("addResData.txt", $addResData);
                
///////////////////////////////然后收包人关注发包人


				if($addcode==100000){
                	
                	
                $Sellerookie='Cookie:'.$cookieSeller;	
                $aadfUrl = 'https://weibo.com/aj/f/followed?ajwvr=6';
                //post数据
                $aadfData = array(
                    'uid' => $uid,
                    'f' => '1',
                    'refer_flag' => '1005050001_',
                    'location' => 'page_100505_home',
                    'oid' => $uid,
                    'wforce' => '1',
                    'nogroup' => '1',
                    'refer_from' => 'profile_headerv6',
                    'template' => '7',
                    'special_focus' => '1',
                    'isrecommend' => '1',
                    'is_special' => '0',
                    'redirect_url' => '%2Fp%2F1005057345773101%2Fmyfollow%3Fgid%3D4444185002098079%23place',
                    '_t' => '0'
                );
                
                $refer='https://weibo.com/u/'.$uid.'?is_hot=1&noscale_head=1';
                
			    $Referer='Referer:'.$refer;
                $aadfHeader = array('Host:weibo.com','Origin:https://weibo.com','Content-type:application/x-www-form-urlencoded','User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36','X-Requested-With:XMLHttpRequest',$Referer,$Sellerookie);
                
                
                
                $aadfResult = $this->curl_post($aadfUrl, $aadfHeader, $aadfData);
               // file_put_contents("aadfResult.txt", $aadfResult);
                
                $aadfResData = json_decode($aadfResult, true);
                $aadfcode=$aadfResData['code'];
                //100000 代表成功 详情看日志 
				file_put_contents("log/DaEtakeusercode.txt", date('Y-m-d H:i:s')."|收包关注发包:|".$aadfcode.'|'."\n", FILE_APPEND);
                }                           
/********************************************************************************************************************************************************/                            

                            // 发红包信息至收款人
                $sUrl = 'https://mall.e.weibo.com/aj/redenvelope/sendmsg';
                //post数据
                $aData = array(
                    'msgid' => $msgid,
                    'msgtype' => '1',
                    'set_id'   => $order_id,
                    '_t'      => '0'
                );
                
             // file_put_contents("aData.txt", $aData);
                
                $aHeader = array('Content-type:application/x-www-form-urlencoded','User-Agent:Mozilla/5.0 (Linux; Android 5.1.1; DUK-AL20 Build/LMY48Z) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Safari/537.36 Weibo (HUAWEI-DUK-AL20__weibo__9.7.2.1__android__android5.1.1))','X-Requested-With:XMLHttpRequest',$cookie);
                
                
                
                $sResult = $this->curl_post($sUrl, $aHeader, $aData);
                
                $aResData = json_decode($sResult, true);	
                $code=$aResData['code'];
                
                
 /********************************************************************************************************************************************************/               
                
/********************************************************************************************************************************************************/



              //开始收包！
              
        		if($code==100000){
         	
         	   $header="X-Requested-With:com.sina.weibo\r\nx-user-agent:HUAWEI-DUK-AL20__weibo__9.7.2.1__android__android5.1.1\r\nUser-Agent:Mozilla/5.0 (Linux; Android 5.1.1; DUK-AL20 Build/LMY48Z) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Safari/537.36 Weibo (HUAWEI-DUK-AL20__weibo__9.7.2.1__android__android5.1.1)\r\nCookie:".$cookieSeller."\r\n";
                
                $url = "https://mall.e.weibo.com/h5/redenvelope/draw?set_id=".$order_id."&sinainternalbrowser=topnav&portrait_only=1&from=1097295010&weiboauthoruid=";
                $context_options = array(
                 'http' =>
                  array(
                   'method' => "GET",
                   'header' => $header,
                  ));
                $context = stream_context_create($context_options);
                $html = file_get_contents($url,FALSE,$context);
                file_put_contents("log/html.txt", date('Y-m-d H:i:s')."|html:|".$html.'|'."\n", FILE_APPEND);
				$matches = array();
				preg_match_all('( <p class="red_amount">(.*)</p>)', $html, $matches);
				$money=$matches[1][0];
				
				
				
				 file_put_contents("log/takemoney.txt", date('Y-m-d H:i:s')."|金额:|".$money.'|'."\n", FILE_APPEND);
				 
				$arry=empty($money);
				
				
/********************************************************************************************************************************************************/				
				
				if($arry==false){
				//echo "不为空";	
				 $this->mysql->update("client_alipay_automatic_orders", ['syrmb' => $syrmb-$money], "id={$did}");
				
				$this->mysql->update("client_alipay_automatic_appid", ['all_amount' => $all_amount+$money,'amount' => $jr_amount+$money,'today_number' => $today_number+1,'all_number' => $all_number+1], "id={$aid}");
					
				}
				 
			 
				 
				 
/********************************************************************************************************************************************************/			 
	//开始查单			
	$rea = callbacks::curl(URL_ROOT . '/server/callback/takelist', http_build_query(['userid' => $user_id,'amount' =>$money,'fid' => $uid,'seler_uid' => $shouid,'set_id' => $order_id,'kuk' => $kuk]));	

/********************************************************************************************************************************************************/	        			
        		}

    
	  }	
    
     	
     }
  
  echo 'success';
  
  }	
	
	
	

    function serviceCallback()
    {
        $service = $this->mysql->query('service_account', "status = 4", 'id,status');
        var_dump($service);
        echo "<br/>";
        if (!empty($service)) {
            foreach ($service as $val) {
                $result = callbacks::curl(URL_ROOT . '/server/service/callback', http_build_query(['id' => $val['id']]));
                print_r($result);
                echo $val['id'] . "<br/>";
            }
        }

    }

    //alipay v1.0 接口
    public function alipayCallback()
    {
        $module_name = 'alipay_auto';
        error_reporting(-1);
        $creation_time = time() - 300;
        // -------------------------
        // 获取需要回调的列表
        $order = $this->mysql->query('client_alipay_automatic_orders', "status=4 and callback_status=0 AND callback_count < 3 AND creation_time > $creation_time");
        print_r($order);
        foreach ($order as $obj) {
            $user = $this->mysql->query("client_user", "id={$obj['user_id']}")[0];
            if (!is_array($user)) continue;

            $group = $this->mysql->query('client_group', "id={$user['group_id']}")[0];

            $authority = json_decode($group['authority'], true)[$module_name];
            if (!is_array($group) || $group['authority'] == -1 || $authority['open'] != 1) continue;

            // 开始扣手续费
            $fees = $obj['amount'] * $authority['cost'];
            $user_balance = $user['balance'] - $fees; // 用户最终余额
            $user_balance = floatval($user_balance);

            if ($user_balance >= 0) {

                $user['balance'] = $user_balance;
                $callback_time = time();
                // 手续费扣除成功，开始回调

                $result = callbacks::curl_request($obj['callback_url'], [
                    'account_name'  => $user['username'],
                    'pay_time'      => $obj['pay_time'],
                    'status'        => 'success',
                    'amount'        => $obj['amount'],
                    'out_trade_no'  => $obj['out_trade_no'],
                    'trade_no'      => $obj['trade_no'],
                    'fees'          => $fees,
                    'sign'          => functions::sign($user['key_id'], [
                        'amount'       => floatval($obj['amount']),
                        'out_trade_no' => $obj['out_trade_no']
                    ]),
                    'callback_time' => $callback_time,
                    'type'          => 2,
                    'account_key'   => $user['key_id']
                ]);
                var_dump($result);
                $callback_status = 0;
                if (strtolower($result) == 'success') {
                    $callback_status = 1;

                    $deductionStatus = $this->mysql->update("client_user", [
                        'balance' => floatval($user_balance)
                    ], "id={$user['id']}");
                    echo $deductionStatus;
                }

                echo $this->mysql->update("client_alipay_automatic_orders", [
                    'callback_time'    => $callback_time,
                    'callback_status'  => $callback_status,
                    'callback_content' => htmlentities($result),
                    'callback_count'   => $obj['callback_count'] + 1,
                    'fees'             => $fees
                ], "id={$obj['id']}");
            }


        }

    }

    //检测服务端掉线
    public function checkOnline()
    {
        $time = functions::getAndroidHeartbeatNowTime(30);

        //支付宝公开版
        $this->mysql->update("client_wechat_automatic_account", ['status' => 1], "status=4 and active_time<{$time}");
        //微信公开版
        $this->mysql->update("client_alipay_automatic_account", ['status' => 1], "status=4 and active_time<{$time}");
        //云闪付公开版
        $this->mysql->update("client_ysf_automatic_account", ['status' => 1], "status=4 and active_time<{$time}");
        //服务版
 		$this->mysql->update("service_account", ['status' => 5], "status=4 and active_time<{$time} and types in(1,2,4)");        functions::json(200, '异常处理完毕');
    }

    function checkWechatHeartbeat()
    {
        return false;
        // file_put_contents('log.txt', date('Y-m-d H:i:s') . '=======checkWechatHeartbeat=======', FILE_APPEND);
        $signkey = @cog::read("server")['key'];
        $now = time() - functions::getAndroidHeartbeatNowTime();
        $data_list = $this->mysql->query('client_wechat_automatic_account', "natapp_url != ' '", 'id,user_id,key_id,heartbeats,natapp_url', 'android_heartbeat', 'desc');
        if (empty($data_list)) return false;
        foreach ($data_list as $val) {
            print_r($val);
            if (empty($val)) continue;

            $url = $val['natapp_url'] . "checkHeartbeat?device_key={$val['key_id']}&signkey={$signkey}&type=1&uid={$val['user_id']}";

            $text = @file_get_contents($url);
            var_dump($text);
            $time = time();
            if ((int)$text == 1) {

                $editData = [
                    'status'            => 4,
                    'login_time'        => $time,
                    'heartbeats'        => $val['heartbeats'] + 1,
                    'active_time'       => $time,
                    'android_heartbeat' => $time,
                ];

            } else {

                $editData = [
                    'status' => 1,
//                    'training'  => 2,
//                    'receiving' => 2
                ];

            }

            var_dump($this->mysql->update("client_wechat_automatic_account", $editData, "id={$val['id']}"));

        }
        functions::json(200, '微信检测完毕');
    }

    function checkServiceHeartbeat()
    {
        return false;
        //file_put_contents('log.txt', date('Y-m-d H:i:s') . '=======checkServiceHeartbeat=======', FILE_APPEND);
        $signkey = @cog::read("server")['key'];

        $now = time() - functions::getAndroidHeartbeatNowTime();
        $data_list = $this->mysql->query('service_account', "natapp_url != ' ' ", 'id,key_id,natapp_url,heartbeats,types', 'android_heartbeat', 'desc');
        if (empty($data_list)) return false;
        foreach ($data_list as $val) {
            print_r($val);
            if (empty($val)) continue;

            $url = $val['natapp_url'] . "checkHeartbeat?device_key={$val['key_id']}&signkey={$signkey}&type={$val['types']}";
            echo $url;
            $text = @file_get_contents($url);
            var_dump($text);
            $time = time();
            if ((int)$text == 1) {
                $editData = [
                    'status'            => 4,
                    'login_time'        => $time,
                    'heartbeats'        => $val['heartbeats'] + 1,
                    'active_time'       => $time,
                    'android_heartbeat' => $time,
                ];

            } else {
                $editData = [
                    'status' => 1,
//                    'training'  => 2,
//                    'receiving' => 2
                ];

            }
            $this->mysql->update("service_account", $editData, "id={$val['id']}");

        }
        functions::json(200, '服务端心跳检测完毕');
    }

    public function checkAlipayHeartbeat()
    {
        return false;
        //error_reporting(E_ALL);
        // file_put_contents('log.txt', date('Y-m-d H:i:s') . '=======checkAlipayHeartbeat=======', FILE_APPEND);
        $signkey = @cog::read("server")['key'];
        $now = time() - functions::getAndroidHeartbeatNowTime();
        $data_list = $this->mysql->query('client_alipay_automatic_account', "natapp_url != ' ' ", 'id,user_id,key_id,heartbeats,natapp_url,training,receiving', 'android_heartbeat', 'desc');

        if (empty($data_list)) return false;
        $data_list[] = [];
        foreach ($data_list as $val) {
            if (empty($val)) continue;
            print_r($val);
            $url = $val['natapp_url'] . "checkHeartbeat?device_key={$val['key_id']}&signkey={$signkey}&type=2&uid={$val['user_id']}";
            $text = @file_get_contents($url);
            var_dump($text);
            $time = time();
            if ((int)$text == 1) {
                $editData = [
                    'status'            => 4,
                    'login_time'        => $time,
                    'heartbeats'        => $val['heartbeats'] + 1,
                    'active_time'       => $time,
                    'android_heartbeat' => $time,
                ];

            } else {
                $editData = [
                    'status' => 1,
//                    'training'  => 2,
//                    'receiving' => 2
                ];


            }
            $update_id = $this->mysql->update("client_alipay_automatic_account", $editData, "id={$val['id']}");


        }
        functions::json(200, '阿里心跳检测完毕');
    }


    public function uploadLoginData()
    {
        $wechat_key = request::filter('post.wechat_key', '', 'trim');
        $alipay_key = request::filter('post.alipay_key', '', 'trim');
        $service_alypay_key = request::filter('post.service_alypay_key', '', 'trim');
        $service_wechat_key = request::filter('post.service_wechat_key', '', 'trim');
        if (!empty($service_wechat_key)) {
            $this->mysql->update("service_account", [
                'status'      => 4,
                'login_time'  => time(),
                'active_time' => time()
            ], "key_id='{$service_wechat_key}'");
        }
        if (!empty($service_alypay_key)) {
            $this->mysql->update("service_account", [
                'status'      => 4,
                'login_time'  => time(),
                'active_time' => time()
            ], "key_id='{$service_alypay_key}'");
        }
        if (!empty($wechat_key)) {
            $this->mysql->update("client_wechat_automatic_account", [
                'status'      => 4,
                'login_time'  => time(),
                'active_time' => time()
            ], "key_id='{$wechat_key}'");
        }

        if (!empty($alipay_key)) {
            $this->mysql->update("client_alipay_automatic_account", [
                'status'      => 4,
                'login_time'  => time(),
                'active_time' => time()
            ], "key_id='{$alipay_key}'");
        }

        functions::json(200, ' [' . date("Y/m/d H:i:s", time()) . ']: 服务ID->登录成功');
    }


    //安卓登录
    public function loginDo()
    {


        $username = request::filter('post.member_id', '', 'trim');
        $pwd = request::filter('post.pwd', '', 'trim');
        $signkey = request::filter('post.signkey', '', 'trim');
        if (cog::read("server")['key'] != $signkey) functions::json(-1, '通讯失败');

        $find = $this->mysql->query("client_user", "username='{$username}'", 'id,username,pwd,token,key_id')[0];

        if (is_array($find)) {
            //开始验证密码
            if (functions::pwd($pwd, $find['token']) != $find['pwd']) functions::json(-2, '密码错误!');
            unset($find['token']);
            unset($find['pwd']);
            functions::json(200, '登录成功', $find);
        }
        //如果没找到用户名，检测是否为手机号
        if (!functions::isMobile($username)) functions::json('-3', '会员名输入有误');
        //检测手机号码
        $find = $this->mysql->query("client_user", "phone={$username}")[0];
        if (is_array($find)) {
            //开始验证密码
            if (functions::pwd($pwd, $find['token']) != $find['pwd']) functions::json(-2, '密码错误!');
            unset($find['token']);
            unset($find['pwd']);
            functions::json(200, '登录成功', $find);
        }

        functions::json(-3, '手机号码输入有误');
    }


    public function login()
    {

        $encrpty = new encrypt();
        $data = json_decode($encrpty->Decode(request::filter('post.data', '', 'htmlspecialchars'), cog::read("server")['key']), true);
        $username = $data['member_id'];
        $pwd = $data['pwd'];
        $find = $this->mysql->query("client_user", "username='{$username}'")[0];
        if (is_array($find)) {
            //开始验证密码
            if (functions::pwd($pwd, $find['token']) != $find['pwd']) functions::json_encode(-2, '密码错误!');
            functions::json_encode(200, '登录成功');
        }
        //如果没找到用户名，检测是否为手机号
        if (!functions::isMobile($username)) functions::json_encode('-3', '会员名输入有误');
        //检测手机号码
        $find = $this->mysql->query("client_user", "phone={$username}")[0];
        if (is_array($find)) {
            //开始验证密码
            if (functions::pwd($pwd, $find['token']) != $find['pwd']) functions::json_encode(-2, '密码错误!');
            functions::json_encode(200, '登录成功');
        }
        functions::json_encode(-3, '手机号码输入有误');
    }


    //获取二维码生成任务
    public function taskGet()
    {
        //调用登录
        $user = $this->loginAndroid();
        //任务队列
        $Task = [];
        //检测微信是否有值
        if (is_array($user['wechat'])) {
            //查询准备生成二维码的订单
            $wechat_order = $this->mysql->query('client_wechat_automatic_orders', "wechat_id={$user['wechat']['id']} and status=1 and user_id={$user['id']}", "amount,trade_no")[0];
            //更新心跳
            //$this->mysql->update("client_wechat_automatic_account", ['android_heartbeat'=>time()],"id={$user['wechat']['id']}");
            if (is_array($wechat_order)) {
                //将该任务添加到队列
                $Task[] = array_merge($wechat_order, ['type' => 'wechat']);
            }
            //更新心跳
            $this->mysql->update("client_wechat_automatic_account", ['android_heartbeat' => time()], "id={$user['wechat']['id']}");
        }
        //检测支付宝是否有值
        if (is_array($user['alipay'])) {
            //查询准备生成二维码的订单
            $alipay_order = $this->mysql->query('client_alipay_automatic_orders', "alipay_id={$user['alipay']['id']} and status=1 and user_id={$user['id']}", "amount,trade_no")[0];
            //更新心跳
            //$this->mysql->update("client_alipay_automatic_account", ['android_heartbeat'=>time()],"id={$user['alipay']['id']}");
            if (is_array($alipay_order)) {
                //将该任务添加到队列
                $Task[] = array_merge($alipay_order, ['type' => 'alipay']);
            }
            //更新心跳
            $this->mysql->update("client_alipay_automatic_account", ['android_heartbeat' => time()], "id={$user['alipay']['id']}");
        }
        //下发任务
        functions::json_encode(200, 'success', $Task);
    }

    //安卓验证账号密码
    protected function loginAndroid()
    {
        $encrpty = new encrypt();
        $data = json_decode($encrpty->Decode(request::filter('post.data'), cog::read("server")['key']), true);
        //会员名/手机号
        $username = $data['member_id'];
        //密码
        $pwd = $data['pwd'];
        //微信_key
        $WECHAT_Key = $data['wechat_key'];
        //支付宝_key
        $ALIPAY_Key = $data['alipay_key'];
        //QQ_key -> 未开发
        $QQ_key = $data['tenpay_key'];

        $find = $this->mysql->query("client_user", "username='{$username}'")[0];

        //验证用户名模式
        if (is_array($find)) {
            //开始验证密码
            if (functions::pwd($pwd, $find['token']) != $find['pwd']) functions::json_encode(-2, '密码错误!');
            //验证微信key
            $find['wechat'] = $this->mysql->query("client_wechat_automatic_account", "user_id={$find['id']} and key_id='{$WECHAT_Key}'")[0];
            //验证支付宝key
            $find['alipay'] = $this->mysql->query("client_alipay_automatic_account", "user_id={$find['id']} and key_id='{$ALIPAY_Key}'")[0];
            //附加post参数
            $find['data'] = $data;

            //返回
            return $data;
        }

        //如果没找到用户名，检测是否为手机号
        if (!functions::isMobile($username)) functions::json_encode('-6', request::filter('post.data', '', 'htmlspecialchars'));
        //检测手机号码
        $find = $this->mysql->query("client_user", "phone={$username}")[0];
        if (is_array($find)) {
            //开始验证密码
            if (functions::pwd($pwd, $find['token']) != $find['pwd']) functions::json_encode(-2, '密码错误!');
            //验证微信key
            $find['wechat'] = $this->mysql->query("client_wechat_automatic_account", "user_id={$find['id']} and key_id='{$WECHAT_Key}'")[0];
            //验证支付宝key
            $find['alipay'] = $this->mysql->query("client_alipay_automatic_account", "user_id={$find['id']} and key_id='{$ALIPAY_Key}'")[0];
            //附加post参数
            $find['data'] = $data;

            //返回
            return $find;
        }
        functions::json_encode(-3, '手机号码输入有误');
    }

    //删除1天以前的所有日志记录
    public function crontabClearLog()
    {
        $add_time = time() - (60 * 60 * 24);
        $delete = $this->mysql->delete('order_log', "add_time < {$add_time}");
        file_put_contents("crontabClearLog.txt", date('Y-m-d H:i:s') . "sql:" . "add_time < {$add_time}" . ';delete_count' . $delete . PHP_EOL, FILE_APPEND);
    }

    //删除7天前无效的订单数据
    public function crontabClearOrder()
    {
        $add_time = time() - (60 * 60 * 24 * 7);
        $delete = $this->mysql->delete('client_alipay_automatic_orders', "status != 4 AND creation_time < {$add_time}");
        file_put_contents("crontabClearOrder.txt", date('Y-m-d H:i:s') . "sql:" . "add_time < {$add_time}" . ';delete_count' . $delete . PHP_EOL, FILE_APPEND);
        $delete = $this->mysql->delete('client_wechat_automatic_orders', "status != 4 AND creation_time < {$add_time}");
        file_put_contents("crontabClearOrder.txt", date('Y-m-d H:i:s') . "type:wecht-sql:" . "add_time < {$add_time}" . ';delete_count' . $delete . PHP_EOL, FILE_APPEND);
        $delete = $this->mysql->delete('client_pay_record', "pay_time < {$add_time}");

    }

    public function editName()
    {
        $name = request::filter('post.name');
        $id = request::filter('post.id');
        $where = 'id = ' . $id;
        $update['name'] = $name;
        $result = $this->mysql->update('service_account', $update, $where);
        if ($result) {
            echo json_encode(['code' => 200, 'msg' => '成功']);
        } else {
            echo json_encode(['code' => -1, 'msg' => '失败']);
        }
    }
    public function unlockFloorNum(){
        echo "unlock start!\n";
        $orders = $this->mysql->query('client_bank_automatic_orders', "status!=4 and del_floor=0 order by id asc");
        $temp = [];

        //同一金额的订单，大于10分钟的需要解锁金额，但是有不大于10分钟的金额不能够解锁
        foreach($orders as $order){
            $now = time();
            if(($now - $order['creation_time']) >= 10*60){ //大余10分钟的需要解锁金额
                $temp[$order['amount']] = $order['amount'];
                $this->mysql->update('client_bank_automatic_orders', ['del_floor'=>1], 'id='.$order['id']);
            }else{
                // 不大于10分钟的金额不能够解锁
                if(isset($temp[$order['amount']])){
                    unset($temp[$order['amount']]);
                }
            }
        }

        // 开始解锁金额
        $redis = $redis = redis::getInstance(functions::getRedisConfig());
        foreach ($temp as $val){
            $floorMoney = floor($val); // 把小数点去掉 如100.10转成100
            $floorNum = explode(".",$val)[1]/100;
            $redisKey = 'order:amount:lock:floor:'.$floorMoney;

            //解锁金额
            $res = $redis->srem($redisKey,$floorNum);
            $str = date('Y-m-d H:i:s')."-解锁浮动金额-$floorMoney".'-'.$floorNum.'=>解锁结果:'.$res."\n";
            echo $str;
            file_put_contents("jiaoben_unlock_floor.txt", $str, FILE_APPEND);

        }
        echo 'unlock done!';

    }
  
    public function unlockFloorNumm(){
        echo "unlock start!\n";
        $orders = $this->mysql->query('service_order', "status!=4 and del_floor=0 order by id asc");
        $temp = [];

        //同一金额的订单，大于10分钟的需要解锁金额，但是有不大于10分钟的金额不能够解锁
        foreach($orders as $order){
            $now = time();
            if(($now - $order['creation_time']) >= 10*60){ //大余10分钟的需要解锁金额
                $temp[$order['amount']] = $order['amount'];
                $this->mysql->update('service_order', ['del_floor'=>1], 'id='.$order['id']);
            }else{
                // 不大于10分钟的金额不能够解锁
                if(isset($temp[$order['amount']])){
                    unset($temp[$order['amount']]);
                }
            }
        }

        // 开始解锁金额
        $redis = $redis = redis::getInstance(functions::getRedisConfig());
        foreach ($temp as $val){
            $floorMoney = floor($val); // 把小数点去掉 如100.10转成100
            $floorNum = explode(".",$val)[1]/100;
            $redisKey = 'order:amount:lock:floor:'.$floorMoney;

            //解锁金额
            $res = $redis->srem($redisKey,$floorNum);
            $str = date('Y-m-d H:i:s')."-解锁浮动金额-$floorMoney".'-'.$floorNum.'=>解锁结果:'.$res."\n";
            echo $str;
            file_put_contents("server_unlock_floor.txt", $str, FILE_APPEND);

        }
        echo 'unlock done!';

    }
}
