<?php

namespace App\Sports\Controller;

use BaseController\Controller;

use Biz\Account\AccountManager;

/**
 * 赛事数据验证
 * Tank.peng
 * 2019/11/6
 */
class MatchVer extends Controller
{
    public function init() {
        $this->time = date('Y-m-d H:i:s',time());
        $this->accountManager = new AccountManager();
        $this->commonFunction =  C()->get('commonFunction');
    }

    /**
     * 验证 赛事赔率/比分 是否发生变更
     */
    public function VerOddsScore(){
        /*
        //拼装请求数据
        $data = [
            [
                'game_code'=>'zq',//球类代码
                'match_id'=>123,//赛事id
                'home_score'=>1,//主队得分/进球 如果是滚球让球
                'guest_score'=>2,//客队得分/进球 如果是滚球让球
                'odds_only'=>'34f8e550779c6446c05d2dd2bb969631'//赔率uuid
            ],
            [
                'game_code'=>'lq',
                'match_id'=>123,
                'home_score'=>1,
                'guest_score'=>2,
                'odds_only'=>'5c890c276384c40648760233194067b9'
            ]

        ];
        */

        //获取 查询数据
        $data_json = $_REQUEST['data'];
        // $token = $_REQUEST['token'];

        // if(empty($data_json)){
        //     Render('', '51029',lang('Errors','Api')->get('error-51029'));
        // }

        //验证用户token
        // $this->getAgent($token);

        //数据转arr
        $data_arr = json_decode($data_json,true);
        if(empty($data_arr)) Render('', '10030', lang('Errors','Sports')->get('error-10030'));
        //循环处理 根据球类分组
        //足球 赛事数据
        $zq_data = [];
        //篮球 赛事数据
        $lq_data = [];
        //网球 赛事数据
        $wq_data = [];
        //棒球 赛事数据
        $bq_data = [];
        foreach($data_arr as $k=>$v){
            //序号 赋值
            $v['sort'] = $k;
            //状态 默认0 待处理 1正常 2赛事状态异常  3赔率异常 4赛事比分有更新
            $v['status'] = 1;
            //异常提示
            $v['ver_mark'] = '正常';
            //足球
            if($v['game_code'] == 'zq'){
                $zq_data[] = $v;
            }
            //篮球
            if($v['game_code'] == 'lq'){
                $lq_data[] = $v;
            }
            //网球
            if($v['game_code'] == 'wq'){
                $wq_data[] = $v;
            }
            //棒球
            if($v['game_code'] == 'bq'){
                $bq_data[] = $v;
            }
            $data_arr[$k] = $v;
        }
        //处理 足球
        $zq_odd_err = [];
        if(!empty($zq_data)){
            $zq_odd_err = $this->verOddsData('zq',$zq_data);
        }
        //处理 篮球
        $lq_odd_err = [];
        if(!empty($lq_data)){
            $lq_odd_err = $this->verOddsData('lq',$lq_data);
        }
        //处理 网球
        $wq_odd_err = [];
        if(!empty($wq_data)){
            $wq_odd_err = $this->verOddsData('wq',$wq_data);
        }
        //处理 棒球
        $bq_odd_err = [];
        if(!empty($bq_data)){
            $bq_odd_err = $this->verOddsData('bq',$bq_data);
        }

        //合并各球类异常投注项
        $all_err = array_merge($zq_odd_err,$lq_odd_err,$wq_odd_err,$bq_odd_err);


        //如果有异常投注数据
        if(!empty($all_err)){
            //合并 投注赔率数据
            foreach($data_arr as $k=>$v){
                foreach($all_err as $kk=>$vv){
                    if($v['sort'] == $vv['sort']){
                        $data_arr[$k] = $vv;
                    }
                }
            }
        }else{
            $data_arr = 'ok';
        }
              
        //验证比分是否发生变化
        Render($data_arr, '1', lang('Tips','Sports')->get('success'));
    }
    
