<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/12
 * Time: 9:32
 */

namespace Biz\Game;

use  Biz\Account\AccountManager;
use  Biz\Game\TranferMoneyLogic;
use  App\Commons\Model\Wagent_clientgame_log as Wagent_clientgame_logModel;
use  Illuminate\Database\Capsule\Manager as DB;
use Biz\Game\SportbetRecordLogic ;



class GameLogic
{
    private $paras = [] ;
    private $userKey = '' ;
    private $wagetnModel = null ;

    public function  __construct($paras,$userKey,$wagentModel)
    {
        $this->paras = $paras;
        $this->userKey = $userKey;
        $this->wagetnModel =  $wagentModel ;
    }


    //返回数据
    private function  makeret($status=1,$msg='success',$datas=[]){
        return [
            'status'=>$status,
            'msg'=>$msg,
            'datas'=>$datas
        ];
    }

    //CheckAccountIsExist（账户是否存在）
    public function  CheckAccountIsExist(){

        $username= isset($this->paras['username']) ?  trim($this->paras['username']) : '';
        if (empty($username)){
            return $this->makeret(0,'请求参数缺失','key_error');
        }
        $username = $this->wagetnModel->agent_pre.$username;

        $ac = new AccountManager();
        $ret = $ac->getAccount($username);
        if ($ret){
            return $this->makeret(1,'success',1);
        }else{
            return $this->makeret(1,'success',0);
        }

    }


    //CheckAndCreateAccount（检测并创建游戏帐户）
    public function CheckAndCreateAccount(){

        $username = isset($this->paras['username']) ?  trim($this->paras['username']) : '';
        $password  = isset($this->paras['password']) ?  trim($this->paras['password']) : '' ;

        $remark = [
            'moneysort'=>'',
            'limitvideo'=>0,
            'limitroulette'=>0,
        ];
        $remark['moneysort'] = isset($this->paras['moneysort']) ?  trim($this->paras['moneysort']) : '' ;
        $remark['limitvideo'] = isset($this->paras['limitvideo']) ?  intval($this->paras['limitvideo']) : 0;
        $remark['limitroulette'] = isset($this->paras['limitroulette']) ? intval($this->paras['limitroulette']) : 0 ;
        $remark =   json_encode($remark);

        if (empty($username)   ||  empty($password) ){
            return $this->makeret(0,'请求参数缺失','key_error');
        }

        $username = $this->wagetnModel->agent_pre.$username;
        $ac = new AccountManager();
        $userInfo = $ac->getAccount($username);
        if ($userInfo){
            return $this->makeret(1,'success','1');
        }

        if (!$this->nameCheck($username)){
            return $this->makeret(0,'false',3);
        }

        if (!$this->passCheck($password)){
            return $this->makeret(0,'false',2);
        }

        $wagent_name = isset($this->paras['agent']) ?  $this->paras['agent'] : '';
        $postdatas = [
            'account' => $username,
            'password' => $password,
            'again_password' => $password,
            'name' =>  $username,
            'phone' => uniqid('agent_'),
            'remark' => $remark,
            'wagent_name' => $wagent_name,
        ];
        $ac = new AccountManager();
        $ret = $ac->register($postdatas);

        if (isset($ret['status'])  &&  $ret['status']==1){
            return $this->makeret(1,'success','1');
        }else{
            $errormsg = isset($ret['msg']) ? $ret['msg'] :  'false' ;
            return $this->makeret(0,$errormsg,'0');
        }

    }
    private function  nameCheck($name){
        if (mb_strlen($name) >= 32){
            return false;
        }
        return true;
    }


    private function passCheck($pass){
        $skip = ['\'','"','\\','/','>','<','&','#','--','%','?','$',' '] ;
        foreach ($skip as $val){
            if  ( stripos($pass,$val) !== false ){
                return false;
            }
        }
        return true;
    }


    //GetBalance（查询余额）
    public function GetBalance(){

        $accountModel= $this->accountAndPassCheck();
        $account_identity = $accountModel->identity;

        $parentinfo = lm('account_detailed', 'commons')->where('account_identity', $account_identity)->first();

        if (empty($parentinfo)) {
            return $this->makeret(1,'账号记录不存在','0');
        }
        return $this->makeret(1,'success',$parentinfo->cash) ;

    }


