<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/25
 * Time: 14:10
 */

namespace Biz\Settlement;
set_time_limit(600);
ini_set('memory_limit', '256M');


class SettlementSql
{

    //用户的期末基本资料表 [uid]['account'=>$obj,'detail'=>$obj];
     public  $AccountArrays = []  ;

     //buy_match 里batch_id 相同的数据
     public  $MatchBatchIdArrays = [] ;

     //buy_str 批次号相同的记录
    public  $BuyStrBatchIdArrays = [] ;

    //所有比赛场次号相同的记录
    public  $AllMatchIdArrays = [];

    //比赛结束消息通知模型
    public  $ComendNoticModel = null  ;

    //返回的sql数组
    private  $sqlArray = [] ;

    public $gameType = '' ;  //类型
    public $resultId = 0 ; //比赛最终结果ID
    public $resultModel = null ; //比赛最终结果对像MODEL
    public $resultRecords = [] ; //比赛中间结果对像数组;

    //类型映射
    public $gameAllMap = [
        'zq'=>'ZqRule',
        'lq'=>'LqRule',
        'wq'=>'WqRule',
        'bq'=>'BqRule',
    ];
    private  $AdapterObj = null ;

    private   $RefClass = null  ;


    public function   doRun(){


        try {
            _beginTransaction();

            $ComendNoticModel = $this->getComendNoticeModel();
            if (!$ComendNoticModel) {
                _commit();
                return  $this->makeData();
            }
            $this->writeStatusBegin($ComendNoticModel);

            $allmatchs = $this->getAllMatchIdArrays($ComendNoticModel->game_code, $ComendNoticModel->match_id, 2);
            $this->setAdapterObj( $ComendNoticModel->game_code );
            $this->RefClass = new  \ReflectionClass(  $this->setAdapterObj ) ;
            $this->getCompResult($ComendNoticModel->game_code,$ComendNoticModel->match_id);


            if (!$allmatchs) {
                $this->writeStatusEndOk($ComendNoticModel);
                _commit();
                return  $this->makeData();
            }

            foreach ($allmatchs  as $buymatchmodel){
                    $this->doSettlement($buymatchmodel);
            }

            _commit();
            return  $this->makeData();

        }catch (\Exception $e){
            _rollBack();
            return $this->makeData(0,'false',['msg'=>$e->getMessage(),'code'=>$e->getCode()]) ;

        }

    }


    //拼装  逻辑 sql;
    private  function  doSettlement($model){
        $fun = $model->odds_code ;
        if ( $this->RefClass->hasMethod( $fun)){
                $winorfalse = $this->AdapterObj->$fun($model,$this->resultModel,$this->resultRecords);
                $this->makesql_up_buymatch_winorfalse($model->id,$winorfalse,date("Y-m-d H:i:s"));
                if ($winorfalse == -1){
                    $this->masql_up_buymatch_false($model->batch_id);
                }






        }else{
            throw  new  \Exception('找不到此玩法的胜负规则逻辑!',4005);
        }
    }


    private function  makesql_up_buymatch_winorfalse($id,$result,$utime){
        $sql = " update  money_buy_match  set  result=$result,utime=$utime  where id=$id  limit 1";
        $this->sqlArray[] = $sql;
        return true;
    }
    private function masql_up_buymatch_false($batch_id){
        $uptime = date("Y-m-d H:i:s");
        $sql = " update  money_buy_match  set  result=-1 ,utime=$uptime,status=1  where batch_id=$batch_id  ";
        $this->sqlArray[] = $sql;

        $sql =  "update  money_buy_str  set   settle_status=1,game_status=3 ,wait_match_num=0  where  batch_id=$batch_id " ;
        $this->sqlArray[] = $sql;

        return true ;
    }





    private  function  setAdapterObj($game_type){

        if ( isset($this->gameAllMap)){  throw  new \Exception('赛事类型错误',4002);   return false;  }

        switch ($game_type){
            case 'bq':
                C()->set('BqRule','\Biz\Settlement\Adapter\BqRule');
                $this->AdapterObj = C()->get('BqRule');
                break;
            case  'lq':
                C()->set('LqRule','\Biz\Settlement\Adapter\LqRule');
                $this->AdapterObj = C()->get('LqRule');
                break;
            case  'wq':
                C()->set('WqRule','\Biz\Settlement\Adapter\WqRule');
                $this->AdapterObj = C()->get('WqRule');
                break;
            case  'zq':
                C()->set('ZqRule','\Biz\Settlement\Adapter\ZqRule');
                $this->AdapterObj = C()->get('ZqRule');
                break;
        }
        return  true ;
    }


