<?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 SettlementBase
{
     const  USER_WIN  = 1 ;   //用户赢钱
     const  USER_LOSE = -1;   //用户输钱
     const  USER_FLAT = 2 ;   //持平,用户钱原路返回

     public $match_id  = 0 ;     //比赛场次ID
     public $matchModel = null ;  //比赛场次Model对像

     public $lg_id = 0  ;    //联赛ID
     public $lgModel = null ;  //联赛Model对像

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

     public $buyArrays = [] ;   //订单记录表

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


    public  function __construct()
    {
        C()->set('BqRule','\Biz\Settlement\Adapter\BqRule');
        C()->set('LqRule','\Biz\Settlement\Adapter\LqRule');
        C()->set('WqRule','\Biz\Settlement\Adapter\WqRule');
        C()->set('ZqRule','\Biz\Settlement\Adapter\ZqRule');

        return true;
    }

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

    //开始结算处理
    public function  doSettlement(){
            $model = $this->getNoticeData();
            if ($model) {    return $this->makeData(1,'no data to process') ;  }

            try{
                _beginTransaction();
                $ret1 = $this->doInit($model->type,$model->competionid);
                if (!$ret1){   _rollBack(); return $this->makeData(0,'false_1') ;  }

                $ret2 = $this->writeStatusBegin($model);
                if (!$ret2){   _rollBack(); return $this->makeData(0,'false_2') ;  }

                $ret3 = $this->getOrdersByMatchid($this->gameType,$this->match_id);
                if (!$ret3){
                    //没有下单数据，本场赛事结算处理完毕
                    $this->writeStatusEndOk($model);
                    _commit();
                    return  $this->makeData();
                }

                $ret4 = $this->BatchModesResult($ret3);
                if (!$ret4){
                    _rollBack(); return $this->makeData(0,'false_4') ;
                }







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

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

    }


    //写处理状态
    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  getNoticeData($where = ['status'=>0]){
        $model = lm('Comendnotice','Commons')->where($where)->first();
        if (!$model){
            return false;
        }
        return $model ;
    }

    //实现结算功能
    public function   doInit($type,$match_id){
            if ( isset($this->gameAllMap)){  throw  new \Exception('赛事类型错误',4002);   return false;  }

            switch ($type){
                case 'bq':
                    $this->AdapterObj = C()->get('BqRule');
                    break;
                case  'lq':
                    $this->AdapterObj = C()->get('LqRule');
                    break;
                case  'wq':
                    $this->AdapterObj = C()->get('WqRule');
                    break;
                case  'zq':
                    $this->AdapterObj = C()->get('ZqRule');
                    break;
            }

            $this->gameType = $type ;
            $this->match_id = $match_id ;

            $this->getCompetitionData($type,$match_id);
            $this->getCompResult($type,$match_id);

            return true ;
    }

    //获取比赛数据模型
    public function  getCompetitionData($type,$match_id){

        $model = null ;
        switch ($type){
            case 'bq':
                $model = lm('St_bq_competition','Commons')->where('match_id',$match_id)->first();
                break;
            case  'lq':
                $model = lm('St_lq_competition','Commons')->where('match_id',$match_id)->first();
                break;
            case  'wq':
                $model = lm('St_wq_competition','Commons')->where('match_id',$match_id)->first();
                break;
            case  'zq':
                $model = lm('St_zq_competition','Commons')->where('match_id',$match_id)->first();
                break;
        }
        if (empty($model)){
            throw  new   \Exception('无效match_id_'.$type.'-'.$match_id,4004);
            return false;
        }

        $this->matchModel = $model;
        return $model ;
    }


    //查询此比较有下单记录
    public function  getOrdersByMatchid($type,$marchid){
            $modes = lm('Money_buy_match','Commons')->getByTypeMatch($type,$marchid);
            return $$modes;
    }

    //批量结算处理 [只处理状态]
    public function  BatchModesResult($type,$models){
             $pclass = $this->AdapterObj ;
             $RefClass = new  \ReflectionClass($pclass) ;
            foreach ($models as $model){
                  $oddscode = $model->odds_code;
                  if ( $RefClass->hasMethod($oddscode)){
                      $model->result  = $pclass->$oddscode($model,$this->resultModel,$this->resultRecords);
                      $model->utime = date("Y-m-d H:i:s");
                      $ret  = $model->save();
                      if (!$ret){
                          throw  new  \Exception('更新记录buy_match失败!',4006);
                      }
                      $this->getBuyDatas($model->order_id);

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






    //某个订单下面的所有比赛是否全部处理完成
    public function   OrderIsPressFinish($orderId){


    }


    //得到比赛最终结果记录 和 中间结果记录
    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;

    }

    //得到订单信息
    public function  getBuyDatas($orderId){
         if ( isset($this->buyArrays[$orderId]) ){
             return $this->buyArrays[$orderId];
         }

         $model = lm("Money_buy")->where(['order_id',$orderId])->first();
         if (!$model){
             throw new  \Exception('没有订单基本信息_'.$orderId, 4008);
         }

         $details = lm("Money_buy_detail")->where(['order_id',$orderId])->find();
         if (!$details){
             throw new  \Exception('没有订单detail信息_'.$orderId, 4009);
         }

         $ret = [
             'buy' =>$model ,
             'details' => $details ,
         ];

        $this->buyArrays[$orderId] = $ret  ;
        return $ret;
    }



}