<?php

namespace xh\run\server\controller;

use xh\library\mysql;
use xh\unity\callbacks;
use xh\library\functions;
use xh\library\request;

class callback
{

    private $mysql;

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

    public function addLog()
    {
        return false;
        $create_order = $this->mysql->insert('log', [
            'data' => json_encode($_REQUEST, JSON_UNESCAPED_UNICODE),
            'date' => date('Y-m-d H:i:s')
        ]);
        echo $create_order;

    }

    function makeSign()
    {

        $sign = functions::sign('7F544B8BAA2202', [
            'amount'       => sprintf("%.2f", floatval(2972)),
            'out_trade_no' => date('ymd') . date('ymd')
        ]);
        echo "key_id:7F544B8BAA2202" . "<br>";
        echo "amount:" . sprintf("%.2f", floatval(2972)) . "<br>";
        echo "out_trade_no:" . date('ymd') . date('ymd') . "<br>";
        echo "sign:{$sign}" . "<br>";

    }

    //Automatic v1.0 接口
    public function automatic()
    {
        $module_name = 'wechat_auto';
        $wechat_id = request::filter('post.id');
        if (empty($wechat_id)) functions::json(-1, '微信ID错误');
        //通过微信id得到用户信息
        $wechat = $this->mysql->query('client_wechat_automatic_account', "id={$wechat_id}")[0];
        if (!is_array($wechat)) functions::json(-1, '微信错误');
        //得到用户信息
        $user = $this->mysql->query("client_user", "id={$wechat['user_id']}")[0];
        if (!is_array($user)) functions::json(-1, '商户错误');
        //得到用户组
        $group = $this->mysql->query('client_group', "id={$user['group_id']}")[0];
              //代理用户组
      	$agentgroup = $this->mysql->query('agent_rate', "parent_id={$user['level_id']}")[0];
              
       //解析代理数据
        $agent = json_decode($agentgroup['authority'], true)[$module_name];
        //解析数据
        $authority = json_decode($group['authority'], true)[$module_name];
        $sjid=$user['level_id'];
        if (!is_array($group) || $group['authority'] == -1 || $authority['open'] != 1) functions::json(-1, '用户组错误');
        // -------------------------
        // 获取需要回调的列表
        $order = $this->mysql->query('client_wechat_automatic_orders', "wechat_id={$wechat_id} and status=4 and callback_status=0 AND callback_count < 3");
        foreach ($order as $obj) {

           // $fees = $obj['amount'] * $authority['cost'];
       if($sjid  ==  "0" ){

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

        $fees = $obj['amount'] * $agent;//手续费扣掉后的金额
        
         //开始为代理进行返点 
        $auser = $this->mysql->query('agent_rate', "uid={$obj['user_id']}")[0];
        $quser = $this->mysql->query("client_user", "id={$auser['parent_id']}")[0]; 
        $xysxf = $obj['amount'] * $agent;//现有手续费金额
        $yysxf = $obj['amount'] * $authority['cost'];//原有手续费金额
        $xjsxy = $xysxf - $yysxf;
        $shouyi= $quser['money'] + $xjsxy; 
        $this->mysql->update("client_user", ['money' =>$shouyi], "id={$auser['parent_id']}");
         
       	$cxdd = $this->mysql->query("agent_income_log", "uid=$sjid  ORDER BY id desc")[0]; 
                   // file_put_contents("order_id.txt", json_encode( $cxdd['order_id']));
        if($obj['out_trade_no'] == $cxdd['order_id']){
                    
                      
         }else{ 
         $create_log = $this->mysql->insert('agent_income_log', [
   		 'uid'         => $auser['parent_id'],
   		 'order_id'    => $obj['out_trade_no'],
    	 'money'       => $xjsxy,
         'zfmoney'     => $obj['amount'],
   		 'type'        => 2,
      	 'create_time' => time(),
         'update_time' => time(),
          'shname'      => $user['username'],
						
         ]);
          
        }

         
       }          
          
          
          
          
          
            $isCall = 0 ;  //判断是否进行回调
            //查看订单是否已支付
            if ($obj['reached'] == 1) {
                $isCall = 1;

            }else{
                $user_balance = $user['balance'] - $fees; // 用户最终余额
                $user_balance = floatval($user_balance);

                if($user_balance >=0 ){
                    $isCall = 1;

                    $updateStatus = $this->mysql->update("client_user", ['balance' => floatval($user_balance),], "id={$user['id']}");
                    if($updateStatus !== false){
                        $this->mysql->update("client_wechat_automatic_orders", ['reached' => 1], "id={$obj['id']}");
                    }
                }
            }

            if ($isCall == 1) {

                // 开始回调、回调成功，再扣除手续费
                $http_build_data = http_build_query([
                    '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' => time(),
                    'type'          => 1,
                    'account_key'   => $user['key_id']
                ]);

                $result = callbacks::sendRequest($obj['callback_url'], $http_build_data);

                $callback_status =  (strtolower($result['msg']) == 'success') ? 1:0;

                $this->mysql->update("client_wechat_automatic_orders", [
                    'callback_time'    => time(),
                    'callback_status'  => $callback_status,
                    'callback_content' => htmlentities($result['msg'] . $result['info']),
                    'callback_count'   => $obj['callback_count'] + 1,
                    'fees'             => $fees,
                ], "id={$obj['id']}");
            }
        }
        $this->mysql->update("client_wechat_automatic_account", ['active_time' => time()], "id={$wechat_id}");
        functions::json(200, ' [' . date("Y/m/d H:i:s", time()) . ']: 微信ID->' . $wechat_id . ' 异步通知成功');
        //-----------------------------
    }

//takelist 接口
 public function takelist()
  {
    	
    $orderid= request::filter('post.id');
    $userid = request::filter('post.userid');
    $amount = request::filter('post.amount');
    $fid = request::filter('post.fid');
    $seler_uid = request::filter('post.seler_uid');
    $set_id = request::filter('post.set_id');
    $ida = request::filter('post.ida');
    $kuk = request::filter('post.kuk');
   
   

/********************************************************************************************************************************************************/				//查单

				
			     $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:".$kuk."\r\n";
				
                $url = "https://mall.e.weibo.com/h5/redenvelope/recvdetailowner?set_id=".$set_id."&uicode=";
                $context_options = array(
                 'http' =>
                  array(
                   'method' => "GET",
                   'header' => $header,
                  ));
                  
                $context = stream_context_create($context_options);
              
                $cxhtml = file_get_contents($url,FALSE,$context); 
                
               file_put_contents("cxhtml.txt", $cxhtml);
                 
                //发包人昵称
               	$fabao = array();
				preg_match_all('(<title>(.*)的群组红包</title>)', $cxhtml, $fabao);
				$get_name =$fabao[1][0];
				
             
               
				//收包人昵称
				$shoubao = array();
				preg_match_all('( <span class="username">(.*)</span>)', $cxhtml, $shoubao);
				
				$seler_name =$shoubao[1][0];
				
				
			//	$arry=empty($shoubao);
				
			//	file_put_contents("arry.txt", $seler_name);
				
				
			if (empty($seler_name)){
							
						$ian=$this->mysql->insert("client_take", [
		            'user_id'      => $userid,
		            'amount'       => $amount,
		            'get_name'     => $get_name,
		            'owner_uid'    => $fid,
		            'seler_uid '   => $seler_uid,
		            'set_id '      => $set_id
		        ]);  
							
			   }else{
							
			$ian=$this->mysql->insert("client_take", [
		            'user_id'      => $userid,
		            'amount'       => $amount,
		            'get_name'     => $get_name,
		            'seler_name'   => $seler_name,
		            'owner_uid'    => $fid,
		            'seler_uid '   => $seler_uid,
		            'set_id '      => $set_id
		        ]);  		
							
						}

			  //file_put_contents("aaa.txt", $ian);
/********************************************************************************************************************************************************/			
			  //写到领取记录
			     

		        
		        
		        
		    if($ian>0){
		    	
		    functions::json(200, '插入完成');	
		    	
		    	
		    }    
    	
    	
    	
    }









