<?php
/**
 * Created by PhpStorm.
 * User: qin
 * Date: 2019/2/27
 * Time: 15:13
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Request;
use Illuminate\Support\Facades\DB;
use \SoapClient;
use \SoapVar;
use \SoapHeader;

class MgGameController extends Controller
{
	protected $SessionGUID = 'ae6b4f27-ffdf-4db1-b1d2-3f99031f6d14';
	protected $game_type;
    protected $user_prefix;
    protected $agent_host;
    protected $agent_username;
    protected $agent_pincode;
    protected $agent_gameinfo;
    protected $api_url1;
    protected $api_url2;
    protected $token       = '123321';
    protected $callbackurl;
    
    
    const cache_path = './';
    const PWDSTR = '2019';

    public function __construct()
    {
    	$set = new \App\Models\Rgame_setting();

        $where = array();
        $where[] = array('game_type','=','mggame');
        $set_obj  = $set->getGame($where);
        $json = json_decode($set_obj->extend, true);
        $this->agent_username = $set_obj->agent_name;
        $this->agent_pincode  = $set_obj->agent_pwd;
        $this->api_url1    = $json['host1'];//api1
        $this->api_url2    = $json['host2'] ?? '';//api2
        $this->paly_host1  = $json['host3'] ?? '';//play1
        $this->paly_host2  = $json['host4'] ?? '';//play2
        $this->callbackurl = $json['callbackurl'] ?? '';//返回地址
        $this->game_type   = $set_obj->game_type;
        $this->user_prefix = $set_obj->user_prefix;
        $this->agent_host  = $set_obj->agent_url;
        $this->actype = 1;
    }

    //获取投注记录
    public function getbetlist(){
    	$limit = Request::has ('limit') ? Request::get ('limit') : 10;
    	$page = Request::has ('page') ? Request::get ('page') : 1;
        $start_time = Request::has ('start_time') ? Request::get ('start_time') : '';
        $end_time = Request::has ('end_time') ? Request::get ('end_time') : '';
        $mggame =  new \App\Models\Mggame_betting_ogrbv();
        $where[] = array('GameEndTime','>=',strtotime($start_time.' 00:00:00'));
        $where[] = array('GameEndTime','<',strtotime($end_time.' 23:59:59'));

        $data = $mggame->getlist($where,$limit);
        foreach($data['data'] as $key => $val)
        {
            $data['data'][$key]['GameEndTime'] = date('Y-m-d H:i:s', $val['GameEndTime']);
        }
        return \App\Lib\DataTable\DataTable::init ()->toJson ($data['data'], $data['total']);

    }

    //更新流水
    public function updatebetlist(){
        $limit = Request::has ('limit') ? Request::get ('limit') : 1000;
        $page = Request::has ('page') ? Request::get ('page') : 1;
        $start_time = Request::has ('start_time') ? Request::get ('start_time') : date('Y-m-d');
        $end_time = Request::has ('end_time') ? Request::get ('end_time') : date('Y-m-d');
        $res = array();
        $this->IsAuthenticate();
        $id=$this->GetBetInfoDetails($start_time,$end_time,$limit);
        if(!empty($id)){
            $res = $this->GetReportResult($id,$page);
            if($res['code'] == 0){
                $indata =   [];
                $indatatwo =   [];
                foreach ($res['data'] as $key => $value) {
                   //获取本站用户名
                    $loainfo = \App\Models\Oggame_user::select('lo_name')->where('rp_name',$value['AccountNumber'])->where('game_type','mggame')->first();
                    if(!$loainfo || empty($loainfo->lo_name))return -50630201302;
                    //获取本站用户ID
                    $aid = \App\Models\Account::select('identity')->where('account',$loainfo->lo_name)->first();
                    if(!$aid || empty($aid->identity))return -50630200302;
                    $mginfo = \App\Models\Mggame_betting_ogrbv::where(['AccountNumber'=>$value['AccountNumber'],'GameEndTime'=>strtotime($value['Date'])])->first();
                    if(empty($mginfo)){
                        $indata[$key] = array(
                            'RowId' => md5(json_encode($value)),
                            'AccountNumber' => $value['AccountNumber'],
                            'Income' => $value['Income'],
                            'Payout' => $value['Payout'],
                            'WinAmount' => $value['WinAmount'],
                            'LoseAmount' => $value['LoseAmount'],
                            'ModuleId' => $value['ModuleId'],
                            'ClientId' => $value['ClientId'],
                            'DisplayGameCategory' => $value['GameType'],
                            'GameEndTime' => strtotime($value['Date']),
                            'account_identity'=>$aid->identity,
                            'account_name'=>$loainfo->lo_name,
                            'winloseamount'=>floatval($value['WinAmount'])+floatval($value['LoseAmount'])
                        );
                    }else{
                        $indatatwo = array(
                            'RowId' => md5(json_encode($value)),
                            'AccountNumber' => $value['AccountNumber'],
                            'Income' => $value['Income'],
                            'Payout' => $value['Payout'],
                            'WinAmount' => $value['WinAmount'],
                            'LoseAmount' => $value['LoseAmount'],
                            'ModuleId' => $value['ModuleId'],
                            'ClientId' => $value['ClientId'],
                            'DisplayGameCategory' => $value['GameType'],
                            'GameEndTime' => strtotime($value['Date']),
                            'account_identity'=>$aid->identity,
                            'account_name'=>$loainfo->lo_name,
                            'winloseamount'=>floatval($value['WinAmount'])+floatval($value['LoseAmount'])
                        );
                        $restt = \App\Models\Mggame_betting_ogrbv::where('id',$mginfo->id)->update($indatatwo);
                    }
                    
                }
            }
            if(!empty($indata)){
                $res = \App\Models\Mggame_betting_ogrbv::insert($indata);
                if($res<0)return -50630200402;
            }

        }

        return 1;
    }

    /**
	 * get SessionGUID
	 *
	 * Authenticates the agent by login name and password.
	 * The SessionGUID which retrieved via this method should be used in all other methods in theHeader
	 *
	 * @param $agentname
	 * @param $pincode
	 */
	public function IsAuthenticate(){
		
		$client = new SoapClient($this->api_url1.'?wsdl', array('compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP));

		$result = $client->IsAuthenticate(
            array(
                'loginName' => $this->agent_username,
                'pinCode' =>$this->agent_pincode
            )
        );

		if ($result->IsAuthenticateResult->ErrorCode == 0) {
			$this->SessionGUID = $result->IsAuthenticateResult->SessionGUID;
		}
		return $result;
	}
	

    //获取投注详情id
    public function GetBetInfoDetails($s_time='',$e_time='',$limit){
        $client = new SoapClient($this->api_url1.'?wsdl', array('compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP));
        $starttime  =   date("Y-m-d\TH:i:s",strtotime($s_time)) ?? date("Y-m-d\TH:i:s",strtotime("-1 day"));
        $endtime    =   date("Y-m-d\TH:i:s",strtotime($e_time)) ?? date("Y-m-d\TH:i:s");
        $data = [
            'dateFrom' => $starttime,
            'dateTo' => $endtime,
            'maxNumRowsPage' => $limit,
        ];
        $xml = '
            <AgentSession xmlns="https://entservices.totalegame.net">
                <SessionGUID>' . $this->SessionGUID . '</SessionGUID>
                <IPAddress>' . $_SERVER['REMOTE_ADDR'] . '</IPAddress>
            </AgentSession>
        ';
        $xmlvar = new SoapVar($xml, XSD_ANYXML);
        $header = new SoapHeader($this->api_url1, 'AgentSession', $xmlvar);
        $client->__setSoapHeaders($header);
        $result = $client->GetBetInfoDetails($data);
        $res=$result->GetBetInfoDetailsResult;
        return $res;
    }
    //获取投注列表
     public function GetReportResult($id,$page){
        $client = new SoapClient($this->api_url1.'?wsdl', array('compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP));
        $data = [
            'id' => $id,
            'nPage' => $page
        ];
        $xml = '
            <AgentSession xmlns="https://entservices.totalegame.net">
                <SessionGUID>' . $this->SessionGUID . '</SessionGUID>
                <IPAddress>' . $_SERVER['REMOTE_ADDR'] . '</IPAddress>
            </AgentSession>
        ';
        $xmlvar = new SoapVar($xml, XSD_ANYXML);
        $header = new SoapHeader($this->api_url1, 'AgentSession', $xmlvar);
        $client->__setSoapHeaders($header);
        $result = $client->GetReportResult($data);
        $res=$result->GetReportResultResult;
        if($res->ErrorCode ==0){
            $json =  json_decode(json_encode(simplexml_load_string($res->CurrentPageData->any)),TRUE);
            $da['code'] = 0;
            if(empty($json)){
            	$da['data'] = [];
            }else{
            	$da['data'] = $json['NewDataSet']['Table'];
            }
            $paging = json_decode(json_encode($res->Paging),TRUE);
            $da['count'] = count($da['data']);
            $da['extras'] =[];
            $da['msg'] ='';
        }
        return $da;
    }


}