    /**
     * 验证投注内容 
     */
    public function verOddsData($game_code,$oddsData){
        //获取model
        $getModels = $this->commonFunction->getModels($game_code);
        //获取赛事id
        $match_ids = array_column($oddsData,'match_id');
        //获取赔率odds_only
        $odds_onlys =  array_column($oddsData,'odds_only');
        //比分正常 投注项
        $score_pass = [];
        //比分异常 投注项
        $score_err = [];
        //玩法赔率正常 投注项
        $odds_pass = [];
        //玩法赔率 异常 投注项
        $odds_err = [];
        //赛事状态异常的 投注项
        $status_err = [];
        //赛事状态正常的 投注项
        $status_pass = [];

        //根据赛事id 获取赛事状态
        $match_status = $this->getMatchStatus($match_ids,$getModels);
        //验证赛事状态是否异常
        if(!empty($match_status)){
            
            foreach($match_status as $k=>$v){
                foreach($oddsData as $kk=>$vv){
                    if($v['match_id'] == $vv['match_id'] and $v['status'] > 1){
                        $vv['status'] = 3;//赛事状态异常
                        $vv['ver_mark'] = '玩法盘口已关闭';
                        $status_err[] = $vv;
                        //排除当前投注项
                        unset($oddsData[$kk]);
                    }
                }
            }

            //当前正常投注项
            $status_pass = $oddsData;
        }

         //如果 还有投注项 验证玩法赔率
         if(!empty($status_pass)){
            //根据赔率uuid 验证是否存在
            $odds_data = $this->getOdds($odds_onlys,$getModels);
           
            foreach($status_pass as $k=>$v){
                if(!empty($odds_data)){
                    foreach($odds_data as $kk=>$vv){
                        if($v['odds_only'] == $vv['odds_only']){
                            $odds_pass[] = $v;
                            //排除当前投注项
                            unset($status_pass[$k]);
                        }
                    }
                }
            }

            //赋值异常 投注
            if(!empty($status_pass)){
                foreach($status_pass as $k=>$v){
                    $v['status'] = 4;//赔率数据异常
                    $v['ver_mark'] = '赔率已更新';
                    $odds_err[] = $v;
                }
            }
        }

        //如果 还有投注项 验证赛事比分
        if(!empty($odds_pass)){
            //根据赛事id 获取赛事比分
            $match_score = $this->getMatchScore($match_ids,$getModels,$game_code);
            foreach($odds_pass as $k=>$v){
                foreach($match_score as $kk=>$vv){
                    //获取异常
                    if($v['match_id'] == $vv->match_id ){
                        if($v['home_score'] != $vv->home_score || $v['guest_score'] != $vv->guest_score){
                            $v['status'] = 2;//比分数据异常
                            $v['ver_mark'] = '比分发生变化';
                            $score_err[] = $v;
                            unset($odds_pass[$k]);
                        }
                    }
                }
            }

            //赋值正常 投注
            $score_pass = $odds_pass;
        }
        //合并以上所有异常
        $score_err = [];
        $all_err = array_merge_recursive($status_err,$odds_err,$score_err);
        return $all_err;
    }

    /**
     * 获取各球类 指定赛事 状态
     */
    public function getMatchStatus($match_ids,$getModels){
        
        $match_model = $getModels['model_match'];
        $match_status = lm($match_model, 'Sports')
            ->select('id as match_id','status')
            ->whereIn('id',$match_ids)
            ->get()
            ->toArray();

        return $match_status;
    }

    /**
     * 获取各球类 指定赛事 比分
     */
    public function getMatchScore($match_ids,$getModels,$game_code){

        $match_ids_str = implode(",", $match_ids);
        $result_record = $getModels['model_result_record'];

         //如果是网球
         if($game_code == 'wq'){
            $sql = "select a.match_id,a.home_player_score as home_score,a.guest_player_score as guest_score,a.match_time as a_time,a.match_process,a.result_mark from $result_record a,
(select match_id,max(id) id from $result_record where match_id IN ($match_ids_str) group by match_id)b
where a.match_id = b.match_id and a.id = b.id ";
        }else
        //如果是棒球
        if($game_code == 'bq' || $game_code == 'lq'){
            $sql = "select a.match_id,a.home_score,a.guest_score,a.match_time as a_time,a.match_process,a.result_mark from $result_record a,
(select match_id,max(id) id from $result_record where match_id IN ($match_ids_str) group by match_id)b
where a.match_id = b.match_id and a.id = b.id ";
        }else{
            //其他球类
            $sql = "select a.match_id,a.home_score,a.guest_score,a.match_time as a_time,a.match_process from $result_record a,
(select match_id,max(id) id from $result_record where match_id IN ($match_ids_str) group by match_id)b
where a.match_id = b.match_id and a.id = b.id ";
        }
        //查询 赛事结果记录最新的一条
        $match_result_record = S ('DB')->select ($sql);

        return $match_result_record;
    }

    /**
     * 获取存在赔率
     */
    public function getOdds($odds_onlys,$getModels){
        $model_odds = $getModels['model_odds'];

        $odds_data = lm($model_odds,'Sports')
            ->select('odds_only')
            ->whereIn('odds_only',$odds_onlys)
            ->get()
            ->toArray();

        return $odds_data;
    }

    /**
     * token获取用户详情
     */
    public function getAgent($token = '') {
        $checkToken = $this->accountManager->checkEffectiveTime($token);
        if ($checkToken['status'] != 1) {
            Render($checkToken['data'], $checkToken['status'], lang('commons')->get('user does login'));
        };
    }
}