    public function  accountAndPassCheck(){
        $username= isset($this->paras['username']) ?  trim($this->paras['username']) : '';
        $password =  isset($this->paras['password']) ?  trim($this->paras['password']) : '';

        if (empty($username) || empty($password) ){
            $ret =  $this->makeret(0,'请求参数缺失','key_error');
            Render($ret['datas'],$ret['status'],$ret['msg']);
        }

        $username = $this->wagetnModel->agent_pre.$username;
        $ac = new AccountManager();
        $account = $ac->getAccount($username);
        if (!$account){
            $ret = $this->makeret(0,'账号不存在','account_no_exist');
            Render($ret['datas'],$ret['status'],$ret['msg']);
        }

        $account_identity = $account->identity;
        $passCheckret = VerPassword($account_identity,$password);
        if (!$passCheckret){
            $ret =  $this->makeret(0,'密码有误','key_error');
            Render($ret['datas'],$ret['status'],$ret['msg']);
        }
        return  $account ;
    }



    //TransferCredit（转帐）
    public function TransferCredit(){

        $accountModel = $this->accountAndPassCheck();
        if ($accountModel->status !=1){
            $ret = $this->makeret(0,'false','userStatus false!') ;
            return $ret;
        }

        $tlogc = new  TranferMoneyLogic( $accountModel,$this->paras,$this->wagetnModel );
        $ret = $tlogc->dorun();

        return $ret;

    }


    //ConfirmTransferCredit（查询转帐）
    public function  ConfirmTransferCredit(){

        $accountModel = $this->accountAndPassCheck();


        $billno =  isset($this->paras['billno']) ?  trim($this->paras['billno']) : '';
        if (empty($billno)){
            $ret = $this->makeret(0,'billno error','0') ;
            return $ret;
        }

        $type =  isset($this->paras['type']) ?  strtoupper(trim($this->paras['type'])) : '';
        if (empty($type) || !in_array($type,['IN','OUT']) ){
            $ret = $this->makeret(0,'type error','0') ;
            return $ret;
        }

        $where = [
            'account_indent' => $accountModel->identity,
            'agent_name' => $this->wagetnModel->agent_name,
            'type' => $type,
            'billno' => $billno
        ];
        $model = lm('Money_transfer','Commons')->where( $where )->first();
        if ($model){
            $ret = $this->makeret(1,'success',1);
            return $ret;
        }else{
            $ret = $this->makeret(0,'false',0);
            return $ret;
        }

    }

    //TransferGame（进入游戏）(记录登陆日志，并自动登陆一次,返回用户登陆信息)
    public function TransferGame(){

        $this->accountAndPassCheck();
        $datas = [
            'agent_name' => $this->paras['agent'],
            'domain' => isset($this->paras['domain']) ?  trim(  $this->paras['domain'] ) : '',
            'userame' => $this->wagetnModel->agent_pre.$this->paras['username'],
            'gametype' =>  isset($this->paras['gametype']) ?  trim(  $this->paras['gametype'] ) : '',
            'gamekind' =>  isset($this->paras['gamekind']) ?  trim(  $this->paras['gamekind'] ) : '',
            'iframe' =>  isset($this->paras['iframe']) ?  intval(trim(  $this->paras['iframe'] )) : -1 ,
            'platformname' =>  isset($this->paras['platformname']) ?  trim(  $this->paras['platformname'] ) : '',
            'lang' =>  isset($this->paras['lang']) ?  trim(  $this->paras['lang'] ) : '',
            'ip'=> GETIP(),
        ];
        $model = new Wagent_clientgame_logModel();
        $ret = $model->insert($datas);
        if ( $ret ){
            $username = $this->wagetnModel->agent_pre.$this->paras['username'];
            $ac = new AccountManager();
            $ret2 = $ac->login($username , $this->paras['password']);

            if ( isset($ret2['status']) &&  $ret2['status']==1 && isset( $ret2['data']['0']['token'] ) ){
                $t_d = $ret2['data']['0'];
                $token = urlencode(json_encode(['img_url'=>$t_d['img_url'],'name'=>$t_d['name'],'token'=>$t_d['token'],'cash'=>$t_d['cash']],256));
                return $this->makeret(1,$ret2['msg'],['ret'=>0,'token'=>$token,'url'=>'http://'.$_SERVER['HTTP_HOST'].'/m/jump.html?token='.$token]);
            }else{
                return $this->makeret(0,'false',0);
            }

        }else{
            return $this->makeret(0,'false',0);
        }

    }