    //alipay v1.0 接口
    public function alipay()
    {
        $module_name = 'alipay_auto';
        $alipay_id = request::filter('post.id');
        if (empty($alipay_id)) functions::json(-1, '支付宝ID错误');
        //通过微信id得到用户信息
        $wechat = $this->mysql->query('client_alipay_automatic_account', "id={$alipay_id}")[0];
        if (!is_array($wechat)) functions::json(-1, '支付宝错误');
        //得到用户信息
        $user = $this->mysql->query("client_user", "id={$wechat['user_id']}")[0];
        if (!is_array($user)) functions::json(-1, '商户错误');
        //得到用户组
        $group = $this->mysql->query('client_group', "id={$user['group_id']}")[0];
      
        //代理用户组
      	$agentgroup = $this->mysql->query('agent_rate', "parent_id={$user['level_id']}")[0];
              
       //解析代理数据
       	$agent = json_decode($agentgroup['authority'], true)[$module_name];
        //解析数据
        $authority = json_decode($group['authority'], true)[$module_name];
      	$sjid=$user['level_id'];
        if (!is_array($group) || $group['authority'] == -1 || $authority['open'] != 1) functions::json(-1, '用户组错误');
        // -------------------------
        // 获取需要回调的列表
        $order = $this->mysql->query('client_alipay_automatic_orders', "alipay_id={$alipay_id} and status=4 and callback_status=0");
        foreach ($order as $obj) {

            //$fees = $obj['amount'] * $authority['cost'];
       if($user['level_id']  ==  "0" ){

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

        $fees = $obj['amount'] * $agent;//手续费扣掉后的金额
        
         //开始为代理进行返点 
        $auser = $this->mysql->query('agent_rate', "uid={$obj['user_id']}")[0];
        $quser = $this->mysql->query("client_user", "id={$auser['parent_id']}")[0]; 
        $xysxf = $obj['amount'] * $agent;//现有手续费金额
        $yysxf = $obj['amount'] * $authority['cost'];//原有手续费金额
        $xjsxy = $xysxf - $yysxf;
        $shouyi= $quser['money'] + $xjsxy; 
        $this->mysql->update("client_user", ['money' =>$shouyi], "id={$auser['parent_id']}");
       	$cxdd = $this->mysql->query("agent_income_log", "uid=$sjid  ORDER BY id desc")[0]; 
                   // file_put_contents("order_id.txt", json_encode( $cxdd['order_id']));
        if($obj['out_trade_no'] == $cxdd['order_id']){
                    
                      
         }else{ 
         $create_log = $this->mysql->insert('agent_income_log', [
   		 'uid'         => $auser['parent_id'],
   		 'order_id'    => $obj['out_trade_no'],
    	 'money'       => $xjsxy,
         'zfmoney'     => $obj['amount'],
   		 'type'        => 1,
      	 'create_time' => time(),
         'update_time' => time(),
          'shname'      => $user['username'],
						
         ]);
          
        }


         
       }
          
          
          
          
            $isCall = 0 ;  //判断是否进行回调
            //查看订单是否已支付
            if ($obj['reached'] == 1) {
                $isCall = 1;

            }else{
                $user_balance = $user['balance'] - $fees; // 用户最终余额
                $user_balance = floatval($user_balance);

                if($user_balance >=0 ){
                    $isCall = 1;

                    $updateStatus = $this->mysql->update("client_user", ['balance' => floatval($user_balance),], "id={$user['id']}");
                    if($updateStatus !== false){
                        $this->mysql->update("client_alipay_automatic_orders", ['reached' => 1], "id={$obj['id']}");
                    }
                }
            }


            if ($isCall == 1) {

                // 开始回调、回调成功，再扣除手续费
                $http_build_data = http_build_query([
                    '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' => time(),
                    'type'          => 2,
                    'account_key'   => $user['key_id']
                ]);
                $result = callbacks::sendRequest($obj['callback_url'], $http_build_data);

                $callback_status =  (strtolower($result['msg']) == 'success') ? 1:0;

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

        //$this->mysql->update("client_alipay_automatic_account", ['active_time' => time()], "id={$alipay_id}");
        functions::json(200, ' [' . date("Y/m/d H:i:s", time()) . ']: 支付宝ID->' . $alipay_id . ' 异步通知成功');
        //-----------------------------
    }

}