    //返回数据
    private function  makeData($status=1,$message='success',$data=''){
        return [
            'status' => $status ,
            'message' =>$message,
            'data' => $data ,
        ] ;
    }

    //写处理状态
    public function  writeStatusBegin($comendnticeModel){
        $comendnticeModel->status = 1 ;
        $comendnticeModel->pupdatetime = date("Y-m-d H:i:s");
        $comendnticeModel->pcount ++ ;
        $comendnticeModel->logs = 'begin|';
        $ret = $comendnticeModel->save();
        return  $ret;
    }

    //写处理状态结束
    public function  writeStatusEndOk($comendnticeModel){
        $comendnticeModel->status = 4 ;
        $comendnticeModel->pret = 1 ;
        $comendnticeModel->puodateendtime = date("Y-m-d H:i:s");
        $comendnticeModel->logs = $comendnticeModel->logs.'end ok';
        $ret = $comendnticeModel->save();
        return  $ret;
    }




    public  function   getComendNoticeModel(){
            $ret = lm('Comendnotice','Commons')->wherer('status',0)->order('id','asc')->first();
            $this->ComendNoticModel = $ret;
            return $ret;
    }


    public function  getAllMatchIdArrays( $type,$matchid ,$bet_type=2,$result = 0 ){
            $ret = lm('Money_buy_match','Commons')->where(['game_code'=>$type,'match_id'=>$matchid,'bet_type'=>$bet_type,'result'=>$result])->find();
            $this->AllMatchIdArrays = $ret;
            return $ret;
    }


    public function  getUserInfo($account_name){
         if (isset($this->AccountArrays[$account_name])){
             return $this->AccountArrays['$account_name'];
         }

         $accountModel = lm('Account','Commons')->where(['account',$account_name])->first();
         if (!$accountModel){
             throw  new   \Exception('查无此用户数据account='.$account_name,41002);
         }

         $detailModel = lm('Account_detailed','Commons')->where(['account_identity',$accountModel->identity])->first();
         if (!$detailModel){
             throw  new   \Exception('查无此用户数据account_detail='.$accountModel->identity,41002);
         }
         $ret = [
             'account'=>$detailModel,
             'detail' => $detailModel ,
         ];
         $this->AccountArrays[$account_name] = $ret ;
         $this->AccountArrays[$accountModel->identity] = $ret ;

         return $ret;
     }


    public function  GetMatchBatchIdArrays($batch_id){
            if (isset($this->MatchBatchIdArrays[$batch_id])){
                return   $this->MatchBatchIdArrays[$batch_id];
            }
            $all = lm("Money_buy_match")->getByBatchId($batch_id);
            if (!$all) {
                throw  new  \Exception('无效的Money_buy_str->batch_id='.$batch_id , 41001);
            }
            $this->MatchBatchIdArrays[$batch_id] = $all ;
            return $all ;
    }


    public function  GetBuyStrBatchIdArrays($batch_id){

        if (isset($this->BuyStrBatchIdArrays[$batch_id])){
            return   $this->BuyStrBatchIdArrays[$batch_id];
        }
        $all = lm("Money_buy_str")->getByBatchId($batch_id);
        if (!$all) {
            throw  new  \Exception('无效的Money_buy_str->batch_id='.$batch_id , 41001);
        }
        $this->BuyStrBatchIdArrays[$batch_id] = $all ;
        return $all ;

    }


    //得到比赛最终结果记录 和 中间结果记录
    public function  getCompResult($type,$match_id){
        $model = null ;
        switch ($type){
            case 'bq':
                $model = lm('St_bq_result','Commons')->where('match_id',$match_id)->first();
                $models = lm('St_bq_result_record','Commons')->where('match_id',$match_id)->find();
                break;
            case  'lq':
                $model = lm('St_lq_resultn','Commons')->where('match_id',$match_id)->first();
                $models = lm('St_lq_result_record','Commons')->where('match_id',$match_id)->find();
                break;
            case  'wq':
                $model = lm('St_wq_result','Commons')->where('match_id',$match_id)->first();
                $models = lm('St_wq_result_record','Commons')->where('match_id',$match_id)->find();
                break;
            case  'zq':
                $model = lm('St_zq_result','Commons')->where('match_id',$match_id)->first();
                $models = lm('St_zq_result_record','Commons')->where('match_id',$match_id)->find();
                break;
        }
        if (empty($model)){
            throw  new   \Exception('没找到比赛结果记录match_id_'.$type.'-'.$match_id,4007);
            return false;
        }

        $this->resultModel = $model;
        $this->resultRecords = $models ;

        $ret = [
            'result' => $model,
            'records' => $models ,
        ];
        return $ret;

    }


}