    //GetReport（获取报表数据）
    public function   GetReport(){
        $this->accountAndPassCheck();
        $datetart = isset($this->paras['datestart']) ? trim($this->paras['datestart']) : '';
        $dateends = isset($this->paras['dateend']) ? trim($this->paras['dateend']) : '';
        if (empty($datetart) ||  empty($dateends)){
            return  $this->makeret(0,'begin or endtime is empty',0);
        }
        $retstr = '/^(\d{4}-\d{2}-\d{2})$/';
        if ( !preg_match($retstr,$datetart) || !preg_match($retstr,$dateends)){
            return  $this->makeret(0,'date fromat error',0);
        }
        $username = $this->wagetnModel->agent_pre.$this->paras['username'];
        $ret = $this->getMoneyBuyData($username ,$datetart , $dateends );

        $retlast['sports']['UserName'] = $this->paras['username'];
        $retlast['sports']['BettingTime'] = intval($ret['counts']);
        $retlast['sports']['BettingAmount'] = intval($ret['money']);
        $retlast['sports']['BettingEffectiveAmount'] = intval($ret['prize_money']);
        $retlast['sports']['BettingLoseWin'] = intval($ret['money']  -  $ret['prize_money']) ;

        return $this->makeret(1,'success',$retlast);
    }
    //获取某人体育游戏的统计数据
    public  function   getMoneyBuyData($account,$databegin,$dataend){
        $db = $GLOBALS['DB'] ;
        $ret1 = $db->select("select  count(id) as counts,sum(money) as money, sum(prize_money) as  money_buy   from  money_buy_simplex  where account_name=:account and  status in (1,2) and  money_time>=:timebegin and money_time<=:timeend  group by account_name ;",['account'=>$account,'timebegin'=>$databegin,'timeend'=>$dataend]);
        $ret2 = $db->select("select  count(id) as counts,sum(money) as money, sum(prize_money) as  money_buy   from  money_buy_str  where account_name=:account and  status in (1,2) and  money_time>=:timebegin and money_time<=:timeend  group by account_name ;",['account'=>$account,'timebegin'=>$databegin,'timeend'=>$dataend]);

        $ret = ['counts'=>0,'money'=>0,'prize_money'=>0] ;
        if ($ret1){
            $ret['counts'] += $ret1['0']['count'];
            $ret['money'] += $ret1['0']['money'];
            $ret['prize_money'] += $ret1['0']['prize_money'];
        }

        if ($ret2){
            $ret['counts'] += $ret2['0']['count'];
            $ret['money'] += $ret2['0']['money'];
            $ret['prize_money'] += $ret2['0']['prize_money'];
        }

        return $ret;
    }



    // GetCashTrade（转帐记录）
    public function   GetCashTrade(){

        $billno = isset($this->paras['billno']) ?  $this->paras['billno'] : '' ;
        if (empty($billno)){
            $ret = $this->makeret(0,'billno empty',0) ;
            return $ret;
        }

        $moneyTransferModel = lm('Money_transfer','Commons')->where(['agent_name'=>$this->wagetnModel->agent_name,'billno'=>$billno])->first();
        if (empty( $moneyTransferModel )){
            $ret = $this->makeret(0,'no data',0) ;
            return $ret;
        }
        $AccountArray= lm('Account','Commons')->getinfo($moneyTransferModel->account_indent,2);
        if (empty($AccountArray) ||  !is_array( $AccountArray )){
            $ret = $this->makeret(0,'account error',0) ;
            return $ret;
        }

        $datas = [
            'Billno'=>$moneyTransferModel->billno,
            'UserName'=>substr($AccountArray['account'],strlen($this->wagetnModel->agent_pre)),
            'OrderNumber'=>$moneyTransferModel->billno,
            'TradeAmount'=>$moneyTransferModel->tradeamount,
            'Balance'=>$moneyTransferModel->blance,
            'TradeType'=> trim($moneyTransferModel->type),
            'From'=>$moneyTransferModel->tfrom,
            'To'=>$moneyTransferModel->tto,
            'AddTime'=>$moneyTransferModel->addtime,
        ];

        $ret = $this->makeret(1,'success',$datas) ;
        return $ret;
    }


    //GetBettingRecordByVendor（真人游戏记录）
    public function   GetBettingRecordByVendor(){


        $ret = $this->makeret() ;
        return $ret;
    }


    //GetSportsBettingRecordByVendor（体育投注记录）
    public function   GetSportsBettingRecordByVendor(){
        $vendorid = isset($this->paras['vendorid']) ?  trim( $this->paras['vendorid'] ) : 0 ;
        $isjs = isset($this->paras['isjs']) ?  intval( $this->paras['isjs'] ) : 0 ;

        if (empty($vendorid)){
            $ret = $this->makeret(0,'paretn error',0) ;
            return $ret;
        }

        $logic = new  SportbetRecordLogic($this->wagetnModel , $vendorid , $isjs);
        $ret =  $logic->dorun();

        if (!$ret){
            return $this->makeret(0,'false',0);
        }else{
            return $this->makeret(1,'success', $ret) ;
        }
        return $ret;
    }

    //GetEleBettingRecord（电子投注记录）
    public function   GetEleBettingRecord(){


        $ret = $this->makeret() ;
        return $ret;
    }

    //GetFishBettingRecord（捕鱼王投注记录）
    public function   GetFishBettingRecord(){


        $ret = $this->makeret() ;
        return $ret;
    }

    //GetLotteryBettingRecord（彩票投注记录）
    public function   GetLotteryBettingRecord(){


        $ret = $this->makeret() ;
        return $ret;
    }

    //GetGameResult（游戏结果记录）
    public function   GetGameResult(){


        $ret = $this->makeret() ;
        return $ret;
    }

    //UpdateAccount（帐户密码更改）
    public function   UpdateAccount(){

        $username = isset($this->paras['username']) ?  trim($this->paras['username']) : '';
        $password  = isset($this->paras['password']) ?  trim($this->paras['password']) : '' ;

        if (empty($username)   ||  empty($password) ){
            return $this->makeret(0,'请求参数缺失','key_error');
        }

        $username = $this->wagetnModel->agent_pre.$username;
        $ac = new AccountManager();
        $userInfo = $ac->getAccount($username);
        if (!$userInfo){
            return $this->makeret(0,'false','key_error');
        }
        if ($userInfo->status != 1){
            return $this->makeret(0,'用户状态不正确','key_error');
        }

        $pwdData = GenPassword($password);
        $passdatas = [
            'account_password'=>$pwdData['password'],
            "encryption" => $pwdData['encryption'],
        ];

        $ret = lm('account_password', 'Commons')->where('account_identity',$userInfo->identity)->update($passdatas);

        if ($ret ){
            $ret = $this->makeret(1,'success',1) ;
        }else{
            $ret = $this->makeret(0,'false',0) ;
        }

        return $ret;
    }

    //GetSportVendorId（获取体育VendorId）
    public function   GetSportVendorId(){


        $ret = $this->makeret() ;
        return $ret;
    }


    //代理帮用户请求一次登陆操作,如果成功有用户有效token值
    public function AutoLogin(){
        $this->accountAndPassCheck();

        $username = $this->wagetnModel->agent_pre.$this->paras['username'];
        $ac = new AccountManager();
        $ret2 = $ac->login($username , $this->paras['password']);

        if ( isset($ret2['status']) &&  $ret2['status']==1 && isset( $ret2['data']['0']['token'] ) ){
            $t_d = $ret2['data']['0'];
            $token = urlencode(json_encode(['img_url'=>$t_d['img_url'],'name'=>$t_d['name'],'token'=>$t_d['token'],'cash'=>$t_d['cash']],256));
            return $this->makeret(1,$ret2['msg'],['ret'=>0,'token'=>$token,'url'=>'http://'.$_SERVER['HTTP_HOST'].'/m/jump.html?token='.$token]);
        }else{
            return $this->makeret(0,'false',0);
        }


    }



}